aboutsummaryrefslogtreecommitdiffstats
path: root/stacks
diff options
context:
space:
mode:
authorsatish.karunanithi <satish.fdio@gmail.com>2018-08-13 19:39:55 +0530
committersatish.karunanithi <satish.fdio@gmail.com>2018-08-14 10:22:59 +0530
commit54f5a270c74c405d3bb0e15d5b69d6d0e1e96c49 (patch)
treea855ebf120dd46c50784c30a53a1bdf9aedea632 /stacks
parentbd6e75c243db1b384ba0882ecaf9063ec4cd70bd (diff)
Feat : LWIP integration part3
Change-Id: I62998963da110827a410287eed90a22da7ae4222 Signed-off-by: satish.karunanithi <satish.fdio@gmail.com>
Diffstat (limited to 'stacks')
-rw-r--r--stacks/lwip_stack/CMakeLists.txt115
-rw-r--r--stacks/lwip_stack/app_conf/module_config.json27
-rw-r--r--stacks/lwip_stack/app_conf/nStackConfig.json32
-rw-r--r--stacks/lwip_stack/app_conf/rd_config.json26
-rw-r--r--stacks/lwip_stack/build/.gitkeep0
-rw-r--r--stacks/lwip_stack/patch/.gitkeep0
-rw-r--r--stacks/lwip_stack/release/configure/ip_data.json31
-rw-r--r--stacks/lwip_stack/release/configure/nStackConfig.json32
-rw-r--r--stacks/lwip_stack/release/configure/network_data_tonStack.json32
-rw-r--r--stacks/lwip_stack/release/include/nstack_custom_api.h42
-rw-r--r--stacks/lwip_stack/release/lib64/.gitkeep0
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/arch/queue.c120
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/arch/sys_arch.c237
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/core/timeouts.c527
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/download_lwip.sh35
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/include/lwipopts.h39
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/include/opt.h2875
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/include/sys.h455
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/include/timeouts.h134
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/lwip/arch/atomic_32.h53
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/lwip/arch/cc.h82
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/lwip/arch/queue.h30
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/lwip/arch/sys_arch.h29
-rw-r--r--stacks/lwip_stack/release/lwip_helper_files/lwip/arch/win_minmax.h120
-rw-r--r--stacks/lwip_stack/release/script/nstack_fun.sh591
-rw-r--r--stacks/lwip_stack/release/script/nstack_var.sh63
-rw-r--r--stacks/lwip_stack/release/script/run_nstack_main.sh26
-rw-r--r--stacks/lwip_stack/release/script/run_nstack_master.sh29
-rw-r--r--stacks/lwip_stack/release/send_alarm.sh17
-rw-r--r--stacks/lwip_stack/release/start_nstack.sh124
-rw-r--r--stacks/lwip_stack/release/stop_nstack.sh49
-rw-r--r--stacks/lwip_stack/release/uninstall.sh34
-rw-r--r--stacks/lwip_stack/release/upgrade_nstack.sh452
-rw-r--r--stacks/lwip_stack/release_tar.sh86
-rw-r--r--stacks/lwip_stack/run_stackx.txt131
-rw-r--r--stacks/lwip_stack/src/CMakeLists.txt62
-rw-r--r--stacks/lwip_stack/src/alarm/CMakeLists.txt34
-rw-r--r--stacks/lwip_stack/src/alarm/alarm.c863
-rw-r--r--stacks/lwip_stack/src/alarm/alarm.h80
-rw-r--r--stacks/lwip_stack/src/alarm/alarm_api.h107
-rw-r--r--stacks/lwip_stack/src/include/nsfw_msg.h203
-rw-r--r--stacks/lwip_stack/src/include/nsfw_msg_api.h309
-rw-r--r--stacks/lwip_stack/src/include/nsfw_mt_config.h292
-rw-r--r--stacks/lwip_stack/src/include/nsfw_rti.h66
-rw-r--r--stacks/lwip_stack/src/io_adpt/CMakeLists.txt31
-rw-r--r--stacks/lwip_stack/src/io_adpt/dpdk.c2315
-rw-r--r--stacks/lwip_stack/src/maintain/CMakeLists.txt44
-rw-r--r--stacks/lwip_stack/src/maintain/fw_mt_config.c843
-rw-r--r--stacks/lwip_stack/src/maintain/nsfw_msg.c23
-rw-r--r--stacks/lwip_stack/src/maintain/nsfw_rti.c92
-rw-r--r--stacks/lwip_stack/src/nStackMain/CMakeLists.txt60
-rw-r--r--stacks/lwip_stack/src/nStackMain/main.c427
-rw-r--r--stacks/lwip_stack/src/sbr/CMakeLists.txt30
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_err.h191
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_index_ring.c212
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_index_ring.h61
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_protocol_api.h99
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_res_mgr.c88
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_res_mgr.h128
-rw-r--r--stacks/lwip_stack/src/sbr/sbr_socket.c1231
-rw-r--r--stacks/lwip_stack/src/tools/CMakeLists.txt22
-rw-r--r--stacks/lwip_stack/src/tools/dump_tool.c622
-rw-r--r--stacks/lwip_stack/src/tools/dump_tool.h81
-rw-r--r--stacks/lwip_stack/tools/CMakeLists.txt91
-rw-r--r--stacks/lwip_stack/tools/nping.c627
-rw-r--r--stacks/lwip_stack/tools/ntcpdump.c1368
-rw-r--r--stacks/lwip_stack/tools/tool_common.h243
-rw-r--r--stacks/lwip_stack/vagrant/Vagrantfile63
-rw-r--r--stacks/lwip_stack/vagrant/build.sh267
-rw-r--r--stacks/lwip_stack/vagrant/env.sh7
-rw-r--r--stacks/lwip_stack/vagrant/install_prereq.sh39
71 files changed, 17996 insertions, 0 deletions
diff --git a/stacks/lwip_stack/CMakeLists.txt b/stacks/lwip_stack/CMakeLists.txt
new file mode 100644
index 0000000..9f64af9
--- /dev/null
+++ b/stacks/lwip_stack/CMakeLists.txt
@@ -0,0 +1,115 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+CMAKE_MINIMUM_REQUIRED(VERSION 2.8.11)
+PROJECT(nStack)
+SET(CMAKE_C_COMPILER "gcc")
+SET(OS_RELEASE "" CACHE STRING "User-specified OS release.")
+SET(EXECUTABLE_PATH ${CMAKE_CURRENT_LIST_DIR}/release/bin)
+SET(LIB_PATH_STATIC ${PROJECT_BINARY_DIR})
+SET(LIB_PATH_SHARED ${CMAKE_CURRENT_LIST_DIR}/release/lib64)
+SET(NSTACKTOOLS_PATH ${CMAKE_CURRENT_LIST_DIR}/release/tools)
+SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIB_PATH_STATIC})
+SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_PATH})
+SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LIB_PATH_SHARED})
+
+
+MESSAGE(STATUS "Top dir is: " ${CMAKE_CURRENT_LIST_DIR})
+MESSAGE(STATUS "Static library dir: " ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY})
+MESSAGE(STATUS "Executable binary dir: " ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
+MESSAGE(STATUS "Shared library dir: " ${CMAKE_LIBRARY_OUTPUT_DIRECTORY})
+
+option(WITH_SECUREC_LIB "Option description" OFF)
+option(WITH_HAL_LIB "Option description" OFF)
+
+if(WITH_SECUREC_LIB)
+ add_definitions(-DSECUREC_LIB)
+endif()
+
+if(WITH_HAL_LIB)
+ add_definitions(-DHAL_LIB)
+endif()
+
+SET(post_compile "${PROJECT_BINARY_DIR}/post_compile.sh")
+FILE(WRITE ${post_compile} "#!/bin/bash\n")
+FILE(APPEND ${post_compile}
+"
+
+find ${CMAKE_CURRENT_LIST_DIR}/release/ -name \"*.sh\" -exec chmod +x {} \\;
+find ${CMAKE_CURRENT_LIST_DIR}/release/ -name \"*.py\" -exec chmod +x {} \\;
+ln -sfn ./run_nstack_main.sh ${CMAKE_CURRENT_LIST_DIR}/release/script/run_nstack.sh
+echo post compile process success.
+"
+)
+
+ADD_CUSTOM_TARGET(DPDK ALL COMMAND sh post_compile.sh)
+
+execute_process(
+ COMMAND cp -rf ${CMAKE_CURRENT_LIST_DIR}/../../release/include ${CMAKE_CURRENT_LIST_DIR}/src/
+ COMMAND cp ${CMAKE_CURRENT_LIST_DIR}/../../release/lib64/libnStackAPI.so ${CMAKE_CURRENT_LIST_DIR}/release/lib64/
+ COMMAND cp ${CMAKE_CURRENT_LIST_DIR}/../../release/lib64/libdmm_api.so ${CMAKE_CURRENT_LIST_DIR}/release/lib64/
+ COMMAND cp ${CMAKE_CURRENT_LIST_DIR}/../../build/libnStackMaintain.a ${CMAKE_CURRENT_LIST_DIR}/release/lib64/
+ COMMAND cp ${CMAKE_CURRENT_LIST_DIR}/../../build/libsocket.a ${CMAKE_CURRENT_LIST_DIR}/build/
+ COMMAND echo "stacklwip prepare ok"
+)
+execute_process(
+ COMMAND sh ${CMAKE_CURRENT_LIST_DIR}/release/lwip_helper_files/download_lwip.sh
+)
+
+ADD_DEFINITIONS(-D_GNU_SOURCE -DNSTACK_GETVER_VERSION="18.04")
+
+SET(JSON_C_SRC ${CMAKE_CURRENT_LIST_DIR}/../../thirdparty/json/json-c-0.12.1)
+INCLUDE(ExternalProject)
+ExternalProject_Add(
+ JSON
+ SOURCE_DIR ${JSON_C_SRC}
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND sh autogen.sh COMMAND sh ./configure --enable-static --with-pic
+ BUILD_COMMAND make -j 8
+ INSTALL_COMMAND cp -f .libs/libjson-c.a ${LIB_PATH_STATIC}/
+)
+
+SET(SECUREC_SRC ${CMAKE_CURRENT_LIST_DIR}/../SecureC/src)
+SET(SECUREC_SRC_H ${CMAKE_CURRENT_LIST_DIR}/../SecureC/include)
+
+if(WITH_SECUREC_LIB)
+INCLUDE(ExternalProject)
+ExternalProject_Add(
+ SECUREC
+ SOURCE_DIR ${SECUREC_SRC}
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND COMMAND make -j 8
+ INSTALL_COMMAND cp -f ${SECUREC_SRC}/../lib/libsecurec.so ${LIB_PATH_SHARED}/
+)
+endif()
+
+SET(GLOG_SRC ${CMAKE_CURRENT_LIST_DIR}/../../thirdparty/glog/glog-0.3.4)
+INCLUDE(ExternalProject)
+ExternalProject_Add(
+ GLOG
+ SOURCE_DIR ${GLOG_SRC}
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND autoreconf COMMAND sh configure CFLAGS=-fPIC CXXFLAGS=-fPIC
+ BUILD_COMMAND COMMAND make -j 8
+ INSTALL_COMMAND cp -f ${GLOG_SRC}/.libs/libglog.a ${LIB_PATH_STATIC}/
+)
+
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(lwip_src)
+ADD_SUBDIRECTORY(lwip_src/socket)
+ADD_SUBDIRECTORY(tools)
+#ADD_SUBDIRECTORY(thirdparty/rsrdma)
diff --git a/stacks/lwip_stack/app_conf/module_config.json b/stacks/lwip_stack/app_conf/module_config.json
new file mode 100644
index 0000000..a179ad4
--- /dev/null
+++ b/stacks/lwip_stack/app_conf/module_config.json
@@ -0,0 +1,27 @@
+{
+ "default_stack_name": "kernel",
+ "module_list": [
+ {
+ "stack_name": "kernel",
+ "function_name": "kernel_stack_register",
+ "libname": "./",
+ "loadtype": "static",
+ "deploytype": "1",
+ "maxfd": "1024",
+ "minfd": "0",
+ "priorty": "1",
+ "stackid": "0",
+ },
+ {
+ "stack_name": "stackx",
+ "function_name": "nstack_stack_register",
+ "libname": "libnstack.so",
+ "loadtype": "dynmic",
+ "deploytype": "3",
+ "maxfd": "1024",
+ "minfd": "0",
+ "priorty": "1",
+ "stackid": "1",
+ },
+ ]
+}
diff --git a/stacks/lwip_stack/app_conf/nStackConfig.json b/stacks/lwip_stack/app_conf/nStackConfig.json
new file mode 100644
index 0000000..3cc54c5
--- /dev/null
+++ b/stacks/lwip_stack/app_conf/nStackConfig.json
@@ -0,0 +1,32 @@
+{
+"cfg_seg_socket": [
+{
+ "socket_num": 8192,
+ "arp_stale_time": 300,
+ "arp_bc_retrans_num": 5
+}
+],
+"cfg_seg_log": [
+{
+ "run_log_size": 50,
+ "run_log_count": 10,
+ "mon_log_size": 10,
+ "mon_log_count": 10
+}
+],
+"cfg_seg_thread_pri": [
+{
+ "comment":"0:SCHED_OTHER, 1:SCHED_FIFO, 2:SCHED_RR",
+ "sched_policy": 0,
+ "thread_pri": 0
+}
+],
+"cfg_seg_path": [
+{
+ "stackpool_log_path": "/var/log/nStack",
+ "master_log_path": "/var/log/nStack",
+ "nstack_log_path": "/var/log/nStack",
+ "dpdk_log_path": "/var/log/nstack-dpdk"
+}
+]
+}
diff --git a/stacks/lwip_stack/app_conf/rd_config.json b/stacks/lwip_stack/app_conf/rd_config.json
new file mode 100644
index 0000000..38374bc
--- /dev/null
+++ b/stacks/lwip_stack/app_conf/rd_config.json
@@ -0,0 +1,26 @@
+{
+ "ip_route": [
+ {
+ "subnet": "192.168.1.1/24",
+ "type": "nstack-dpdk",
+ },
+ {
+ "subnet": "192.167.1.1/24",
+ "type": "nstack-kernel",
+ },
+ {
+ "subnet": "192.166.1.1/24",
+ "type": "nstack-kernel",
+ }
+ ],
+ "prot_route": [
+ {
+ "proto_type": "1",
+ "type": "nstack-dpdk",
+ },
+ {
+ "proto_type": "2",
+ "type": "nstack-kernel",
+ }
+ ],
+}
diff --git a/stacks/lwip_stack/build/.gitkeep b/stacks/lwip_stack/build/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/stacks/lwip_stack/build/.gitkeep
diff --git a/stacks/lwip_stack/patch/.gitkeep b/stacks/lwip_stack/patch/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/stacks/lwip_stack/patch/.gitkeep
diff --git a/stacks/lwip_stack/release/configure/ip_data.json b/stacks/lwip_stack/release/configure/ip_data.json
new file mode 100644
index 0000000..f29103e
--- /dev/null
+++ b/stacks/lwip_stack/release/configure/ip_data.json
@@ -0,0 +1,31 @@
+{
+ "containerID": "9112d2b6aa31",
+ "primary_port": "PortA",
+ "ports_list": [
+ {
+ "port_name": "PortA",
+ "ref_nic": [
+ "eth7"
+ ],
+ "mac": [
+ "00:54:32:19:3d:19"
+ ],
+ "net_name": "IDX-M",
+ "ip_cidr": ["192.168.1.207/24"],
+ "multicast_id": [
+ {
+ "group_id": "cast_group_1",
+ "group_ip": "239.0.0.1"
+ },
+ {
+ "group_id": "cast_group_2",
+ "group_ip": "239.0.0.2"
+ }
+ ],
+ "vlan_id": 42,
+ "vlan_inside": true,
+ "vxlan_id": -1,
+ "vxlan_inside": false
+ }
+ ]
+}
diff --git a/stacks/lwip_stack/release/configure/nStackConfig.json b/stacks/lwip_stack/release/configure/nStackConfig.json
new file mode 100644
index 0000000..3cc54c5
--- /dev/null
+++ b/stacks/lwip_stack/release/configure/nStackConfig.json
@@ -0,0 +1,32 @@
+{
+"cfg_seg_socket": [
+{
+ "socket_num": 8192,
+ "arp_stale_time": 300,
+ "arp_bc_retrans_num": 5
+}
+],
+"cfg_seg_log": [
+{
+ "run_log_size": 50,
+ "run_log_count": 10,
+ "mon_log_size": 10,
+ "mon_log_count": 10
+}
+],
+"cfg_seg_thread_pri": [
+{
+ "comment":"0:SCHED_OTHER, 1:SCHED_FIFO, 2:SCHED_RR",
+ "sched_policy": 0,
+ "thread_pri": 0
+}
+],
+"cfg_seg_path": [
+{
+ "stackpool_log_path": "/var/log/nStack",
+ "master_log_path": "/var/log/nStack",
+ "nstack_log_path": "/var/log/nStack",
+ "dpdk_log_path": "/var/log/nstack-dpdk"
+}
+]
+}
diff --git a/stacks/lwip_stack/release/configure/network_data_tonStack.json b/stacks/lwip_stack/release/configure/network_data_tonStack.json
new file mode 100644
index 0000000..7c059ef
--- /dev/null
+++ b/stacks/lwip_stack/release/configure/network_data_tonStack.json
@@ -0,0 +1,32 @@
+[
+ {
+ "cniVersion": "0.2.0",
+ "name": "IDX-M",
+ "multi_entry": "3",
+ "type": "nstack-dpdk",
+ "vlanID": 42,
+ "vlan_inside": true,
+ "ipam": {
+ "type": "canal-ipam",
+ "subnet": "192.168.1.1/24",
+ "gateway": "192.168.1.254",
+ "range-start": "192.168.1.198",
+ "range-end": "192.168.1.209",
+ "routes": [
+ {
+ "dst": "192.168.1.0/24",
+ "gw": "192.168.1.254"
+ }
+ ]
+ },
+ "args": {
+ "phynet": {
+ "ref_nic": [
+ "eth7"
+ ],
+ "bond_name": "",
+ "bond_mode": -1
+ }
+ }
+ },
+]
diff --git a/stacks/lwip_stack/release/include/nstack_custom_api.h b/stacks/lwip_stack/release/include/nstack_custom_api.h
new file mode 100644
index 0000000..e6cae1e
--- /dev/null
+++ b/stacks/lwip_stack/release/include/nstack_custom_api.h
@@ -0,0 +1,42 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef __NSTACK_CUSTOM_API_H__
+#define __NSTACK_CUSTOM_API_H__
+
+/*****************************************************************************
+* Prototype : create a custom socket ,when using this type .
+*****************************************************************************/
+#ifndef SOCK_NS_CUSTOM
+#define SOCK_NS_CUSTOM 0xf001
+#endif
+
+/*****************************************************************************
+* Prototype : setsockopt level type
+*****************************************************************************/
+enum
+{
+ NSTACK_SOCKOPT = 0xff02
+};
+
+/*****************************************************************************
+* Prototype : setsockopt optname type
+*****************************************************************************/
+enum
+{
+ NSTACK_SEM_SLEEP = 0X0001
+};
+#endif
diff --git a/stacks/lwip_stack/release/lib64/.gitkeep b/stacks/lwip_stack/release/lib64/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/stacks/lwip_stack/release/lib64/.gitkeep
diff --git a/stacks/lwip_stack/release/lwip_helper_files/arch/queue.c b/stacks/lwip_stack/release/lwip_helper_files/arch/queue.c
new file mode 100644
index 0000000..4916dae
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/arch/queue.c
@@ -0,0 +1,120 @@
+#include <pthread.h>
+#include "lwip/memp.h"
+#include "lwip/mem.h"
+
+#include "arch/queue.h"
+#include "lwip/sys.h"
+#include "nstack_log.h"
+#include "lwip/sockets.h"
+#include "stackx_spl_share.h"
+#include "lwip/api.h"
+#include "lwip/ip.h"
+#include <netif/sc_dpdk.h>
+
+err_t
+queue_push (queue_t * q, void *pmsg, int isTrypush)
+{
+ int pushRet;
+ // struct tcpip_msg* _msg = pmsg;
+
+ //enum tcpip_msg_type tcpip_type = TCPIP_MSG_MAX;
+ //struct new_api_msg* lo_newapimsg = NULL;
+ // enum api_msg_type api_type = NEW_MSG_API_MAX;
+ // struct netconn *lo_conn = NULL;
+ //u64_t tcp_tx_bytes = 0;
+ while (1)
+ {
+ pushRet = nsfw_mem_ring_enqueue (q->llring, pmsg);
+
+ switch (pushRet)
+ {
+
+ case -1:
+ NSSOC_LOGERR ("Box range check has failed]llring_a=%p, msg=%p",
+ q->llring, pmsg);
+ return ERR_MEM;
+
+ case 1:
+ return ERR_OK;
+
+ default:
+ if (isTrypush)
+ {
+ return ERR_MEM;
+ }
+ else
+ {
+ continue;
+ }
+ }
+ }
+}
+
+void *
+queue_pop (queue_t * q, u32_t * timeout, int isTryPop)
+{
+ void *pmsg;
+ int popRet;
+ int retVal;
+ u32_t ellapsetime = 0;
+// struct tcpip_msg* _msg;
+ struct timespec starttm = { 0 };
+ struct timespec endtm;
+ u32_t timeDiff;
+ if (*timeout != 0)
+ {
+ retVal = clock_gettime (CLOCK_MONOTONIC, &starttm);
+ if (0 != retVal)
+ {
+ NSPOL_LOGERR ("clock_gettime() failed]");
+ *timeout = SYS_ARCH_TIMEOUT;
+ return NULL;
+ }
+ }
+
+ while (1)
+ {
+ //TODO:May have to consider, take out the data sharing problem
+ popRet = nsfw_mem_ring_dequeue (q->llring, &pmsg);
+
+ switch (popRet)
+ {
+ case 1:
+ *timeout = ellapsetime;
+ return pmsg;
+
+ default:
+
+ if (isTryPop)
+ {
+ *timeout = SYS_ARCH_TIMEOUT;
+ return NULL;
+ }
+ else
+ {
+ if (*timeout != 0)
+ {
+ retVal = clock_gettime (CLOCK_MONOTONIC, &endtm);
+ if (0 != retVal)
+ {
+ NSPOL_LOGERR ("clock_gettime() failed]");
+ *timeout = SYS_ARCH_TIMEOUT;
+ return NULL;
+ }
+
+ timeDiff = endtm.tv_sec - starttm.tv_sec;
+ if (timeDiff > *timeout)
+ {
+ *timeout = SYS_ARCH_TIMEOUT;
+ return NULL;
+ }
+ sys_sleep_ns (0, 100000);
+ }
+
+ continue;
+ }
+
+ }
+ }
+
+}
diff --git a/stacks/lwip_stack/release/lwip_helper_files/arch/sys_arch.c b/stacks/lwip_stack/release/lwip_helper_files/arch/sys_arch.c
new file mode 100644
index 0000000..bdda4d2
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/arch/sys_arch.c
@@ -0,0 +1,237 @@
+#include <sys/queue.h>
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stdint.h>
+
+#include <pthread.h>
+#include <sys/time.h>
+#include <time.h>
+#include <linux/sched.h>
+
+#include <asm/unistd.h>
+#include <linux/unistd.h>
+#include <syscall.h>
+
+#include <lwip/sys.h>
+#include <cc.h>
+#include <arch/sys_arch.h>
+#include <arch/queue.h>
+#include "nstack_log.h"
+#include "lwip/sockets.h"
+#include "spl_timers.h"
+#include "nstack_securec.h"
+#include "nstack_share_res.h"
+#include "nstack_log.h"
+
+#include "stackx_spl_share.h"
+#include "lwip/api.h"
+#include "lwip/ip.h"
+#include <netif/sc_dpdk.h>
+#include <netif/sharedmemory.h>
+
+#include "common_mem_common.h"
+#include "common_func.h"
+#include "common_mem_api.h"
+
+#include "mgr_com.h"
+#ifdef HAL_LIB
+#else
+#include "rte_ring.h"
+#endif
+
+#include "timeouts.h"
+
+sys_sem_st g_global_semaphore;
+
+/** Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */
+int
+sys_mbox_valid (sys_mbox_t * mbox)
+{
+ return ((*mbox == SYS_MBOX_NULL) ? 0 : 1);
+}
+
+struct lwip_thread
+{
+ void (*func) (void *arg);
+ void *arg;
+};
+
+static void *
+lwip_thread_entry (void *arg)
+{
+ struct lwip_thread *lt = arg;
+
+ lt->func (lt->arg);
+
+ free (lt);
+ return 0;
+}
+
+/** The only thread function:
+ * Creates a new thread
+ * @param name human-readable name for the thread (used for debugging purposes)
+ * @param thread thread-function
+ * @param arg parameter passed to 'thread'
+ * @param stacksize stack size in bytes for the new thread (may be ignored by ports)
+ * @param prio priority of the new thread (may be ignored by ports) */
+sys_thread_t
+sys_thread_new2 (const char *name, lwip_thread_fn thread, void *arg,
+ int stacksize, int prio, int policy)
+{
+ pthread_attr_t attr;
+ set_thread_attr (&attr, stacksize, prio, policy);
+
+ struct lwip_thread *lt = malloc (sizeof (*lt));
+ if (lt == NULL)
+ {
+ NSPOL_LOGERR ("process abort:cannot allocate thread struct");
+ abort ();
+ }
+
+ lt->func = thread;
+ lt->arg = arg;
+
+ pthread_t t;
+ int r = pthread_create (&t, &attr, lwip_thread_entry, lt);
+
+ if (r != 0)
+ {
+ NSPOL_LOGERR ("process abort:lwip:annot create]errno_string=%s",
+ strerror (r));
+ abort ();
+ }
+ else
+ {
+ NSPOL_LOGINF (SC_DPDK_INFO, "]thread_name=%s.", name);
+ }
+
+ (void) pthread_setname_np (t, name);
+
+ return t;
+}
+
+/** The only thread function:
+ * Creates a new thread
+ * @param name human-readable name for the thread (used for debugging purposes)
+ * @param thread thread-function
+ * @param arg parameter passed to 'thread'
+ * @param stacksize stack size in bytes for the new thread (may be ignored by ports)
+ * @param prio priority of the new thread (may be ignored by ports) */
+sys_thread_t
+sys_thread_new (const char *name, lwip_thread_fn thread, void *arg,
+ int stacksize, int prio)
+{
+ pthread_attr_t attr;
+ set_thread_attr (&attr, stacksize, prio, 0);
+
+ struct lwip_thread *lt = malloc (sizeof (*lt));
+ if (lt == NULL)
+ {
+ NSPOL_LOGERR ("process abort:cannot allocate thread struct");
+ abort ();
+ }
+
+ lt->func = thread;
+ lt->arg = arg;
+
+ pthread_t t;
+ int r = pthread_create (&t, &attr, lwip_thread_entry, lt);
+
+ if (r != 0)
+ {
+ NSPOL_LOGERR ("process abort:lwip:annot create]errno_string=%s",
+ strerror (r));
+ abort ();
+ }
+ else
+ {
+ NSPOL_LOGINF (SC_DPDK_INFO, "]thread_name=%s.", name);
+ }
+
+ (void) pthread_setname_np (t, name);
+
+ return t;
+}
+
+void
+stackx_global_lock (void)
+{
+ sys_arch_lock_with_pid (&g_global_semaphore);
+}
+
+void
+stackx_global_unlock (void)
+{
+ sys_sem_s_signal (&g_global_semaphore);
+}
+
+void
+sys_init (void)
+{
+ return;
+}
+
+void
+sys_timeouts_mbox_fetch (sys_mbox_t * mbox, void **msg)
+{
+ return;
+}
+
+void
+sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
+{
+ struct ptimer_node *tmo = arg;
+
+ tmo = malloc (sizeof (struct ptimer_node)); /*lint !e586 */
+ if (NULL == tmo)
+ {
+ NSPOL_LOGERR ("malloc ptimer node failed!");
+ return;
+ }
+
+ int ret = MEMSET_S (tmo, sizeof (struct ptimer_node), 0,
+ sizeof (struct ptimer_node));
+ if (EOK != ret)
+ {
+ NSPOL_LOGERR ("MEMSET_S failed]ret=%d", ret);
+ free (tmo);
+ return;
+ }
+
+ NSPOL_LOGDBG (TIMERS_DEBUG, "alloc]ptimer_node=%p", tmo);
+
+ tmo->info.msec = msecs;
+ tmo->info._phandle = handler;
+ tmo->info.ctx = arg;
+ tmo->info.flags = PTIMER_ONESHOT;
+ tmo->index = 0;
+ regedit_ptimer (SYS_PTIMEROUT_MSG, handler, tmo);
+}
+
+void
+sys_untimeout (sys_timeout_handler handler, void *arg)
+{
+ regedit_ptimer (SYS_UNPTIMEROUT_MSG, handler, arg);
+ return;
+}
+
+/**
+ * Timer callback function that calls mld6_tmr() and reschedules itself.
+ *
+ * @param arg unused argument
+ */
+void
+cyclic_timer (void *arg)
+{
+ const struct lwip_cyclic_timer *cyclic =
+ (const struct lwip_cyclic_timer *) arg;
+#if LWIP_DEBUG_TIMERNAMES
+ LWIP_DEBUGF (TIMERS_DEBUG, ("tcpip: %s()\n", cyclic->handler_name));
+#endif
+ cyclic->handler ();
+ sys_timeout (cyclic->interval_ms, cyclic_timer, arg);
+}
diff --git a/stacks/lwip_stack/release/lwip_helper_files/core/timeouts.c b/stacks/lwip_stack/release/lwip_helper_files/core/timeouts.c
new file mode 100644
index 0000000..efbda94
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/core/timeouts.c
@@ -0,0 +1,527 @@
+/**
+ * @file
+ * Stack-internal timers implementation.
+ * This file includes timer callbacks for stack-internal timers as well as
+ * functions to set up or stop timers and check for expired timers.
+ *
+ */
+
+/*
+ * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+ * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+ * OF SUCH DAMAGE.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ * Simon Goldschmidt
+ *
+ */
+
+#include "lwip/opt.h"
+
+#include "lwip/timeouts.h"
+#include "lwip/priv/tcp_priv.h"
+
+#include "lwip/def.h"
+#include "lwip/memp.h"
+#include "lwip/priv/tcpip_priv.h"
+
+#include "lwip/ip4_frag.h"
+#include "lwip/etharp.h"
+#include "lwip/dhcp.h"
+#include "lwip/autoip.h"
+#include "lwip/igmp.h"
+#include "lwip/dns.h"
+#include "lwip/nd6.h"
+#include "lwip/ip6_frag.h"
+#include "lwip/mld6.h"
+#include "lwip/sys.h"
+#include "lwip/pbuf.h"
+
+#if LWIP_DEBUG_TIMERNAMES
+#define HANDLER(x) x, #x
+#else /* LWIP_DEBUG_TIMERNAMES */
+#define HANDLER(x) x
+#endif /* LWIP_DEBUG_TIMERNAMES */
+
+/** This array contains all stack-internal cyclic timers. To get the number of
+ * timers, use LWIP_ARRAYSIZE() */
+const struct lwip_cyclic_timer lwip_cyclic_timers[] = {
+#if LWIP_TCP
+ /* The TCP timer is a special case: it does not have to run always and
+ is triggered to start from TCP using tcp_timer_needed() */
+ {TCP_TMR_INTERVAL, HANDLER (tcp_tmr)},
+#endif /* LWIP_TCP */
+#if LWIP_IPV4
+#if IP_REASSEMBLY
+ {IP_TMR_INTERVAL, HANDLER (ip_reass_tmr)},
+#endif /* IP_REASSEMBLY */
+#if LWIP_ARP
+ {ARP_TMR_INTERVAL, HANDLER (etharp_tmr)},
+#endif /* LWIP_ARP */
+#if LWIP_DHCP
+ {DHCP_COARSE_TIMER_MSECS, HANDLER (dhcp_coarse_tmr)},
+ {DHCP_FINE_TIMER_MSECS, HANDLER (dhcp_fine_tmr)},
+#endif /* LWIP_DHCP */
+#if LWIP_AUTOIP
+ {AUTOIP_TMR_INTERVAL, HANDLER (autoip_tmr)},
+#endif /* LWIP_AUTOIP */
+#if LWIP_IGMP
+ {IGMP_TMR_INTERVAL, HANDLER (igmp_tmr)},
+#endif /* LWIP_IGMP */
+#endif /* LWIP_IPV4 */
+#if LWIP_DNS
+ {DNS_TMR_INTERVAL, HANDLER (dns_tmr)},
+#endif /* LWIP_DNS */
+#if LWIP_IPV6
+ {ND6_TMR_INTERVAL, HANDLER (nd6_tmr)},
+#if LWIP_IPV6_REASS
+ {IP6_REASS_TMR_INTERVAL, HANDLER (ip6_reass_tmr)},
+#endif /* LWIP_IPV6_REASS */
+#if LWIP_IPV6_MLD
+ {MLD6_TMR_INTERVAL, HANDLER (mld6_tmr)},
+#endif /* LWIP_IPV6_MLD */
+#endif /* LWIP_IPV6 */
+};
+
+#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM
+
+/** The one and only timeout list */
+static struct sys_timeo *next_timeout;
+static u32_t timeouts_last_time;
+
+#if LWIP_TCP
+/** global variable that shows if the tcp timer is currently scheduled or not */
+static int tcpip_tcp_timer_active;
+
+/**
+ * Timer callback function that calls tcp_tmr() and reschedules itself.
+ *
+ * @param arg unused argument
+ */
+static void
+tcpip_tcp_timer (void *arg)
+{
+ LWIP_UNUSED_ARG (arg);
+
+ /* call TCP timer handler */
+ tcp_tmr ();
+ /* timer still needed? */
+ if (tcp_active_pcbs || tcp_tw_pcbs)
+ {
+ /* restart timer */
+ sys_timeout (TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
+ }
+ else
+ {
+ /* disable timer */
+ tcpip_tcp_timer_active = 0;
+ }
+}
+
+/**
+ * Called from TCP_REG when registering a new PCB:
+ * the reason is to have the TCP timer only running when
+ * there are active (or time-wait) PCBs.
+ */
+void
+tcp_timer_needed (void)
+{
+ /* timer is off but needed again? */
+ if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs))
+ {
+ /* enable and start timer */
+ tcpip_tcp_timer_active = 1;
+ sys_timeout (TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
+ }
+}
+#endif /* LWIP_TCP */
+
+/**
+ * Timer callback function that calls mld6_tmr() and reschedules itself.
+ *
+ * @param arg unused argument
+ */
+static void
+cyclic_timer (void *arg)
+{
+ const struct lwip_cyclic_timer *cyclic =
+ (const struct lwip_cyclic_timer *) arg;
+#if LWIP_DEBUG_TIMERNAMES
+ LWIP_DEBUGF (TIMERS_DEBUG, ("tcpip: %s()\n", cyclic->handler_name));
+#endif
+ cyclic->handler ();
+ sys_timeout (cyclic->interval_ms, cyclic_timer, arg);
+}
+
+/** Initialize this module */
+void
+sys_timeouts_init (void)
+{
+ size_t i;
+ /* tcp_tmr() at index 0 is started on demand */
+ for (i = (LWIP_TCP ? 1 : 0); i < LWIP_ARRAYSIZE (lwip_cyclic_timers); i++)
+ {
+ /* we have to cast via size_t to get rid of const warning
+ (this is OK as cyclic_timer() casts back to const* */
+ sys_timeout (lwip_cyclic_timers[i].interval_ms, cyclic_timer,
+ LWIP_CONST_CAST (void *, &lwip_cyclic_timers[i]));
+ }
+
+ /* Initialise timestamp for sys_check_timeouts */
+ timeouts_last_time = sys_now ();
+}
+
+/**
+ * Create a one-shot timer (aka timeout). Timeouts are processed in the
+ * following cases:
+ * - while waiting for a message using sys_timeouts_mbox_fetch()
+ * - by calling sys_check_timeouts() (NO_SYS==1 only)
+ *
+ * @param msecs time in milliseconds after that the timer should expire
+ * @param handler callback function to call when msecs have elapsed
+ * @param arg argument to pass to the callback function
+ */
+#if LWIP_DEBUG_TIMERNAMES
+void
+sys_timeout_debug (u32_t msecs, sys_timeout_handler handler, void *arg,
+ const char *handler_name)
+#else /* LWIP_DEBUG_TIMERNAMES */
+void
+sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
+#endif /* LWIP_DEBUG_TIMERNAMES */
+{
+ struct sys_timeo *timeout, *t;
+ u32_t now, diff;
+
+ timeout = (struct sys_timeo *) memp_malloc (MEMP_SYS_TIMEOUT);
+ if (timeout == NULL)
+ {
+ LWIP_ASSERT
+ ("sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty",
+ timeout != NULL);
+ return;
+ }
+
+ now = sys_now ();
+ if (next_timeout == NULL)
+ {
+ diff = 0;
+ timeouts_last_time = now;
+ }
+ else
+ {
+ diff = now - timeouts_last_time;
+ }
+
+ timeout->next = NULL;
+ timeout->h = handler;
+ timeout->arg = arg;
+ timeout->time = msecs + diff;
+#if LWIP_DEBUG_TIMERNAMES
+ timeout->handler_name = handler_name;
+ LWIP_DEBUGF (TIMERS_DEBUG,
+ ("sys_timeout: %p msecs=%" U32_F " handler=%s arg=%p\n",
+ (void *) timeout, msecs, handler_name, (void *) arg));
+#endif /* LWIP_DEBUG_TIMERNAMES */
+
+ if (next_timeout == NULL)
+ {
+ next_timeout = timeout;
+ return;
+ }
+
+ if (next_timeout->time > msecs)
+ {
+ next_timeout->time -= msecs;
+ timeout->next = next_timeout;
+ next_timeout = timeout;
+ }
+ else
+ {
+ for (t = next_timeout; t != NULL; t = t->next)
+ {
+ timeout->time -= t->time;
+ if (t->next == NULL || t->next->time > timeout->time)
+ {
+ if (t->next != NULL)
+ {
+ t->next->time -= timeout->time;
+ }
+ else if (timeout->time > msecs)
+ {
+ /* If this is the case, 'timeouts_last_time' and 'now' differs too much.
+ This can be due to sys_check_timeouts() not being called at the right
+ times, but also when stopping in a breakpoint. Anyway, let's assume
+ this is not wanted, so add the first timer's time instead of 'diff' */
+ timeout->time = msecs + next_timeout->time;
+ }
+ timeout->next = t->next;
+ t->next = timeout;
+ break;
+ }
+ }
+ }
+}
+
+/**
+ * Go through timeout list (for this task only) and remove the first matching
+ * entry (subsequent entries remain untouched), even though the timeout has not
+ * triggered yet.
+ *
+ * @param handler callback function that would be called by the timeout
+ * @param arg callback argument that would be passed to handler
+*/
+void
+sys_untimeout (sys_timeout_handler handler, void *arg)
+{
+ struct sys_timeo *prev_t, *t;
+
+ if (next_timeout == NULL)
+ {
+ return;
+ }
+
+ for (t = next_timeout, prev_t = NULL; t != NULL; prev_t = t, t = t->next)
+ {
+ if ((t->h == handler) && (t->arg == arg))
+ {
+ /* We have a match */
+ /* Unlink from previous in list */
+ if (prev_t == NULL)
+ {
+ next_timeout = t->next;
+ }
+ else
+ {
+ prev_t->next = t->next;
+ }
+ /* If not the last one, add time of this one back to next */
+ if (t->next != NULL)
+ {
+ t->next->time += t->time;
+ }
+ memp_free (MEMP_SYS_TIMEOUT, t);
+ return;
+ }
+ }
+ return;
+}
+
+/**
+ * @ingroup lwip_nosys
+ * Handle timeouts for NO_SYS==1 (i.e. without using
+ * tcpip_thread/sys_timeouts_mbox_fetch(). Uses sys_now() to call timeout
+ * handler functions when timeouts expire.
+ *
+ * Must be called periodically from your main loop.
+ */
+#if !NO_SYS && !defined __DOXYGEN__
+static
+#endif /* !NO_SYS */
+ void
+sys_check_timeouts (void)
+{
+ if (next_timeout)
+ {
+ struct sys_timeo *tmptimeout;
+ u32_t diff;
+ sys_timeout_handler handler;
+ void *arg;
+ u8_t had_one;
+ u32_t now;
+
+ now = sys_now ();
+ /* this cares for wraparounds */
+ diff = now - timeouts_last_time;
+ do
+ {
+ PBUF_CHECK_FREE_OOSEQ ();
+ had_one = 0;
+ tmptimeout = next_timeout;
+ if (tmptimeout && (tmptimeout->time <= diff))
+ {
+ /* timeout has expired */
+ had_one = 1;
+ timeouts_last_time += tmptimeout->time;
+ diff -= tmptimeout->time;
+ next_timeout = tmptimeout->next;
+ handler = tmptimeout->h;
+ arg = tmptimeout->arg;
+#if LWIP_DEBUG_TIMERNAMES
+ if (handler != NULL)
+ {
+ LWIP_DEBUGF (TIMERS_DEBUG, ("sct calling h=%s arg=%p\n",
+ tmptimeout->handler_name, arg));
+ }
+#endif /* LWIP_DEBUG_TIMERNAMES */
+ memp_free (MEMP_SYS_TIMEOUT, tmptimeout);
+ if (handler != NULL)
+ {
+#if !NO_SYS
+ /* For LWIP_TCPIP_CORE_LOCKING, lock the core before calling the
+ timeout handler function. */
+ LOCK_TCPIP_CORE ();
+#endif /* !NO_SYS */
+ handler (arg);
+#if !NO_SYS
+ UNLOCK_TCPIP_CORE ();
+#endif /* !NO_SYS */
+ }
+ LWIP_TCPIP_THREAD_ALIVE ();
+ }
+ /* repeat until all expired timers have been called */
+ }
+ while (had_one);
+ }
+}
+
+/** Set back the timestamp of the last call to sys_check_timeouts()
+ * This is necessary if sys_check_timeouts() hasn't been called for a long
+ * time (e.g. while saving energy) to prevent all timer functions of that
+ * period being called.
+ */
+void
+sys_restart_timeouts (void)
+{
+ timeouts_last_time = sys_now ();
+}
+
+/** Return the time left before the next timeout is due. If no timeouts are
+ * enqueued, returns 0xffffffff
+ */
+#if !NO_SYS
+static
+#endif /* !NO_SYS */
+ u32_t
+sys_timeouts_sleeptime (void)
+{
+ u32_t diff;
+ if (next_timeout == NULL)
+ {
+ return 0xffffffff;
+ }
+ diff = sys_now () - timeouts_last_time;
+ if (diff > next_timeout->time)
+ {
+ return 0;
+ }
+ else
+ {
+ return next_timeout->time - diff;
+ }
+}
+
+#if !NO_SYS
+
+/**
+ * Wait (forever) for a message to arrive in an mbox.
+ * While waiting, timeouts are processed.
+ *
+ * @param mbox the mbox to fetch the message from
+ * @param msg the place to store the message
+ */
+void
+sys_timeouts_mbox_fetch (sys_mbox_t * mbox, void **msg)
+{
+ u32_t sleeptime;
+
+again:
+ if (!next_timeout)
+ {
+ sys_arch_mbox_fetch (mbox, msg, 0);
+ return;
+ }
+
+ sleeptime = sys_timeouts_sleeptime ();
+ if (sleeptime == 0
+ || sys_arch_mbox_fetch (mbox, msg, sleeptime) == SYS_ARCH_TIMEOUT)
+ {
+ /* If a SYS_ARCH_TIMEOUT value is returned, a timeout occurred
+ before a message could be fetched. */
+ sys_check_timeouts ();
+ /* We try again to fetch a message from the mbox. */
+ goto again;
+ }
+}
+
+#endif /* NO_SYS */
+
+#else /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */
+/* Satisfy the TCP code which calls this function */
+static int tcpip_tcp_timer_active;
+
+void
+tcp_timer_needed (void)
+{
+ /* timer is off but needed again? */
+ if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs))
+ {
+ /* enable and start timer */
+ tcpip_tcp_timer_active = 1;
+ sys_timeout (TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
+ }
+}
+
+/**
+ * Timer callback function that calls tcp_tmr() and reschedules itself.
+ *
+ * @param arg unused argument
+ */
+void
+tcpip_tcp_timer (void *arg)
+{
+ LWIP_UNUSED_ARG (arg);
+
+ /* call TCP timer handler */
+ tcp_tmr ();
+ /* timer still needed? */
+ if (tcp_active_pcbs || tcp_tw_pcbs)
+ {
+ /* restart timer */
+ sys_timeout (TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
+ }
+ else
+ {
+ /* disable timer */
+ tcpip_tcp_timer_active = 0;
+ }
+}
+
+void
+sys_timeouts_init (void)
+{
+ size_t i;
+ /* tcp_tmr() at index 0 is started on demand */
+ for (i = (LWIP_TCP ? 1 : 0); i < LWIP_ARRAYSIZE (lwip_cyclic_timers); i++)
+ {
+ /* we have to cast via size_t to get rid of const warning
+ (this is OK as cyclic_timer() casts back to const* */
+ sys_timeout (lwip_cyclic_timers[i].interval_ms, cyclic_timer,
+ LWIP_CONST_CAST (void *, &lwip_cyclic_timers[i]));
+ }
+}
+
+#endif /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */
diff --git a/stacks/lwip_stack/release/lwip_helper_files/download_lwip.sh b/stacks/lwip_stack/release/lwip_helper_files/download_lwip.sh
new file mode 100644
index 0000000..316859b
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/download_lwip.sh
@@ -0,0 +1,35 @@
+#########################################################################
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+#!/bin/bash -x
+
+set -x
+
+SCRIPT_DIR=$(dirname "$0")
+echo $SCRIPT_DIR
+LWIP_DOWNLOAD_DIR="${SCRIPT_DIR}/../../lwip_src/"
+echo $LWIP_DOWNLOAD_DIR
+if [ ! -d "${LWIP_DOWNLOAD_DIR}/lwip/" ]; then
+ mkdir -p ${LWIP_DOWNLOAD_DIR}/lwip/
+ cd ${LWIP_DOWNLOAD_DIR}/
+ wget -N --no-check-certificate http://download.savannah.nongnu.org/releases/lwip/lwip-2.0.3.zip
+ unzip ${LWIP_DOWNLOAD_DIR}/lwip-2.0.3.zip "lwip-2.0.3/src/*" -d ${LWIP_DOWNLOAD_DIR}/lwip
+ mv ${LWIP_DOWNLOAD_DIR}/lwip/lwip-2.0.3/src/* ${LWIP_DOWNLOAD_DIR}/lwip/
+ rm -rf ${LWIP_DOWNLOAD_DIR}/lwip/lwip-2.0.3/
+ cp -r ${SCRIPT_DIR}/arch/ ${LWIP_DOWNLOAD_DIR}/lwip/
+ cp -r ${SCRIPT_DIR}/lwip/arch/ ${LWIP_DOWNLOAD_DIR}/lwip/include/lwip/
+ cp -r ${SCRIPT_DIR}/core/* ${LWIP_DOWNLOAD_DIR}/lwip/core/
+ cp -r ${SCRIPT_DIR}/include/* ${LWIP_DOWNLOAD_DIR}/lwip/include/lwip/
+ mv ${LWIP_DOWNLOAD_DIR}/lwip/include/lwip/errno.h ${LWIP_DOWNLOAD_DIR}/lwip/include/lwip/lwip_errno.h
+fi \ No newline at end of file
diff --git a/stacks/lwip_stack/release/lwip_helper_files/include/lwipopts.h b/stacks/lwip_stack/release/lwip_helper_files/include/lwipopts.h
new file mode 100644
index 0000000..4b1cf4f
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/include/lwipopts.h
@@ -0,0 +1,39 @@
+#ifndef LWIP_LWIPOPTS_H
+#define LWIP_LWIPOPTS_H
+
+#define RING_CACHE_SIZE 1024
+#define LISTEN_CACHE_SIZE 1024
+#define RECV_MAX_POOL 4
+#define MAX_TRY_GET_MEMORY_TIMES 4
+#define MAX_MEMORY_USED_SIZE 80
+
+#define IP_HLEN 20
+#define TCP_HLEN 20
+#define TCP_MAX_OPTION_LEN 40
+
+#define _cache_aligned __attribute__((__aligned__(64)))
+#define LWIP_NETIF_API 1
+
+#define TCP_OVERSIZE 1
+#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS
+#define SYS_LIGHTWEIGHT_PROT 1
+#define LWIP_DISABLE_TCP_SANITY_CHECKS 1
+#define LWIP_COMPAT_MUTEX_ALLOWED 1
+#define LWIP_ERRNO_INCLUDE <errno.h>
+#define LWIP_SKIP_PACKING_CHECK 1
+#define PBUF_POOL_FREE_OOSEQ 0
+
+#define LWIP_DEBUG 1
+#define LWIP_TIMERS 0
+#define LWIP_TIMERS_CUSTOM 1
+#define LWIP_TCPIP_CORE_LOCKING 1
+#define MEM_LIBC_MALLOC 1
+#define MEMP_MEM_MALLOC 1
+#define LWIP_CALLBACK_API 1
+#define LWIP_SOCKET 0
+#define LWIP_POSIX_SOCKETS_IO_NAMES 0
+#define LWIP_TCP_KEEPALIVE 1
+#define LWIP_TIMEVAL_PRIVATE 0
+#define LWIP_COMPAT_MUTEX 1
+
+#endif
diff --git a/stacks/lwip_stack/release/lwip_helper_files/include/opt.h b/stacks/lwip_stack/release/lwip_helper_files/include/opt.h
new file mode 100644
index 0000000..040e9cf
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/include/opt.h
@@ -0,0 +1,2875 @@
+/**
+ * @file
+ *
+ * lwIP Options Configuration
+ */
+
+/*
+ * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+ * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+ * OF SUCH DAMAGE.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ */
+
+/*
+ * NOTE: || defined __DOXYGEN__ is a workaround for doxygen bug -
+ * without this, doxygen does not see the actual #define
+ */
+
+#if !defined LWIP_HDR_OPT_H
+#define LWIP_HDR_OPT_H
+
+/*
+ * Include user defined options first. Anything not defined in these files
+ * will be set to standard values. Override anything you don't like!
+ */
+#include "lwipopts.h"
+#include "lwip/debug.h"
+
+/**
+ * @defgroup lwip_opts Options (lwipopts.h)
+ * @ingroup lwip
+ *
+ * @defgroup lwip_opts_debug Debugging
+ * @ingroup lwip_opts
+ *
+ * @defgroup lwip_opts_infrastructure Infrastructure
+ * @ingroup lwip_opts
+ *
+ * @defgroup lwip_opts_callback Callback-style APIs
+ * @ingroup lwip_opts
+ *
+ * @defgroup lwip_opts_threadsafe_apis Thread-safe APIs
+ * @ingroup lwip_opts
+ */
+
+ /*
+ ------------------------------------
+ -------------- NO SYS --------------
+ ------------------------------------
+ */
+/**
+ * @defgroup lwip_opts_nosys NO_SYS
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * NO_SYS==1: Use lwIP without OS-awareness (no thread, semaphores, mutexes or
+ * mboxes). This means threaded APIs cannot be used (socket, netconn,
+ * i.e. everything in the 'api' folder), only the callback-style raw API is
+ * available (and you have to watch out for yourself that you don't access
+ * lwIP functions/structures from more than one context at a time!)
+ */
+#if !defined NO_SYS || defined __DOXYGEN__
+#define NO_SYS 0
+#endif
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lwip_opts_timers Timers
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * LWIP_TIMERS==0: Drop support for sys_timeout and lwip-internal cyclic timers.
+ * (the array of lwip-internal cyclic timers is still provided)
+ * (check NO_SYS_NO_TIMERS for compatibility to old versions)
+ */
+#if !defined LWIP_TIMERS || defined __DOXYGEN__
+#ifdef NO_SYS_NO_TIMERS
+#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS))
+#else
+#define LWIP_TIMERS 1
+#endif
+#endif
+
+/**
+ * LWIP_TIMERS_CUSTOM==1: Provide your own timer implementation.
+ * Function prototypes in timeouts.h and the array of lwip-internal cyclic timers
+ * are still included, but the implementation is not. The following functions
+ * will be required: sys_timeouts_init(), sys_timeout(), sys_untimeout(),
+ * sys_timeouts_mbox_fetch()
+ */
+#if !defined LWIP_TIMERS_CUSTOM || defined __DOXYGEN__
+#define LWIP_TIMERS_CUSTOM 0
+#endif
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lwip_opts_memcpy memcpy
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * MEMCPY: override this if you have a faster implementation at hand than the
+ * one included in your C library
+ */
+#if !defined MEMCPY || defined __DOXYGEN__
+#define MEMCPY(dst,src,len) memcpy(dst,src,len)
+#endif
+
+/**
+ * SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a
+ * call to memcpy() if the length is known at compile time and is small.
+ */
+#if !defined SMEMCPY || defined __DOXYGEN__
+#define SMEMCPY(dst,src,len) memcpy(dst,src,len)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ----------- Core locking -----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_lock Core locking and MPU
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * LWIP_MPU_COMPATIBLE: enables special memory management mechanism
+ * which makes lwip able to work on MPU (Memory Protection Unit) system
+ * by not passing stack-pointers to other threads
+ * (this decreases performance as memory is allocated from pools instead
+ * of keeping it on the stack)
+ */
+#if !defined LWIP_MPU_COMPATIBLE || defined __DOXYGEN__
+#define LWIP_MPU_COMPATIBLE 0
+#endif
+
+/**
+ * LWIP_TCPIP_CORE_LOCKING
+ * Creates a global mutex that is held during TCPIP thread operations.
+ * Can be locked by client code to perform lwIP operations without changing
+ * into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and
+ * UNLOCK_TCPIP_CORE().
+ * Your system should provide mutexes supporting priority inversion to use this.
+ */
+#if !defined LWIP_TCPIP_CORE_LOCKING || defined __DOXYGEN__
+#define LWIP_TCPIP_CORE_LOCKING 1
+#endif
+
+/**
+ * LWIP_TCPIP_CORE_LOCKING_INPUT: when LWIP_TCPIP_CORE_LOCKING is enabled,
+ * this lets tcpip_input() grab the mutex for input packets as well,
+ * instead of allocating a message and passing it to tcpip_thread.
+ *
+ * ATTENTION: this does not work when tcpip_input() is called from
+ * interrupt context!
+ */
+#if !defined LWIP_TCPIP_CORE_LOCKING_INPUT || defined __DOXYGEN__
+#define LWIP_TCPIP_CORE_LOCKING_INPUT 0
+#endif
+
+/**
+ * SYS_LIGHTWEIGHT_PROT==1: enable inter-task protection (and task-vs-interrupt
+ * protection) for certain critical regions during buffer allocation, deallocation
+ * and memory allocation and deallocation.
+ * ATTENTION: This is required when using lwIP from more than one context! If
+ * you disable this, you must be sure what you are doing!
+ */
+#if !defined SYS_LIGHTWEIGHT_PROT || defined __DOXYGEN__
+#define SYS_LIGHTWEIGHT_PROT 1
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ---------- Memory options ----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_mem Heap and memory pools
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library
+ * instead of the lwip internal allocator. Can save code size if you
+ * already use it.
+ */
+#if !defined MEM_LIBC_MALLOC || defined __DOXYGEN__
+#define MEM_LIBC_MALLOC 0
+#endif
+
+/**
+ * MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator.
+ * Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution
+ * speed (heap alloc can be much slower than pool alloc) and usage from interrupts
+ * (especially if your netif driver allocates PBUF_POOL pbufs for received frames
+ * from interrupt)!
+ * ATTENTION: Currently, this uses the heap for ALL pools (also for private pools,
+ * not only for internal pools defined in memp_std.h)!
+ */
+#if !defined MEMP_MEM_MALLOC || defined __DOXYGEN__
+#define MEMP_MEM_MALLOC 0
+#endif
+
+/**
+ * MEM_ALIGNMENT: should be set to the alignment of the CPU
+ * 4 byte alignment -> \#define MEM_ALIGNMENT 4
+ * 2 byte alignment -> \#define MEM_ALIGNMENT 2
+ */
+#if !defined MEM_ALIGNMENT || defined __DOXYGEN__
+#define MEM_ALIGNMENT 1
+#endif
+
+/**
+ * MEM_SIZE: the size of the heap memory. If the application will send
+ * a lot of data that needs to be copied, this should be set high.
+ */
+#if !defined MEM_SIZE || defined __DOXYGEN__
+#define MEM_SIZE 1600
+#endif
+
+/**
+ * MEMP_OVERFLOW_CHECK: memp overflow protection reserves a configurable
+ * amount of bytes before and after each memp element in every pool and fills
+ * it with a prominent default value.
+ * MEMP_OVERFLOW_CHECK == 0 no checking
+ * MEMP_OVERFLOW_CHECK == 1 checks each element when it is freed
+ * MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time
+ * memp_malloc() or memp_free() is called (useful but slow!)
+ */
+#if !defined MEMP_OVERFLOW_CHECK || defined __DOXYGEN__
+#define MEMP_OVERFLOW_CHECK 0
+#endif
+
+/**
+ * MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make
+ * sure that there are no cycles in the linked lists.
+ */
+#if !defined MEMP_SANITY_CHECK || defined __DOXYGEN__
+#define MEMP_SANITY_CHECK 0
+#endif
+
+/**
+ * MEM_USE_POOLS==1: Use an alternative to malloc() by allocating from a set
+ * of memory pools of various sizes. When mem_malloc is called, an element of
+ * the smallest pool that can provide the length needed is returned.
+ * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled.
+ */
+#if !defined MEM_USE_POOLS || defined __DOXYGEN__
+#define MEM_USE_POOLS 0
+#endif
+
+/**
+ * MEM_USE_POOLS_TRY_BIGGER_POOL==1: if one malloc-pool is empty, try the next
+ * bigger pool - WARNING: THIS MIGHT WASTE MEMORY but it can make a system more
+ * reliable. */
+#if !defined MEM_USE_POOLS_TRY_BIGGER_POOL || defined __DOXYGEN__
+#define MEM_USE_POOLS_TRY_BIGGER_POOL 0
+#endif
+
+/**
+ * MEMP_USE_CUSTOM_POOLS==1: whether to include a user file lwippools.h
+ * that defines additional pools beyond the "standard" ones required
+ * by lwIP. If you set this to 1, you must have lwippools.h in your
+ * include path somewhere.
+ */
+#if !defined MEMP_USE_CUSTOM_POOLS || defined __DOXYGEN__
+#define MEMP_USE_CUSTOM_POOLS 0
+#endif
+
+/**
+ * Set this to 1 if you want to free PBUF_RAM pbufs (or call mem_free()) from
+ * interrupt context (or another context that doesn't allow waiting for a
+ * semaphore).
+ * If set to 1, mem_malloc will be protected by a semaphore and SYS_ARCH_PROTECT,
+ * while mem_free will only use SYS_ARCH_PROTECT. mem_malloc SYS_ARCH_UNPROTECTs
+ * with each loop so that mem_free can run.
+ *
+ * ATTENTION: As you can see from the above description, this leads to dis-/
+ * enabling interrupts often, which can be slow! Also, on low memory, mem_malloc
+ * can need longer.
+ *
+ * If you don't want that, at least for NO_SYS=0, you can still use the following
+ * functions to enqueue a deallocation call which then runs in the tcpip_thread
+ * context:
+ * - pbuf_free_callback(p);
+ * - mem_free_callback(m);
+ */
+#if !defined LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT || defined __DOXYGEN__
+#define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------------------
+ ---------- Internal Memory Pool Sizes ----------
+ ------------------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_memp Internal memory pools
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF).
+ * If the application sends a lot of data out of ROM (or other static memory),
+ * this should be set high.
+ */
+#if !defined MEMP_NUM_PBUF || defined __DOXYGEN__
+#define MEMP_NUM_PBUF 16
+#endif
+
+/**
+ * MEMP_NUM_RAW_PCB: Number of raw connection PCBs
+ * (requires the LWIP_RAW option)
+ */
+#if !defined MEMP_NUM_RAW_PCB || defined __DOXYGEN__
+#define MEMP_NUM_RAW_PCB 4
+#endif
+
+/**
+ * MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One
+ * per active UDP "connection".
+ * (requires the LWIP_UDP option)
+ */
+#if !defined MEMP_NUM_UDP_PCB || defined __DOXYGEN__
+#define MEMP_NUM_UDP_PCB 4
+#endif
+
+/**
+ * MEMP_NUM_TCP_PCB: the number of simultaneously active TCP connections.
+ * (requires the LWIP_TCP option)
+ */
+#if !defined MEMP_NUM_TCP_PCB || defined __DOXYGEN__
+#define MEMP_NUM_TCP_PCB 5
+#endif
+
+/**
+ * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections.
+ * (requires the LWIP_TCP option)
+ */
+#if !defined MEMP_NUM_TCP_PCB_LISTEN || defined __DOXYGEN__
+#define MEMP_NUM_TCP_PCB_LISTEN 8
+#endif
+
+/**
+ * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments.
+ * (requires the LWIP_TCP option)
+ */
+#if !defined MEMP_NUM_TCP_SEG || defined __DOXYGEN__
+#define MEMP_NUM_TCP_SEG 16
+#endif
+
+/**
+ * MEMP_NUM_REASSDATA: the number of IP packets simultaneously queued for
+ * reassembly (whole packets, not fragments!)
+ */
+#if !defined MEMP_NUM_REASSDATA || defined __DOXYGEN__
+#define MEMP_NUM_REASSDATA 5
+#endif
+
+/**
+ * MEMP_NUM_FRAG_PBUF: the number of IP fragments simultaneously sent
+ * (fragments, not whole packets!).
+ * This is only used with LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1
+ * with DMA-enabled MACs where the packet is not yet sent when netif->output
+ * returns.
+ */
+#if !defined MEMP_NUM_FRAG_PBUF || defined __DOXYGEN__
+#define MEMP_NUM_FRAG_PBUF 15
+#endif
+
+/**
+ * MEMP_NUM_ARP_QUEUE: the number of simultaneously queued outgoing
+ * packets (pbufs) that are waiting for an ARP request (to resolve
+ * their destination address) to finish.
+ * (requires the ARP_QUEUEING option)
+ */
+#if !defined MEMP_NUM_ARP_QUEUE || defined __DOXYGEN__
+#define MEMP_NUM_ARP_QUEUE 30
+#endif
+
+/**
+ * MEMP_NUM_IGMP_GROUP: The number of multicast groups whose network interfaces
+ * can be members at the same time (one per netif - allsystems group -, plus one
+ * per netif membership).
+ * (requires the LWIP_IGMP option)
+ */
+#if !defined MEMP_NUM_IGMP_GROUP || defined __DOXYGEN__
+#define MEMP_NUM_IGMP_GROUP 8
+#endif
+
+/**
+ * MEMP_NUM_SYS_TIMEOUT: the number of simultaneously active timeouts.
+ * The default number of timeouts is calculated here for all enabled modules.
+ * The formula expects settings to be either '0' or '1'.
+ */
+#if !defined MEMP_NUM_SYS_TIMEOUT || defined __DOXYGEN__
+#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0))
+#endif
+
+/**
+ * MEMP_NUM_NETBUF: the number of struct netbufs.
+ * (only needed if you use the sequential API, like api_lib.c)
+ */
+#if !defined MEMP_NUM_NETBUF || defined __DOXYGEN__
+#define MEMP_NUM_NETBUF 2
+#endif
+
+/**
+ * MEMP_NUM_NETCONN: the number of struct netconns.
+ * (only needed if you use the sequential API, like api_lib.c)
+ */
+#if !defined MEMP_NUM_NETCONN || defined __DOXYGEN__
+#define MEMP_NUM_NETCONN 4
+#endif
+
+/**
+ * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used
+ * for callback/timeout API communication.
+ * (only needed if you use tcpip.c)
+ */
+#if !defined MEMP_NUM_TCPIP_MSG_API || defined __DOXYGEN__
+#define MEMP_NUM_TCPIP_MSG_API 8
+#endif
+
+/**
+ * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used
+ * for incoming packets.
+ * (only needed if you use tcpip.c)
+ */
+#if !defined MEMP_NUM_TCPIP_MSG_INPKT || defined __DOXYGEN__
+#define MEMP_NUM_TCPIP_MSG_INPKT 8
+#endif
+
+/**
+ * MEMP_NUM_NETDB: the number of concurrently running lwip_addrinfo() calls
+ * (before freeing the corresponding memory using lwip_freeaddrinfo()).
+ */
+#if !defined MEMP_NUM_NETDB || defined __DOXYGEN__
+#define MEMP_NUM_NETDB 1
+#endif
+
+/**
+ * MEMP_NUM_LOCALHOSTLIST: the number of host entries in the local host list
+ * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1.
+ */
+#if !defined MEMP_NUM_LOCALHOSTLIST || defined __DOXYGEN__
+#define MEMP_NUM_LOCALHOSTLIST 1
+#endif
+
+/**
+ * PBUF_POOL_SIZE: the number of buffers in the pbuf pool.
+ */
+#if !defined PBUF_POOL_SIZE || defined __DOXYGEN__
+#define PBUF_POOL_SIZE 16
+#endif
+
+/** MEMP_NUM_API_MSG: the number of concurrently active calls to various
+ * socket, netconn, and tcpip functions
+ */
+#if !defined MEMP_NUM_API_MSG || defined __DOXYGEN__
+#define MEMP_NUM_API_MSG MEMP_NUM_TCPIP_MSG_API
+#endif
+
+/** MEMP_NUM_DNS_API_MSG: the number of concurrently active calls to netconn_gethostbyname
+ */
+#if !defined MEMP_NUM_DNS_API_MSG || defined __DOXYGEN__
+#define MEMP_NUM_DNS_API_MSG MEMP_NUM_TCPIP_MSG_API
+#endif
+
+/** MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA: the number of concurrently active calls
+ * to getsockopt/setsockopt
+ */
+#if !defined MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA || defined __DOXYGEN__
+#define MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA MEMP_NUM_TCPIP_MSG_API
+#endif
+
+/** MEMP_NUM_NETIFAPI_MSG: the number of concurrently active calls to the
+ * netifapi functions
+ */
+#if !defined MEMP_NUM_NETIFAPI_MSG || defined __DOXYGEN__
+#define MEMP_NUM_NETIFAPI_MSG MEMP_NUM_TCPIP_MSG_API
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------
+ ---------- ARP options ----------
+ ---------------------------------
+*/
+/**
+ * @defgroup lwip_opts_arp ARP
+ * @ingroup lwip_opts_ipv4
+ * @{
+ */
+/**
+ * LWIP_ARP==1: Enable ARP functionality.
+ */
+#if !defined LWIP_ARP || defined __DOXYGEN__
+#define LWIP_ARP 1
+#endif
+
+/**
+ * ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached.
+ */
+#if !defined ARP_TABLE_SIZE || defined __DOXYGEN__
+#define ARP_TABLE_SIZE 10
+#endif
+
+/** the time an ARP entry stays valid after its last update,
+ * for ARP_TMR_INTERVAL = 1000, this is
+ * (60 * 5) seconds = 5 minutes.
+ */
+#if !defined ARP_MAXAGE || defined __DOXYGEN__
+#define ARP_MAXAGE 300
+#endif
+
+/**
+ * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address
+ * resolution. By default, only the most recent packet is queued per IP address.
+ * This is sufficient for most protocols and mainly reduces TCP connection
+ * startup time. Set this to 1 if you know your application sends more than one
+ * packet in a row to an IP address that is not in the ARP cache.
+ */
+#if !defined ARP_QUEUEING || defined __DOXYGEN__
+#define ARP_QUEUEING 0
+#endif
+
+/** The maximum number of packets which may be queued for each
+ * unresolved address by other network layers. Defaults to 3, 0 means disabled.
+ * Old packets are dropped, new packets are queued.
+ */
+#if !defined ARP_QUEUE_LEN || defined __DOXYGEN__
+#define ARP_QUEUE_LEN 3
+#endif
+
+/**
+ * ETHARP_SUPPORT_VLAN==1: support receiving and sending ethernet packets with
+ * VLAN header. See the description of LWIP_HOOK_VLAN_CHECK and
+ * LWIP_HOOK_VLAN_SET hooks to check/set VLAN headers.
+ * Additionally, you can define ETHARP_VLAN_CHECK to an u16_t VLAN ID to check.
+ * If ETHARP_VLAN_CHECK is defined, only VLAN-traffic for this VLAN is accepted.
+ * If ETHARP_VLAN_CHECK is not defined, all traffic is accepted.
+ * Alternatively, define a function/define ETHARP_VLAN_CHECK_FN(eth_hdr, vlan)
+ * that returns 1 to accept a packet or 0 to drop a packet.
+ */
+#if !defined ETHARP_SUPPORT_VLAN || defined __DOXYGEN__
+#define ETHARP_SUPPORT_VLAN 0
+#endif
+
+/** LWIP_ETHERNET==1: enable ethernet support even though ARP might be disabled
+ */
+#if !defined LWIP_ETHERNET || defined __DOXYGEN__
+#define LWIP_ETHERNET LWIP_ARP
+#endif
+
+/** ETH_PAD_SIZE: number of bytes added before the ethernet header to ensure
+ * alignment of payload after that header. Since the header is 14 bytes long,
+ * without this padding e.g. addresses in the IP header will not be aligned
+ * on a 32-bit boundary, so setting this to 2 can speed up 32-bit-platforms.
+ */
+#if !defined ETH_PAD_SIZE || defined __DOXYGEN__
+#define ETH_PAD_SIZE 0
+#endif
+
+/** ETHARP_SUPPORT_STATIC_ENTRIES==1: enable code to support static ARP table
+ * entries (using etharp_add_static_entry/etharp_remove_static_entry).
+ */
+#if !defined ETHARP_SUPPORT_STATIC_ENTRIES || defined __DOXYGEN__
+#define ETHARP_SUPPORT_STATIC_ENTRIES 0
+#endif
+
+/** ETHARP_TABLE_MATCH_NETIF==1: Match netif for ARP table entries.
+ * If disabled, duplicate IP address on multiple netifs are not supported
+ * (but this should only occur for AutoIP).
+ */
+#if !defined ETHARP_TABLE_MATCH_NETIF || defined __DOXYGEN__
+#define ETHARP_TABLE_MATCH_NETIF 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ --------------------------------
+ ---------- IP options ----------
+ --------------------------------
+*/
+/**
+ * @defgroup lwip_opts_ipv4 IPv4
+ * @ingroup lwip_opts
+ * @{
+ */
+/**
+ * LWIP_IPV4==1: Enable IPv4
+ */
+#if !defined LWIP_IPV4 || defined __DOXYGEN__
+#define LWIP_IPV4 1
+#endif
+
+/**
+ * IP_FORWARD==1: Enables the ability to forward IP packets across network
+ * interfaces. If you are going to run lwIP on a device with only one network
+ * interface, define this to 0.
+ */
+#if !defined IP_FORWARD || defined __DOXYGEN__
+#define IP_FORWARD 0
+#endif
+
+/**
+ * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that
+ * this option does not affect outgoing packet sizes, which can be controlled
+ * via IP_FRAG.
+ */
+#if !defined IP_REASSEMBLY || defined __DOXYGEN__
+#define IP_REASSEMBLY 1
+#endif
+
+/**
+ * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note
+ * that this option does not affect incoming packet sizes, which can be
+ * controlled via IP_REASSEMBLY.
+ */
+#if !defined IP_FRAG || defined __DOXYGEN__
+#define IP_FRAG 1
+#endif
+
+#if !LWIP_IPV4
+/* disable IPv4 extensions when IPv4 is disabled */
+#undef IP_FORWARD
+#define IP_FORWARD 0
+#undef IP_REASSEMBLY
+#define IP_REASSEMBLY 0
+#undef IP_FRAG
+#define IP_FRAG 0
+#endif /* !LWIP_IPV4 */
+
+/**
+ * IP_OPTIONS_ALLOWED: Defines the behavior for IP options.
+ * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped.
+ * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed).
+ */
+#if !defined IP_OPTIONS_ALLOWED || defined __DOXYGEN__
+#define IP_OPTIONS_ALLOWED 1
+#endif
+
+/**
+ * IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally)
+ * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived
+ * in this time, the whole packet is discarded.
+ */
+#if !defined IP_REASS_MAXAGE || defined __DOXYGEN__
+#define IP_REASS_MAXAGE 3
+#endif
+
+/**
+ * IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled.
+ * Since the received pbufs are enqueued, be sure to configure
+ * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive
+ * packets even if the maximum amount of fragments is enqueued for reassembly!
+ */
+#if !defined IP_REASS_MAX_PBUFS || defined __DOXYGEN__
+#define IP_REASS_MAX_PBUFS 10
+#endif
+
+/**
+ * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers.
+ */
+#if !defined IP_DEFAULT_TTL || defined __DOXYGEN__
+#define IP_DEFAULT_TTL 255
+#endif
+
+/**
+ * IP_SOF_BROADCAST=1: Use the SOF_BROADCAST field to enable broadcast
+ * filter per pcb on udp and raw send operations. To enable broadcast filter
+ * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1.
+ */
+#if !defined IP_SOF_BROADCAST || defined __DOXYGEN__
+#define IP_SOF_BROADCAST 0
+#endif
+
+/**
+ * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enable the broadcast
+ * filter on recv operations.
+ */
+#if !defined IP_SOF_BROADCAST_RECV || defined __DOXYGEN__
+#define IP_SOF_BROADCAST_RECV 0
+#endif
+
+/**
+ * IP_FORWARD_ALLOW_TX_ON_RX_NETIF==1: allow ip_forward() to send packets back
+ * out on the netif where it was received. This should only be used for
+ * wireless networks.
+ * ATTENTION: When this is 1, make sure your netif driver correctly marks incoming
+ * link-layer-broadcast/multicast packets as such using the corresponding pbuf flags!
+ */
+#if !defined IP_FORWARD_ALLOW_TX_ON_RX_NETIF || defined __DOXYGEN__
+#define IP_FORWARD_ALLOW_TX_ON_RX_NETIF 0
+#endif
+
+/**
+ * LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS==1: randomize the local port for the first
+ * local TCP/UDP pcb (default==0). This can prevent creating predictable port
+ * numbers after booting a device.
+ */
+#if !defined LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS || defined __DOXYGEN__
+#define LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ---------- ICMP options ----------
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_icmp ICMP
+ * @ingroup lwip_opts_ipv4
+ * @{
+ */
+/**
+ * LWIP_ICMP==1: Enable ICMP module inside the IP stack.
+ * Be careful, disable that make your product non-compliant to RFC1122
+ */
+#if !defined LWIP_ICMP || defined __DOXYGEN__
+#define LWIP_ICMP 1
+#endif
+
+/**
+ * ICMP_TTL: Default value for Time-To-Live used by ICMP packets.
+ */
+#if !defined ICMP_TTL || defined __DOXYGEN__
+#define ICMP_TTL (IP_DEFAULT_TTL)
+#endif
+
+/**
+ * LWIP_BROADCAST_PING==1: respond to broadcast pings (default is unicast only)
+ */
+#if !defined LWIP_BROADCAST_PING || defined __DOXYGEN__
+#define LWIP_BROADCAST_PING 0
+#endif
+
+/**
+ * LWIP_MULTICAST_PING==1: respond to multicast pings (default is unicast only)
+ */
+#if !defined LWIP_MULTICAST_PING || defined __DOXYGEN__
+#define LWIP_MULTICAST_PING 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------
+ ---------- RAW options ----------
+ ---------------------------------
+*/
+/**
+ * @defgroup lwip_opts_raw RAW
+ * @ingroup lwip_opts_callback
+ * @{
+ */
+/**
+ * LWIP_RAW==1: Enable application layer to hook into the IP layer itself.
+ */
+#if !defined LWIP_RAW || defined __DOXYGEN__
+#define LWIP_RAW 0
+#endif
+
+/**
+ * LWIP_RAW==1: Enable application layer to hook into the IP layer itself.
+ */
+#if !defined RAW_TTL || defined __DOXYGEN__
+#define RAW_TTL (IP_DEFAULT_TTL)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ---------- DHCP options ----------
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_dhcp DHCP
+ * @ingroup lwip_opts_ipv4
+ * @{
+ */
+/**
+ * LWIP_DHCP==1: Enable DHCP module.
+ */
+#if !defined LWIP_DHCP || defined __DOXYGEN__
+#define LWIP_DHCP 0
+#endif
+#if !LWIP_IPV4
+/* disable DHCP when IPv4 is disabled */
+#undef LWIP_DHCP
+#define LWIP_DHCP 0
+#endif /* !LWIP_IPV4 */
+
+/**
+ * DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address.
+ */
+#if !defined DHCP_DOES_ARP_CHECK || defined __DOXYGEN__
+#define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP))
+#endif
+
+/**
+ * LWIP_DHCP_CHECK_LINK_UP==1: dhcp_start() only really starts if the netif has
+ * NETIF_FLAG_LINK_UP set in its flags. As this is only an optimization and
+ * netif drivers might not set this flag, the default is off. If enabled,
+ * netif_set_link_up() must be called to continue dhcp starting.
+ */
+#if !defined LWIP_DHCP_CHECK_LINK_UP
+#define LWIP_DHCP_CHECK_LINK_UP 0
+#endif
+
+/**
+ * LWIP_DHCP_BOOTP_FILE==1: Store offered_si_addr and boot_file_name.
+ */
+#if !defined LWIP_DHCP_BOOTP_FILE || defined __DOXYGEN__
+#define LWIP_DHCP_BOOTP_FILE 0
+#endif
+
+/**
+ * LWIP_DHCP_GETS_NTP==1: Request NTP servers with discover/select. For each
+ * response packet, an callback is called, which has to be provided by the port:
+ * void dhcp_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs);
+*/
+#if !defined LWIP_DHCP_GET_NTP_SRV || defined __DOXYGEN__
+#define LWIP_DHCP_GET_NTP_SRV 0
+#endif
+
+/**
+ * The maximum of NTP servers requested
+ */
+#if !defined LWIP_DHCP_MAX_NTP_SERVERS || defined __DOXYGEN__
+#define LWIP_DHCP_MAX_NTP_SERVERS 1
+#endif
+
+/**
+ * LWIP_DHCP_MAX_DNS_SERVERS > 0: Request DNS servers with discover/select.
+ * DHCP servers received in the response are passed to DNS via @ref dns_setserver()
+ * (up to the maximum limit defined here).
+ */
+#if !defined LWIP_DHCP_MAX_DNS_SERVERS || defined __DOXYGEN__
+#define LWIP_DHCP_MAX_DNS_SERVERS DNS_MAX_SERVERS
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ---------- AUTOIP options ----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_autoip AUTOIP
+ * @ingroup lwip_opts_ipv4
+ * @{
+ */
+/**
+ * LWIP_AUTOIP==1: Enable AUTOIP module.
+ */
+#if !defined LWIP_AUTOIP || defined __DOXYGEN__
+#define LWIP_AUTOIP 0
+#endif
+#if !LWIP_IPV4
+/* disable AUTOIP when IPv4 is disabled */
+#undef LWIP_AUTOIP
+#define LWIP_AUTOIP 0
+#endif /* !LWIP_IPV4 */
+
+/**
+ * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on
+ * the same interface at the same time.
+ */
+#if !defined LWIP_DHCP_AUTOIP_COOP || defined __DOXYGEN__
+#define LWIP_DHCP_AUTOIP_COOP 0
+#endif
+
+/**
+ * LWIP_DHCP_AUTOIP_COOP_TRIES: Set to the number of DHCP DISCOVER probes
+ * that should be sent before falling back on AUTOIP (the DHCP client keeps
+ * running in this case). This can be set as low as 1 to get an AutoIP address
+ * very quickly, but you should be prepared to handle a changing IP address
+ * when DHCP overrides AutoIP.
+ */
+#if !defined LWIP_DHCP_AUTOIP_COOP_TRIES || defined __DOXYGEN__
+#define LWIP_DHCP_AUTOIP_COOP_TRIES 9
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ----- SNMP MIB2 support -----
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_mib2 SNMP MIB2 callbacks
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * LWIP_MIB2_CALLBACKS==1: Turn on SNMP MIB2 callbacks.
+ * Turn this on to get callbacks needed to implement MIB2.
+ * Usually MIB2_STATS should be enabled, too.
+ */
+#if !defined LWIP_MIB2_CALLBACKS || defined __DOXYGEN__
+#define LWIP_MIB2_CALLBACKS 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ----- Multicast/IGMP options -----
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_igmp IGMP
+ * @ingroup lwip_opts_ipv4
+ * @{
+ */
+/**
+ * LWIP_IGMP==1: Turn on IGMP module.
+ */
+#if !defined LWIP_IGMP || defined __DOXYGEN__
+#define LWIP_IGMP 0
+#endif
+#if !LWIP_IPV4
+#undef LWIP_IGMP
+#define LWIP_IGMP 0
+#endif
+
+/**
+ * LWIP_MULTICAST_TX_OPTIONS==1: Enable multicast TX support like the socket options
+ * IP_MULTICAST_TTL/IP_MULTICAST_IF/IP_MULTICAST_LOOP
+ */
+#if !defined LWIP_MULTICAST_TX_OPTIONS || defined __DOXYGEN__
+#define LWIP_MULTICAST_TX_OPTIONS (LWIP_IGMP && LWIP_UDP)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ---------- DNS options -----------
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_dns DNS
+ * @ingroup lwip_opts_callback
+ * @{
+ */
+/**
+ * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS
+ * transport.
+ */
+#if !defined LWIP_DNS || defined __DOXYGEN__
+#define LWIP_DNS 0
+#endif
+
+/** DNS maximum number of entries to maintain locally. */
+#if !defined DNS_TABLE_SIZE || defined __DOXYGEN__
+#define DNS_TABLE_SIZE 4
+#endif
+
+/** DNS maximum host name length supported in the name table. */
+#if !defined DNS_MAX_NAME_LENGTH || defined __DOXYGEN__
+#define DNS_MAX_NAME_LENGTH 256
+#endif
+
+/** The maximum of DNS servers
+ * The first server can be initialized automatically by defining
+ * DNS_SERVER_ADDRESS(ipaddr), where 'ipaddr' is an 'ip_addr_t*'
+ */
+#if !defined DNS_MAX_SERVERS || defined __DOXYGEN__
+#define DNS_MAX_SERVERS 2
+#endif
+
+/** DNS do a name checking between the query and the response. */
+#if !defined DNS_DOES_NAME_CHECK || defined __DOXYGEN__
+#define DNS_DOES_NAME_CHECK 1
+#endif
+
+/** LWIP_DNS_SECURE: controls the security level of the DNS implementation
+ * Use all DNS security features by default.
+ * This is overridable but should only be needed by very small targets
+ * or when using against non standard DNS servers. */
+#if !defined LWIP_DNS_SECURE || defined __DOXYGEN__
+#define LWIP_DNS_SECURE (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)
+#endif
+
+/* A list of DNS security features follows */
+#define LWIP_DNS_SECURE_RAND_XID 1
+#define LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING 2
+#define LWIP_DNS_SECURE_RAND_SRC_PORT 4
+
+/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, you have to define an initializer:
+ * \#define DNS_LOCAL_HOSTLIST_INIT {DNS_LOCAL_HOSTLIST_ELEM("host_ip4", IPADDR4_INIT_BYTES(1,2,3,4)), \
+ * DNS_LOCAL_HOSTLIST_ELEM("host_ip6", IPADDR6_INIT_HOST(123, 234, 345, 456)}
+ *
+ * Instead, you can also use an external function:
+ * \#define DNS_LOOKUP_LOCAL_EXTERN(x) extern err_t my_lookup_function(const char *name, ip_addr_t *addr, u8_t dns_addrtype)
+ * that looks up the IP address and returns ERR_OK if found (LWIP_DNS_ADDRTYPE_xxx is passed in dns_addrtype).
+ */
+#if !defined DNS_LOCAL_HOSTLIST || defined __DOXYGEN__
+#define DNS_LOCAL_HOSTLIST 0
+#endif /* DNS_LOCAL_HOSTLIST */
+
+/** If this is turned on, the local host-list can be dynamically changed
+ * at runtime. */
+#if !defined DNS_LOCAL_HOSTLIST_IS_DYNAMIC || defined __DOXYGEN__
+#define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0
+#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+
+/** Set this to 1 to enable querying ".local" names via mDNS
+ * using a One-Shot Multicast DNS Query */
+#if !defined LWIP_DNS_SUPPORT_MDNS_QUERIES || defined __DOXYGEN__
+#define LWIP_DNS_SUPPORT_MDNS_QUERIES 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------
+ ---------- UDP options ----------
+ ---------------------------------
+*/
+/**
+ * @defgroup lwip_opts_udp UDP
+ * @ingroup lwip_opts_callback
+ * @{
+ */
+/**
+ * LWIP_UDP==1: Turn on UDP.
+ */
+#if !defined LWIP_UDP || defined __DOXYGEN__
+#define LWIP_UDP 1
+#endif
+
+/**
+ * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP)
+ */
+#if !defined LWIP_UDPLITE || defined __DOXYGEN__
+#define LWIP_UDPLITE 0
+#endif
+
+/**
+ * UDP_TTL: Default Time-To-Live value.
+ */
+#if !defined UDP_TTL || defined __DOXYGEN__
+#define UDP_TTL (IP_DEFAULT_TTL)
+#endif
+
+/**
+ * LWIP_NETBUF_RECVINFO==1: append destination addr and port to every netbuf.
+ */
+#if !defined LWIP_NETBUF_RECVINFO || defined __DOXYGEN__
+#define LWIP_NETBUF_RECVINFO 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------
+ ---------- TCP options ----------
+ ---------------------------------
+*/
+/**
+ * @defgroup lwip_opts_tcp TCP
+ * @ingroup lwip_opts_callback
+ * @{
+ */
+/**
+ * LWIP_TCP==1: Turn on TCP.
+ */
+#if !defined LWIP_TCP || defined __DOXYGEN__
+#define LWIP_TCP 1
+#endif
+
+/**
+ * TCP_TTL: Default Time-To-Live value.
+ */
+#if !defined TCP_TTL || defined __DOXYGEN__
+#define TCP_TTL (IP_DEFAULT_TTL)
+#endif
+
+/**
+ * TCP_WND: The size of a TCP window. This must be at least
+ * (2 * TCP_MSS) for things to work well.
+ * ATTENTION: when using TCP_RCV_SCALE, TCP_WND is the total size
+ * with scaling applied. Maximum window value in the TCP header
+ * will be TCP_WND >> TCP_RCV_SCALE
+ */
+#if !defined TCP_WND || defined __DOXYGEN__
+#define TCP_WND (4 * TCP_MSS)
+#endif
+
+/**
+ * TCP_MAXRTX: Maximum number of retransmissions of data segments.
+ */
+#if !defined TCP_MAXRTX || defined __DOXYGEN__
+#define TCP_MAXRTX 12
+#endif
+
+/**
+ * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments.
+ */
+#if !defined TCP_SYNMAXRTX || defined __DOXYGEN__
+#define TCP_SYNMAXRTX 6
+#endif
+
+/**
+ * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order.
+ * Define to 0 if your device is low on memory.
+ */
+#if !defined TCP_QUEUE_OOSEQ || defined __DOXYGEN__
+#define TCP_QUEUE_OOSEQ (LWIP_TCP)
+#endif
+
+/**
+ * TCP_MSS: TCP Maximum segment size. (default is 536, a conservative default,
+ * you might want to increase this.)
+ * For the receive side, this MSS is advertised to the remote side
+ * when opening a connection. For the transmit size, this MSS sets
+ * an upper limit on the MSS advertised by the remote host.
+ */
+#if !defined TCP_MSS || defined __DOXYGEN__
+#define TCP_MSS 536
+#endif
+
+/**
+ * TCP_CALCULATE_EFF_SEND_MSS: "The maximum size of a segment that TCP really
+ * sends, the 'effective send MSS,' MUST be the smaller of the send MSS (which
+ * reflects the available reassembly buffer size at the remote host) and the
+ * largest size permitted by the IP layer" (RFC 1122)
+ * Setting this to 1 enables code that checks TCP_MSS against the MTU of the
+ * netif used for a connection and limits the MSS if it would be too big otherwise.
+ */
+#if !defined TCP_CALCULATE_EFF_SEND_MSS || defined __DOXYGEN__
+#define TCP_CALCULATE_EFF_SEND_MSS 1
+#endif
+
+/**
+ * TCP_SND_BUF: TCP sender buffer space (bytes).
+ * To achieve good performance, this should be at least 2 * TCP_MSS.
+ */
+#if !defined TCP_SND_BUF || defined __DOXYGEN__
+#define TCP_SND_BUF (2 * TCP_MSS)
+#endif
+
+/**
+ * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least
+ * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work.
+ */
+#if !defined TCP_SND_QUEUELEN || defined __DOXYGEN__
+#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1))/(TCP_MSS))
+#endif
+
+/**
+ * TCP_SNDLOWAT: TCP writable space (bytes). This must be less than
+ * TCP_SND_BUF. It is the amount of space which must be available in the
+ * TCP snd_buf for select to return writable (combined with TCP_SNDQUEUELOWAT).
+ */
+#if !defined TCP_SNDLOWAT || defined __DOXYGEN__
+#define TCP_SNDLOWAT LWIP_MIN(LWIP_MAX(((TCP_SND_BUF)/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF) - 1)
+#endif
+
+/**
+ * TCP_SNDQUEUELOWAT: TCP writable bufs (pbuf count). This must be less
+ * than TCP_SND_QUEUELEN. If the number of pbufs queued on a pcb drops below
+ * this number, select returns writable (combined with TCP_SNDLOWAT).
+ */
+#if !defined TCP_SNDQUEUELOWAT || defined __DOXYGEN__
+#define TCP_SNDQUEUELOWAT LWIP_MAX(((TCP_SND_QUEUELEN)/2), 5)
+#endif
+
+/**
+ * TCP_OOSEQ_MAX_BYTES: The maximum number of bytes queued on ooseq per pcb.
+ * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1.
+ */
+#if !defined TCP_OOSEQ_MAX_BYTES || defined __DOXYGEN__
+#define TCP_OOSEQ_MAX_BYTES 0
+#endif
+
+/**
+ * TCP_OOSEQ_MAX_PBUFS: The maximum number of pbufs queued on ooseq per pcb.
+ * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1.
+ */
+#if !defined TCP_OOSEQ_MAX_PBUFS || defined __DOXYGEN__
+#define TCP_OOSEQ_MAX_PBUFS 0
+#endif
+
+/**
+ * TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb.
+ */
+#if !defined TCP_LISTEN_BACKLOG || defined __DOXYGEN__
+#define TCP_LISTEN_BACKLOG 0
+#endif
+
+/**
+ * The maximum allowed backlog for TCP listen netconns.
+ * This backlog is used unless another is explicitly specified.
+ * 0xff is the maximum (u8_t).
+ */
+#if !defined TCP_DEFAULT_LISTEN_BACKLOG || defined __DOXYGEN__
+#define TCP_DEFAULT_LISTEN_BACKLOG 0xff
+#endif
+
+/**
+ * TCP_OVERSIZE: The maximum number of bytes that tcp_write may
+ * allocate ahead of time in an attempt to create shorter pbuf chains
+ * for transmission. The meaningful range is 0 to TCP_MSS. Some
+ * suggested values are:
+ *
+ * 0: Disable oversized allocation. Each tcp_write() allocates a new
+ pbuf (old behaviour).
+ * 1: Allocate size-aligned pbufs with minimal excess. Use this if your
+ * scatter-gather DMA requires aligned fragments.
+ * 128: Limit the pbuf/memory overhead to 20%.
+ * TCP_MSS: Try to create unfragmented TCP packets.
+ * TCP_MSS/4: Try to create 4 fragments or less per TCP packet.
+ */
+#if !defined TCP_OVERSIZE || defined __DOXYGEN__
+#define TCP_OVERSIZE TCP_MSS
+#endif
+
+/**
+ * LWIP_TCP_TIMESTAMPS==1: support the TCP timestamp option.
+ * The timestamp option is currently only used to help remote hosts, it is not
+ * really used locally. Therefore, it is only enabled when a TS option is
+ * received in the initial SYN packet from a remote host.
+ */
+#if !defined LWIP_TCP_TIMESTAMPS || defined __DOXYGEN__
+#define LWIP_TCP_TIMESTAMPS 0
+#endif
+
+/**
+ * TCP_WND_UPDATE_THRESHOLD: difference in window to trigger an
+ * explicit window update
+ */
+#if !defined TCP_WND_UPDATE_THRESHOLD || defined __DOXYGEN__
+#define TCP_WND_UPDATE_THRESHOLD LWIP_MIN((TCP_WND / 4), (TCP_MSS * 4))
+#endif
+
+/**
+ * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1.
+ * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all
+ * events (accept, sent, etc) that happen in the system.
+ * LWIP_CALLBACK_API==1: The PCB callback function is called directly
+ * for the event. This is the default.
+ */
+#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) || defined __DOXYGEN__
+#define LWIP_EVENT_API 0
+#define LWIP_CALLBACK_API 1
+#else
+#ifndef LWIP_EVENT_API
+#define LWIP_EVENT_API 0
+#endif
+#ifndef LWIP_CALLBACK_API
+#define LWIP_CALLBACK_API 0
+#endif
+#endif
+
+/**
+ * LWIP_WND_SCALE and TCP_RCV_SCALE:
+ * Set LWIP_WND_SCALE to 1 to enable window scaling.
+ * Set TCP_RCV_SCALE to the desired scaling factor (shift count in the
+ * range of [0..14]).
+ * When LWIP_WND_SCALE is enabled but TCP_RCV_SCALE is 0, we can use a large
+ * send window while having a small receive window only.
+ */
+#if !defined LWIP_WND_SCALE || defined __DOXYGEN__
+#define LWIP_WND_SCALE 0
+#define TCP_RCV_SCALE 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------
+ ---------- Pbuf options ----------
+ ----------------------------------
+*/
+/**
+ * @defgroup lwip_opts_pbuf PBUF
+ * @ingroup lwip_opts
+ * @{
+ */
+/**
+ * PBUF_LINK_HLEN: the number of bytes that should be allocated for a
+ * link level header. The default is 14, the standard value for
+ * Ethernet.
+ */
+#if !defined PBUF_LINK_HLEN || defined __DOXYGEN__
+#if defined LWIP_HOOK_VLAN_SET && !defined __DOXYGEN__
+#define PBUF_LINK_HLEN (18 + ETH_PAD_SIZE)
+#else /* LWIP_HOOK_VLAN_SET */
+#define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE)
+#endif /* LWIP_HOOK_VLAN_SET */
+#endif
+
+/**
+ * PBUF_LINK_ENCAPSULATION_HLEN: the number of bytes that should be allocated
+ * for an additional encapsulation header before ethernet headers (e.g. 802.11)
+ */
+#if !defined PBUF_LINK_ENCAPSULATION_HLEN || defined __DOXYGEN__
+#define PBUF_LINK_ENCAPSULATION_HLEN 0u
+#endif
+
+/**
+ * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is
+ * designed to accommodate single full size TCP frame in one pbuf, including
+ * TCP_MSS, IP header, and link header.
+ */
+#if !defined PBUF_POOL_BUFSIZE || defined __DOXYGEN__
+#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_ENCAPSULATION_HLEN+PBUF_LINK_HLEN)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------------------
+ ---------- Network Interfaces options ----------
+ ------------------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_netif NETIF
+ * @ingroup lwip_opts
+ * @{
+ */
+/**
+ * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname
+ * field.
+ */
+#if !defined LWIP_NETIF_HOSTNAME || defined __DOXYGEN__
+#define LWIP_NETIF_HOSTNAME 0
+#endif
+
+/**
+ * LWIP_NETIF_API==1: Support netif api (in netifapi.c)
+ */
+#if !defined LWIP_NETIF_API || defined __DOXYGEN__
+#define LWIP_NETIF_API 0
+#endif
+
+/**
+ * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface
+ * changes its up/down status (i.e., due to DHCP IP acquisition)
+ */
+#if !defined LWIP_NETIF_STATUS_CALLBACK || defined __DOXYGEN__
+#define LWIP_NETIF_STATUS_CALLBACK 0
+#endif
+
+/**
+ * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface
+ * whenever the link changes (i.e., link down)
+ */
+#if !defined LWIP_NETIF_LINK_CALLBACK || defined __DOXYGEN__
+#define LWIP_NETIF_LINK_CALLBACK 0
+#endif
+
+/**
+ * LWIP_NETIF_REMOVE_CALLBACK==1: Support a callback function that is called
+ * when a netif has been removed
+ */
+#if !defined LWIP_NETIF_REMOVE_CALLBACK || defined __DOXYGEN__
+#define LWIP_NETIF_REMOVE_CALLBACK 0
+#endif
+
+/**
+ * LWIP_NETIF_HWADDRHINT==1: Cache link-layer-address hints (e.g. table
+ * indices) in struct netif. TCP and UDP can make use of this to prevent
+ * scanning the ARP table for every sent packet. While this is faster for big
+ * ARP tables or many concurrent connections, it might be counterproductive
+ * if you have a tiny ARP table or if there never are concurrent connections.
+ */
+#if !defined LWIP_NETIF_HWADDRHINT || defined __DOXYGEN__
+#define LWIP_NETIF_HWADDRHINT 0
+#endif
+
+/**
+ * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data
+ * to be sent into one single pbuf. This is for compatibility with DMA-enabled
+ * MACs that do not support scatter-gather.
+ * Beware that this might involve CPU-memcpy before transmitting that would not
+ * be needed without this flag! Use this only if you need to!
+ *
+ * @todo: TCP and IP-frag do not work with this, yet:
+ */
+#if !defined LWIP_NETIF_TX_SINGLE_PBUF || defined __DOXYGEN__
+#define LWIP_NETIF_TX_SINGLE_PBUF 0
+#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
+
+/**
+ * LWIP_NUM_NETIF_CLIENT_DATA: Number of clients that may store
+ * data in client_data member array of struct netif.
+ */
+#if !defined LWIP_NUM_NETIF_CLIENT_DATA || defined __DOXYGEN__
+#define LWIP_NUM_NETIF_CLIENT_DATA 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ---------- LOOPIF options ----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_loop Loopback interface
+ * @ingroup lwip_opts_netif
+ * @{
+ */
+/**
+ * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1).
+ * This is only needed when no real netifs are available. If at least one other
+ * netif is available, loopback traffic uses this netif.
+ */
+#if !defined LWIP_HAVE_LOOPIF || defined __DOXYGEN__
+#define LWIP_HAVE_LOOPIF LWIP_NETIF_LOOPBACK
+#endif
+
+/**
+ * LWIP_LOOPIF_MULTICAST==1: Support multicast/IGMP on loop interface (127.0.0.1).
+ */
+#if !defined LWIP_LOOPIF_MULTICAST || defined __DOXYGEN__
+#define LWIP_LOOPIF_MULTICAST 0
+#endif
+
+/**
+ * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP
+ * address equal to the netif IP address, looping them back up the stack.
+ */
+#if !defined LWIP_NETIF_LOOPBACK || defined __DOXYGEN__
+#define LWIP_NETIF_LOOPBACK 0
+#endif
+
+/**
+ * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback
+ * sending for each netif (0 = disabled)
+ */
+#if !defined LWIP_LOOPBACK_MAX_PBUFS || defined __DOXYGEN__
+#define LWIP_LOOPBACK_MAX_PBUFS 0
+#endif
+
+/**
+ * LWIP_NETIF_LOOPBACK_MULTITHREADING: Indicates whether threading is enabled in
+ * the system, as netifs must change how they behave depending on this setting
+ * for the LWIP_NETIF_LOOPBACK option to work.
+ * Setting this is needed to avoid reentering non-reentrant functions like
+ * tcp_input().
+ * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a
+ * multithreaded environment like tcpip.c. In this case, netif->input()
+ * is called directly.
+ * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup.
+ * The packets are put on a list and netif_poll() must be called in
+ * the main application loop.
+ */
+#if !defined LWIP_NETIF_LOOPBACK_MULTITHREADING || defined __DOXYGEN__
+#define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ---------- Thread options ----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_thread Threading
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread.
+ */
+#if !defined TCPIP_THREAD_NAME || defined __DOXYGEN__
+#define TCPIP_THREAD_NAME "tcpip_thread"
+#endif
+
+/**
+ * TCPIP_THREAD_STACKSIZE: The stack size used by the main tcpip thread.
+ * The stack size value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined TCPIP_THREAD_STACKSIZE || defined __DOXYGEN__
+#define TCPIP_THREAD_STACKSIZE 0
+#endif
+
+/**
+ * TCPIP_THREAD_PRIO: The priority assigned to the main tcpip thread.
+ * The priority value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined TCPIP_THREAD_PRIO || defined __DOXYGEN__
+#define TCPIP_THREAD_PRIO 1
+#endif
+
+/**
+ * TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages
+ * The queue size value itself is platform-dependent, but is passed to
+ * sys_mbox_new() when tcpip_init is called.
+ */
+#if !defined TCPIP_MBOX_SIZE || defined __DOXYGEN__
+#define TCPIP_MBOX_SIZE 0
+#endif
+
+/**
+ * Define this to something that triggers a watchdog. This is called from
+ * tcpip_thread after processing a message.
+ */
+#if !defined LWIP_TCPIP_THREAD_ALIVE || defined __DOXYGEN__
+#define LWIP_TCPIP_THREAD_ALIVE()
+#endif
+
+/**
+ * SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread.
+ */
+#if !defined SLIPIF_THREAD_NAME || defined __DOXYGEN__
+#define SLIPIF_THREAD_NAME "slipif_loop"
+#endif
+
+/**
+ * SLIP_THREAD_STACKSIZE: The stack size used by the slipif_loop thread.
+ * The stack size value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined SLIPIF_THREAD_STACKSIZE || defined __DOXYGEN__
+#define SLIPIF_THREAD_STACKSIZE 0
+#endif
+
+/**
+ * SLIPIF_THREAD_PRIO: The priority assigned to the slipif_loop thread.
+ * The priority value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined SLIPIF_THREAD_PRIO || defined __DOXYGEN__
+#define SLIPIF_THREAD_PRIO 1
+#endif
+
+/**
+ * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread.
+ */
+#if !defined DEFAULT_THREAD_NAME || defined __DOXYGEN__
+#define DEFAULT_THREAD_NAME "lwIP"
+#endif
+
+/**
+ * DEFAULT_THREAD_STACKSIZE: The stack size used by any other lwIP thread.
+ * The stack size value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined DEFAULT_THREAD_STACKSIZE || defined __DOXYGEN__
+#define DEFAULT_THREAD_STACKSIZE 0
+#endif
+
+/**
+ * DEFAULT_THREAD_PRIO: The priority assigned to any other lwIP thread.
+ * The priority value itself is platform-dependent, but is passed to
+ * sys_thread_new() when the thread is created.
+ */
+#if !defined DEFAULT_THREAD_PRIO || defined __DOXYGEN__
+#define DEFAULT_THREAD_PRIO 1
+#endif
+
+/**
+ * DEFAULT_RAW_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
+ * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed
+ * to sys_mbox_new() when the recvmbox is created.
+ */
+#if !defined DEFAULT_RAW_RECVMBOX_SIZE || defined __DOXYGEN__
+#define DEFAULT_RAW_RECVMBOX_SIZE 0
+#endif
+
+/**
+ * DEFAULT_UDP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
+ * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed
+ * to sys_mbox_new() when the recvmbox is created.
+ */
+#if !defined DEFAULT_UDP_RECVMBOX_SIZE || defined __DOXYGEN__
+#define DEFAULT_UDP_RECVMBOX_SIZE 0
+#endif
+
+/**
+ * DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
+ * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed
+ * to sys_mbox_new() when the recvmbox is created.
+ */
+#if !defined DEFAULT_TCP_RECVMBOX_SIZE || defined __DOXYGEN__
+#define DEFAULT_TCP_RECVMBOX_SIZE 0
+#endif
+
+/**
+ * DEFAULT_ACCEPTMBOX_SIZE: The mailbox size for the incoming connections.
+ * The queue size value itself is platform-dependent, but is passed to
+ * sys_mbox_new() when the acceptmbox is created.
+ */
+#if !defined DEFAULT_ACCEPTMBOX_SIZE || defined __DOXYGEN__
+#define DEFAULT_ACCEPTMBOX_SIZE 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------------------
+ ---------- Sequential layer options ----------
+ ----------------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_netconn Netconn
+ * @ingroup lwip_opts_threadsafe_apis
+ * @{
+ */
+/**
+ * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c)
+ */
+#if !defined LWIP_NETCONN || defined __DOXYGEN__
+#define LWIP_NETCONN 1
+#endif
+
+/** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout to create
+ * timers running in tcpip_thread from another thread.
+ */
+#if !defined LWIP_TCPIP_TIMEOUT || defined __DOXYGEN__
+#define LWIP_TCPIP_TIMEOUT 0
+#endif
+
+/** LWIP_NETCONN_SEM_PER_THREAD==1: Use one (thread-local) semaphore per
+ * thread calling socket/netconn functions instead of allocating one
+ * semaphore per netconn (and per select etc.)
+ * ATTENTION: a thread-local semaphore for API calls is needed:
+ * - LWIP_NETCONN_THREAD_SEM_GET() returning a sys_sem_t*
+ * - LWIP_NETCONN_THREAD_SEM_ALLOC() creating the semaphore
+ * - LWIP_NETCONN_THREAD_SEM_FREE() freeing the semaphore
+ * The latter 2 can be invoked up by calling netconn_thread_init()/netconn_thread_cleanup().
+ * Ports may call these for threads created with sys_thread_new().
+ */
+#if !defined LWIP_NETCONN_SEM_PER_THREAD || defined __DOXYGEN__
+#define LWIP_NETCONN_SEM_PER_THREAD 0
+#endif
+
+/** LWIP_NETCONN_FULLDUPLEX==1: Enable code that allows reading from one thread,
+ * writing from a 2nd thread and closing from a 3rd thread at the same time.
+ * ATTENTION: This is currently really alpha! Some requirements:
+ * - LWIP_NETCONN_SEM_PER_THREAD==1 is required to use one socket/netconn from
+ * multiple threads at once
+ * - sys_mbox_free() has to unblock receive tasks waiting on recvmbox/acceptmbox
+ * and prevent a task pending on this during/after deletion
+ */
+#if !defined LWIP_NETCONN_FULLDUPLEX || defined __DOXYGEN__
+#define LWIP_NETCONN_FULLDUPLEX 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ------------------------------------
+ ---------- Socket options ----------
+ ------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_socket Sockets
+ * @ingroup lwip_opts_threadsafe_apis
+ * @{
+ */
+/**
+ * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c)
+ */
+#if !defined LWIP_SOCKET || defined __DOXYGEN__
+#define LWIP_SOCKET 1
+#endif
+
+/* LWIP_SOCKET_SET_ERRNO==1: Set errno when socket functions cannot complete
+ * successfully, as required by POSIX. Default is POSIX-compliant.
+ */
+#if !defined LWIP_SOCKET_SET_ERRNO || defined __DOXYGEN__
+#define LWIP_SOCKET_SET_ERRNO 1
+#endif
+
+/**
+ * LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names through defines.
+ * LWIP_COMPAT_SOCKETS==2: Same as ==1 but correctly named functions are created.
+ * While this helps code completion, it might conflict with existing libraries.
+ * (only used if you use sockets.c)
+ */
+#if !defined LWIP_COMPAT_SOCKETS || defined __DOXYGEN__
+#define LWIP_COMPAT_SOCKETS 1
+#endif
+
+/**
+ * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names.
+ * Disable this option if you use a POSIX operating system that uses the same
+ * names (read, write & close). (only used if you use sockets.c)
+ */
+#if !defined LWIP_POSIX_SOCKETS_IO_NAMES || defined __DOXYGEN__
+#define LWIP_POSIX_SOCKETS_IO_NAMES 1
+#endif
+
+/**
+ * LWIP_SOCKET_OFFSET==n: Increases the file descriptor number created by LwIP with n.
+ * This can be useful when there are multiple APIs which create file descriptors.
+ * When they all start with a different offset and you won't make them overlap you can
+ * re implement read/write/close/ioctl/fnctl to send the requested action to the right
+ * library (sharing select will need more work though).
+ */
+#if !defined LWIP_SOCKET_OFFSET || defined __DOXYGEN__
+#define LWIP_SOCKET_OFFSET 0
+#endif
+
+/**
+ * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT
+ * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set
+ * in seconds. (does not require sockets.c, and will affect tcp.c)
+ */
+#if !defined LWIP_TCP_KEEPALIVE || defined __DOXYGEN__
+#define LWIP_TCP_KEEPALIVE 0
+#endif
+
+/**
+ * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and
+ * SO_SNDTIMEO processing.
+ */
+#if !defined LWIP_SO_SNDTIMEO || defined __DOXYGEN__
+#define LWIP_SO_SNDTIMEO 0
+#endif
+
+/**
+ * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and
+ * SO_RCVTIMEO processing.
+ */
+#if !defined LWIP_SO_RCVTIMEO || defined __DOXYGEN__
+#define LWIP_SO_RCVTIMEO 0
+#endif
+
+/**
+ * LWIP_SO_SNDRCVTIMEO_NONSTANDARD==1: SO_RCVTIMEO/SO_SNDTIMEO take an int
+ * (milliseconds, much like winsock does) instead of a struct timeval (default).
+ */
+#if !defined LWIP_SO_SNDRCVTIMEO_NONSTANDARD || defined __DOXYGEN__
+#define LWIP_SO_SNDRCVTIMEO_NONSTANDARD 0
+#endif
+
+/**
+ * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing.
+ */
+#if !defined LWIP_SO_RCVBUF || defined __DOXYGEN__
+#define LWIP_SO_RCVBUF 0
+#endif
+
+/**
+ * LWIP_SO_LINGER==1: Enable SO_LINGER processing.
+ */
+#if !defined LWIP_SO_LINGER || defined __DOXYGEN__
+#define LWIP_SO_LINGER 0
+#endif
+
+/**
+ * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize.
+ */
+#if !defined RECV_BUFSIZE_DEFAULT || defined __DOXYGEN__
+#define RECV_BUFSIZE_DEFAULT INT_MAX
+#endif
+
+/**
+ * By default, TCP socket/netconn close waits 20 seconds max to send the FIN
+ */
+#if !defined LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT || defined __DOXYGEN__
+#define LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT 20000
+#endif
+
+/**
+ * SO_REUSE==1: Enable SO_REUSEADDR option.
+ */
+#if !defined SO_REUSE || defined __DOXYGEN__
+#define SO_REUSE 0
+#endif
+
+/**
+ * SO_REUSE_RXTOALL==1: Pass a copy of incoming broadcast/multicast packets
+ * to all local matches if SO_REUSEADDR is turned on.
+ * WARNING: Adds a memcpy for every packet if passing to more than one pcb!
+ */
+#if !defined SO_REUSE_RXTOALL || defined __DOXYGEN__
+#define SO_REUSE_RXTOALL 0
+#endif
+
+/**
+ * LWIP_FIONREAD_LINUXMODE==0 (default): ioctl/FIONREAD returns the amount of
+ * pending data in the network buffer. This is the way windows does it. It's
+ * the default for lwIP since it is smaller.
+ * LWIP_FIONREAD_LINUXMODE==1: ioctl/FIONREAD returns the size of the next
+ * pending datagram in bytes. This is the way linux does it. This code is only
+ * here for compatibility.
+ */
+#if !defined LWIP_FIONREAD_LINUXMODE || defined __DOXYGEN__
+#define LWIP_FIONREAD_LINUXMODE 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ----------------------------------------
+ ---------- Statistics options ----------
+ ----------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_stats Statistics
+ * @ingroup lwip_opts_debug
+ * @{
+ */
+/**
+ * LWIP_STATS==1: Enable statistics collection in lwip_stats.
+ */
+#if !defined LWIP_STATS || defined __DOXYGEN__
+#define LWIP_STATS 1
+#endif
+
+#if LWIP_STATS
+
+/**
+ * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions.
+ */
+#if !defined LWIP_STATS_DISPLAY || defined __DOXYGEN__
+#define LWIP_STATS_DISPLAY 0
+#endif
+
+/**
+ * LINK_STATS==1: Enable link stats.
+ */
+#if !defined LINK_STATS || defined __DOXYGEN__
+#define LINK_STATS 1
+#endif
+
+/**
+ * ETHARP_STATS==1: Enable etharp stats.
+ */
+#if !defined ETHARP_STATS || defined __DOXYGEN__
+#define ETHARP_STATS (LWIP_ARP)
+#endif
+
+/**
+ * IP_STATS==1: Enable IP stats.
+ */
+#if !defined IP_STATS || defined __DOXYGEN__
+#define IP_STATS 1
+#endif
+
+/**
+ * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is
+ * on if using either frag or reass.
+ */
+#if !defined IPFRAG_STATS || defined __DOXYGEN__
+#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG)
+#endif
+
+/**
+ * ICMP_STATS==1: Enable ICMP stats.
+ */
+#if !defined ICMP_STATS || defined __DOXYGEN__
+#define ICMP_STATS 1
+#endif
+
+/**
+ * IGMP_STATS==1: Enable IGMP stats.
+ */
+#if !defined IGMP_STATS || defined __DOXYGEN__
+#define IGMP_STATS (LWIP_IGMP)
+#endif
+
+/**
+ * UDP_STATS==1: Enable UDP stats. Default is on if
+ * UDP enabled, otherwise off.
+ */
+#if !defined UDP_STATS || defined __DOXYGEN__
+#define UDP_STATS (LWIP_UDP)
+#endif
+
+/**
+ * TCP_STATS==1: Enable TCP stats. Default is on if TCP
+ * enabled, otherwise off.
+ */
+#if !defined TCP_STATS || defined __DOXYGEN__
+#define TCP_STATS (LWIP_TCP)
+#endif
+
+/**
+ * MEM_STATS==1: Enable mem.c stats.
+ */
+#if !defined MEM_STATS || defined __DOXYGEN__
+#define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0))
+#endif
+
+/**
+ * MEMP_STATS==1: Enable memp.c pool stats.
+ */
+#if !defined MEMP_STATS || defined __DOXYGEN__
+#define MEMP_STATS (MEMP_MEM_MALLOC == 0)
+#endif
+
+/**
+ * SYS_STATS==1: Enable system stats (sem and mbox counts, etc).
+ */
+#if !defined SYS_STATS || defined __DOXYGEN__
+#define SYS_STATS (NO_SYS == 0)
+#endif
+
+/**
+ * IP6_STATS==1: Enable IPv6 stats.
+ */
+#if !defined IP6_STATS || defined __DOXYGEN__
+#define IP6_STATS (LWIP_IPV6)
+#endif
+
+/**
+ * ICMP6_STATS==1: Enable ICMP for IPv6 stats.
+ */
+#if !defined ICMP6_STATS || defined __DOXYGEN__
+#define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6)
+#endif
+
+/**
+ * IP6_FRAG_STATS==1: Enable IPv6 fragmentation stats.
+ */
+#if !defined IP6_FRAG_STATS || defined __DOXYGEN__
+#define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS))
+#endif
+
+/**
+ * MLD6_STATS==1: Enable MLD for IPv6 stats.
+ */
+#if !defined MLD6_STATS || defined __DOXYGEN__
+#define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD)
+#endif
+
+/**
+ * ND6_STATS==1: Enable Neighbor discovery for IPv6 stats.
+ */
+#if !defined ND6_STATS || defined __DOXYGEN__
+#define ND6_STATS (LWIP_IPV6)
+#endif
+
+/**
+ * MIB2_STATS==1: Stats for SNMP MIB2.
+ */
+#if !defined MIB2_STATS || defined __DOXYGEN__
+#define MIB2_STATS 0
+#endif
+
+#else
+
+#define LINK_STATS 0
+#define ETHARP_STATS 0
+#define IP_STATS 0
+#define IPFRAG_STATS 0
+#define ICMP_STATS 0
+#define IGMP_STATS 0
+#define UDP_STATS 0
+#define TCP_STATS 0
+#define MEM_STATS 0
+#define MEMP_STATS 0
+#define SYS_STATS 0
+#define LWIP_STATS_DISPLAY 0
+#define IP6_STATS 0
+#define ICMP6_STATS 0
+#define IP6_FRAG_STATS 0
+#define MLD6_STATS 0
+#define ND6_STATS 0
+#define MIB2_STATS 0
+
+#endif /* LWIP_STATS */
+/**
+ * @}
+ */
+
+/*
+ --------------------------------------
+ ---------- Checksum options ----------
+ --------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_checksum Checksum
+ * @ingroup lwip_opts_infrastructure
+ * @{
+ */
+/**
+ * LWIP_CHECKSUM_CTRL_PER_NETIF==1: Checksum generation/check can be enabled/disabled
+ * per netif.
+ * ATTENTION: if enabled, the CHECKSUM_GEN_* and CHECKSUM_CHECK_* defines must be enabled!
+ */
+#if !defined LWIP_CHECKSUM_CTRL_PER_NETIF || defined __DOXYGEN__
+#define LWIP_CHECKSUM_CTRL_PER_NETIF 0
+#endif
+
+/**
+ * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.
+ */
+#if !defined CHECKSUM_GEN_IP || defined __DOXYGEN__
+#define CHECKSUM_GEN_IP 1
+#endif
+
+/**
+ * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.
+ */
+#if !defined CHECKSUM_GEN_UDP || defined __DOXYGEN__
+#define CHECKSUM_GEN_UDP 1
+#endif
+
+/**
+ * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.
+ */
+#if !defined CHECKSUM_GEN_TCP || defined __DOXYGEN__
+#define CHECKSUM_GEN_TCP 1
+#endif
+
+/**
+ * CHECKSUM_GEN_ICMP==1: Generate checksums in software for outgoing ICMP packets.
+ */
+#if !defined CHECKSUM_GEN_ICMP || defined __DOXYGEN__
+#define CHECKSUM_GEN_ICMP 1
+#endif
+
+/**
+ * CHECKSUM_GEN_ICMP6==1: Generate checksums in software for outgoing ICMP6 packets.
+ */
+#if !defined CHECKSUM_GEN_ICMP6 || defined __DOXYGEN__
+#define CHECKSUM_GEN_ICMP6 1
+#endif
+
+/**
+ * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.
+ */
+#if !defined CHECKSUM_CHECK_IP || defined __DOXYGEN__
+#define CHECKSUM_CHECK_IP 1
+#endif
+
+/**
+ * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.
+ */
+#if !defined CHECKSUM_CHECK_UDP || defined __DOXYGEN__
+#define CHECKSUM_CHECK_UDP 1
+#endif
+
+/**
+ * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.
+ */
+#if !defined CHECKSUM_CHECK_TCP || defined __DOXYGEN__
+#define CHECKSUM_CHECK_TCP 1
+#endif
+
+/**
+ * CHECKSUM_CHECK_ICMP==1: Check checksums in software for incoming ICMP packets.
+ */
+#if !defined CHECKSUM_CHECK_ICMP || defined __DOXYGEN__
+#define CHECKSUM_CHECK_ICMP 1
+#endif
+
+/**
+ * CHECKSUM_CHECK_ICMP6==1: Check checksums in software for incoming ICMPv6 packets
+ */
+#if !defined CHECKSUM_CHECK_ICMP6 || defined __DOXYGEN__
+#define CHECKSUM_CHECK_ICMP6 1
+#endif
+
+/**
+ * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from
+ * application buffers to pbufs.
+ */
+#if !defined LWIP_CHECKSUM_ON_COPY || defined __DOXYGEN__
+#define LWIP_CHECKSUM_ON_COPY 0
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------------
+ ---------- IPv6 options ---------------
+ ---------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_ipv6 IPv6
+ * @ingroup lwip_opts
+ * @{
+ */
+/**
+ * LWIP_IPV6==1: Enable IPv6
+ */
+#if !defined LWIP_IPV6 || defined __DOXYGEN__
+#define LWIP_IPV6 0
+#endif
+
+/**
+ * LWIP_IPV6_NUM_ADDRESSES: Number of IPv6 addresses per netif.
+ */
+#if !defined LWIP_IPV6_NUM_ADDRESSES || defined __DOXYGEN__
+#define LWIP_IPV6_NUM_ADDRESSES 3
+#endif
+
+/**
+ * LWIP_IPV6_FORWARD==1: Forward IPv6 packets across netifs
+ */
+#if !defined LWIP_IPV6_FORWARD || defined __DOXYGEN__
+#define LWIP_IPV6_FORWARD 0
+#endif
+
+/**
+ * LWIP_IPV6_FRAG==1: Fragment outgoing IPv6 packets that are too big.
+ */
+#if !defined LWIP_IPV6_FRAG || defined __DOXYGEN__
+#define LWIP_IPV6_FRAG 0
+#endif
+
+/**
+ * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented
+ */
+#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__
+#define LWIP_IPV6_REASS (LWIP_IPV6)
+#endif
+
+/**
+ * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Send router solicitation messages during
+ * network startup.
+ */
+#if !defined LWIP_IPV6_SEND_ROUTER_SOLICIT || defined __DOXYGEN__
+#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1
+#endif
+
+/**
+ * LWIP_IPV6_AUTOCONFIG==1: Enable stateless address autoconfiguration as per RFC 4862.
+ */
+#if !defined LWIP_IPV6_AUTOCONFIG || defined __DOXYGEN__
+#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6)
+#endif
+
+/**
+ * LWIP_IPV6_DUP_DETECT_ATTEMPTS=[0..7]: Number of duplicate address detection attempts.
+ */
+#if !defined LWIP_IPV6_DUP_DETECT_ATTEMPTS || defined __DOXYGEN__
+#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1
+#endif
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lwip_opts_icmp6 ICMP6
+ * @ingroup lwip_opts_ipv6
+ * @{
+ */
+/**
+ * LWIP_ICMP6==1: Enable ICMPv6 (mandatory per RFC)
+ */
+#if !defined LWIP_ICMP6 || defined __DOXYGEN__
+#define LWIP_ICMP6 (LWIP_IPV6)
+#endif
+
+/**
+ * LWIP_ICMP6_DATASIZE: bytes from original packet to send back in
+ * ICMPv6 error messages.
+ */
+#if !defined LWIP_ICMP6_DATASIZE || defined __DOXYGEN__
+#define LWIP_ICMP6_DATASIZE 8
+#endif
+
+/**
+ * LWIP_ICMP6_HL: default hop limit for ICMPv6 messages
+ */
+#if !defined LWIP_ICMP6_HL || defined __DOXYGEN__
+#define LWIP_ICMP6_HL 255
+#endif
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lwip_opts_mld6 Multicast listener discovery
+ * @ingroup lwip_opts_ipv6
+ * @{
+ */
+/**
+ * LWIP_IPV6_MLD==1: Enable multicast listener discovery protocol.
+ * If LWIP_IPV6 is enabled but this setting is disabled, the MAC layer must
+ * indiscriminately pass all inbound IPv6 multicast traffic to lwIP.
+ */
+#if !defined LWIP_IPV6_MLD || defined __DOXYGEN__
+#define LWIP_IPV6_MLD (LWIP_IPV6)
+#endif
+
+/**
+ * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast groups that can be joined.
+ * There must be enough groups so that each netif can join the solicited-node
+ * multicast group for each of its local addresses, plus one for MDNS if
+ * applicable, plus any number of groups to be joined on UDP sockets.
+ */
+#if !defined MEMP_NUM_MLD6_GROUP || defined __DOXYGEN__
+#define MEMP_NUM_MLD6_GROUP 4
+#endif
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lwip_opts_nd6 Neighbor discovery
+ * @ingroup lwip_opts_ipv6
+ * @{
+ */
+/**
+ * LWIP_ND6_QUEUEING==1: queue outgoing IPv6 packets while MAC address
+ * is being resolved.
+ */
+#if !defined LWIP_ND6_QUEUEING || defined __DOXYGEN__
+#define LWIP_ND6_QUEUEING (LWIP_IPV6)
+#endif
+
+/**
+ * MEMP_NUM_ND6_QUEUE: Max number of IPv6 packets to queue during MAC resolution.
+ */
+#if !defined MEMP_NUM_ND6_QUEUE || defined __DOXYGEN__
+#define MEMP_NUM_ND6_QUEUE 20
+#endif
+
+/**
+ * LWIP_ND6_NUM_NEIGHBORS: Number of entries in IPv6 neighbor cache
+ */
+#if !defined LWIP_ND6_NUM_NEIGHBORS || defined __DOXYGEN__
+#define LWIP_ND6_NUM_NEIGHBORS 10
+#endif
+
+/**
+ * LWIP_ND6_NUM_DESTINATIONS: number of entries in IPv6 destination cache
+ */
+#if !defined LWIP_ND6_NUM_DESTINATIONS || defined __DOXYGEN__
+#define LWIP_ND6_NUM_DESTINATIONS 10
+#endif
+
+/**
+ * LWIP_ND6_NUM_PREFIXES: number of entries in IPv6 on-link prefixes cache
+ */
+#if !defined LWIP_ND6_NUM_PREFIXES || defined __DOXYGEN__
+#define LWIP_ND6_NUM_PREFIXES 5
+#endif
+
+/**
+ * LWIP_ND6_NUM_ROUTERS: number of entries in IPv6 default router cache
+ */
+#if !defined LWIP_ND6_NUM_ROUTERS || defined __DOXYGEN__
+#define LWIP_ND6_NUM_ROUTERS 3
+#endif
+
+/**
+ * LWIP_ND6_MAX_MULTICAST_SOLICIT: max number of multicast solicit messages to send
+ * (neighbor solicit and router solicit)
+ */
+#if !defined LWIP_ND6_MAX_MULTICAST_SOLICIT || defined __DOXYGEN__
+#define LWIP_ND6_MAX_MULTICAST_SOLICIT 3
+#endif
+
+/**
+ * LWIP_ND6_MAX_UNICAST_SOLICIT: max number of unicast neighbor solicitation messages
+ * to send during neighbor reachability detection.
+ */
+#if !defined LWIP_ND6_MAX_UNICAST_SOLICIT || defined __DOXYGEN__
+#define LWIP_ND6_MAX_UNICAST_SOLICIT 3
+#endif
+
+/**
+ * Unused: See ND RFC (time in milliseconds).
+ */
+#if !defined LWIP_ND6_MAX_ANYCAST_DELAY_TIME || defined __DOXYGEN__
+#define LWIP_ND6_MAX_ANYCAST_DELAY_TIME 1000
+#endif
+
+/**
+ * Unused: See ND RFC
+ */
+#if !defined LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT || defined __DOXYGEN__
+#define LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT 3
+#endif
+
+/**
+ * LWIP_ND6_REACHABLE_TIME: default neighbor reachable time (in milliseconds).
+ * May be updated by router advertisement messages.
+ */
+#if !defined LWIP_ND6_REACHABLE_TIME || defined __DOXYGEN__
+#define LWIP_ND6_REACHABLE_TIME 30000
+#endif
+
+/**
+ * LWIP_ND6_RETRANS_TIMER: default retransmission timer for solicitation messages
+ */
+#if !defined LWIP_ND6_RETRANS_TIMER || defined __DOXYGEN__
+#define LWIP_ND6_RETRANS_TIMER 1000
+#endif
+
+/**
+ * LWIP_ND6_DELAY_FIRST_PROBE_TIME: Delay before first unicast neighbor solicitation
+ * message is sent, during neighbor reachability detection.
+ */
+#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__
+#define LWIP_ND6_DELAY_FIRST_PROBE_TIME 5000
+#endif
+
+/**
+ * LWIP_ND6_ALLOW_RA_UPDATES==1: Allow Router Advertisement messages to update
+ * Reachable time and retransmission timers, and netif MTU.
+ */
+#if !defined LWIP_ND6_ALLOW_RA_UPDATES || defined __DOXYGEN__
+#define LWIP_ND6_ALLOW_RA_UPDATES 1
+#endif
+
+/**
+ * LWIP_ND6_TCP_REACHABILITY_HINTS==1: Allow TCP to provide Neighbor Discovery
+ * with reachability hints for connected destinations. This helps avoid sending
+ * unicast neighbor solicitation messages.
+ */
+#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__
+#define LWIP_ND6_TCP_REACHABILITY_HINTS 1
+#endif
+
+/**
+ * LWIP_ND6_RDNSS_MAX_DNS_SERVERS > 0: Use IPv6 Router Advertisement Recursive
+ * DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS
+ * servers to the DNS module.
+ */
+#if !defined LWIP_ND6_RDNSS_MAX_DNS_SERVERS || defined __DOXYGEN__
+#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS 0
+#endif
+/**
+ * @}
+ */
+
+/**
+ * LWIP_IPV6_DHCP6==1: enable DHCPv6 stateful address autoconfiguration.
+ */
+#if !defined LWIP_IPV6_DHCP6 || defined __DOXYGEN__
+#define LWIP_IPV6_DHCP6 0
+#endif
+
+/*
+ ---------------------------------------
+ ---------- Hook options ---------------
+ ---------------------------------------
+*/
+
+/**
+ * @defgroup lwip_opts_hooks Hooks
+ * @ingroup lwip_opts_infrastructure
+ * Hooks are undefined by default, define them to a function if you need them.
+ * @{
+ */
+
+/**
+ * LWIP_HOOK_FILENAME: Custom filename to #include in files that provide hooks.
+ * Declare your hook function prototypes in there, you may also #include all headers
+ * providing data types that are need in this file.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_FILENAME "path/to/my/lwip_hooks.h"
+#endif
+
+/**
+ * LWIP_HOOK_TCP_ISN:
+ * Hook for generation of the Initial Sequence Number (ISN) for a new TCP
+ * connection. The default lwIP ISN generation algorithm is very basic and may
+ * allow for TCP spoofing attacks. This hook provides the means to implement
+ * the standardized ISN generation algorithm from RFC 6528 (see contrib/adons/tcp_isn),
+ * or any other desired algorithm as a replacement.
+ * Called from tcp_connect() and tcp_listen_input() when an ISN is needed for
+ * a new TCP connection, if TCP support (@ref LWIP_TCP) is enabled.\n
+ * Signature: u32_t my_hook_tcp_isn(const ip_addr_t* local_ip, u16_t local_port, const ip_addr_t* remote_ip, u16_t remote_port);
+ * - it may be necessary to use "struct ip_addr" (ip4_addr, ip6_addr) instead of "ip_addr_t" in function declarations\n
+ * Arguments:
+ * - local_ip: pointer to the local IP address of the connection
+ * - local_port: local port number of the connection (host-byte order)
+ * - remote_ip: pointer to the remote IP address of the connection
+ * - remote_port: remote port number of the connection (host-byte order)\n
+ * Return value:
+ * - the 32-bit Initial Sequence Number to use for the new TCP connection.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_TCP_ISN(local_ip, local_port, remote_ip, remote_port)
+#endif
+
+/**
+ * LWIP_HOOK_IP4_INPUT(pbuf, input_netif):
+ * - called from ip_input() (IPv4)
+ * - pbuf: received struct pbuf passed to ip_input()
+ * - input_netif: struct netif on which the packet has been received
+ * Return values:
+ * - 0: Hook has not consumed the packet, packet is processed as normal
+ * - != 0: Hook has consumed the packet.
+ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook
+ * (i.e. free it when done).
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_IP4_INPUT(pbuf, input_netif)
+#endif
+
+/**
+ * LWIP_HOOK_IP4_ROUTE(dest):
+ * - called from ip_route() (IPv4)
+ * - dest: destination IPv4 address
+ * Returns the destination netif or NULL if no destination netif is found. In
+ * that case, ip_route() continues as normal.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_IP4_ROUTE()
+#endif
+
+/**
+ * LWIP_HOOK_IP4_ROUTE_SRC(dest, src):
+ * - source-based routing for IPv4 (see LWIP_HOOK_IP4_ROUTE(), src may be NULL)
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_IP4_ROUTE_SRC(dest, src)
+#endif
+
+/**
+ * LWIP_HOOK_ETHARP_GET_GW(netif, dest):
+ * - called from etharp_output() (IPv4)
+ * - netif: the netif used for sending
+ * - dest: the destination IPv4 address
+ * Returns the IPv4 address of the gateway to handle the specified destination
+ * IPv4 address. If NULL is returned, the netif's default gateway is used.
+ * The returned address MUST be directly reachable on the specified netif!
+ * This function is meant to implement advanced IPv4 routing together with
+ * LWIP_HOOK_IP4_ROUTE(). The actual routing/gateway table implementation is
+ * not part of lwIP but can e.g. be hidden in the netif's state argument.
+*/
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_ETHARP_GET_GW(netif, dest)
+#endif
+
+/**
+ * LWIP_HOOK_IP6_INPUT(pbuf, input_netif):
+ * - called from ip6_input() (IPv6)
+ * - pbuf: received struct pbuf passed to ip6_input()
+ * - input_netif: struct netif on which the packet has been received
+ * Return values:
+ * - 0: Hook has not consumed the packet, packet is processed as normal
+ * - != 0: Hook has consumed the packet.
+ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook
+ * (i.e. free it when done).
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_IP6_INPUT(pbuf, input_netif)
+#endif
+
+/**
+ * LWIP_HOOK_IP6_ROUTE(src, dest):
+ * - called from ip6_route() (IPv6)
+ * - src: sourc IPv6 address
+ * - dest: destination IPv6 address
+ * Returns the destination netif or NULL if no destination netif is found. In
+ * that case, ip6_route() continues as normal.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_IP6_ROUTE(src, dest)
+#endif
+
+/**
+ * LWIP_HOOK_ND6_GET_GW(netif, dest):
+ * - called from nd6_get_next_hop_entry() (IPv6)
+ * - netif: the netif used for sending
+ * - dest: the destination IPv6 address
+ * Returns the IPv6 address of the next hop to handle the specified destination
+ * IPv6 address. If NULL is returned, a NDP-discovered router is used instead.
+ * The returned address MUST be directly reachable on the specified netif!
+ * This function is meant to implement advanced IPv6 routing together with
+ * LWIP_HOOK_IP6_ROUTE(). The actual routing/gateway table implementation is
+ * not part of lwIP but can e.g. be hidden in the netif's state argument.
+*/
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_ND6_GET_GW(netif, dest)
+#endif
+
+/**
+ * LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr):
+ * - called from ethernet_input() if VLAN support is enabled
+ * - netif: struct netif on which the packet has been received
+ * - eth_hdr: struct eth_hdr of the packet
+ * - vlan_hdr: struct eth_vlan_hdr of the packet
+ * Return values:
+ * - 0: Packet must be dropped.
+ * - != 0: Packet must be accepted.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr)
+#endif
+
+/**
+ * LWIP_HOOK_VLAN_SET:
+ * Hook can be used to set prio_vid field of vlan_hdr. If you need to store data
+ * on per-netif basis to implement this callback, see @ref netif_cd.
+ * Called from ethernet_output() if VLAN support (@ref ETHARP_SUPPORT_VLAN) is enabled.\n
+ * Signature: s32_t my_hook_vlan_set(struct netif* netif, struct pbuf* pbuf, const struct eth_addr* src, const struct eth_addr* dst, u16_t eth_type);\n
+ * Arguments:
+ * - netif: struct netif that the packet will be sent through
+ * - p: struct pbuf packet to be sent
+ * - src: source eth address
+ * - dst: destination eth address
+ * - eth_type: ethernet type to packet to be sent\n
+ *
+ *
+ * Return values:
+ * - &lt;0: Packet shall not contain VLAN header.
+ * - 0 &lt;= return value &lt;= 0xFFFF: Packet shall contain VLAN header. Return value is prio_vid in host byte order.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type)
+#endif
+
+/**
+ * LWIP_HOOK_MEMP_AVAILABLE(memp_t_type):
+ * - called from memp_free() when a memp pool was empty and an item is now available
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_MEMP_AVAILABLE(memp_t_type)
+#endif
+
+/**
+ * LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif):
+ * Called from ethernet_input() when an unknown eth type is encountered.
+ * Return ERR_OK if packet is accepted, any error code otherwise.
+ * Payload points to ethernet header!
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif)
+#endif
+/**
+ * @}
+ */
+
+/*
+ ---------------------------------------
+ ---------- Debugging options ----------
+ ---------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_debugmsg Debug messages
+ * @ingroup lwip_opts_debug
+ * @{
+ */
+/**
+ * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is
+ * compared against this value. If it is smaller, then debugging
+ * messages are written.
+ * @see debugging_levels
+ */
+#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__
+#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL
+#endif
+
+/**
+ * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable
+ * debug messages of certain types.
+ * @see debugging_levels
+ */
+#if !defined LWIP_DBG_TYPES_ON || defined __DOXYGEN__
+#define LWIP_DBG_TYPES_ON LWIP_DBG_ON
+#endif
+
+/**
+ * ETHARP_DEBUG: Enable debugging in etharp.c.
+ */
+#if !defined ETHARP_DEBUG || defined __DOXYGEN__
+#define ETHARP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * NETIF_DEBUG: Enable debugging in netif.c.
+ */
+#if !defined NETIF_DEBUG || defined __DOXYGEN__
+#define NETIF_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * PBUF_DEBUG: Enable debugging in pbuf.c.
+ */
+#if !defined PBUF_DEBUG || defined __DOXYGEN__
+#define PBUF_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * API_LIB_DEBUG: Enable debugging in api_lib.c.
+ */
+#if !defined API_LIB_DEBUG || defined __DOXYGEN__
+#define API_LIB_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * API_MSG_DEBUG: Enable debugging in api_msg.c.
+ */
+#if !defined API_MSG_DEBUG || defined __DOXYGEN__
+#define API_MSG_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * SOCKETS_DEBUG: Enable debugging in sockets.c.
+ */
+#if !defined SOCKETS_DEBUG || defined __DOXYGEN__
+#define SOCKETS_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * ICMP_DEBUG: Enable debugging in icmp.c.
+ */
+#if !defined ICMP_DEBUG || defined __DOXYGEN__
+#define ICMP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * IGMP_DEBUG: Enable debugging in igmp.c.
+ */
+#if !defined IGMP_DEBUG || defined __DOXYGEN__
+#define IGMP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * INET_DEBUG: Enable debugging in inet.c.
+ */
+#if !defined INET_DEBUG || defined __DOXYGEN__
+#define INET_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * IP_DEBUG: Enable debugging for IP.
+ */
+#if !defined IP_DEBUG || defined __DOXYGEN__
+#define IP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass.
+ */
+#if !defined IP_REASS_DEBUG || defined __DOXYGEN__
+#define IP_REASS_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * RAW_DEBUG: Enable debugging in raw.c.
+ */
+#if !defined RAW_DEBUG || defined __DOXYGEN__
+#define RAW_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * MEM_DEBUG: Enable debugging in mem.c.
+ */
+#if !defined MEM_DEBUG || defined __DOXYGEN__
+#define MEM_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * MEMP_DEBUG: Enable debugging in memp.c.
+ */
+#if !defined MEMP_DEBUG || defined __DOXYGEN__
+#define MEMP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * SYS_DEBUG: Enable debugging in sys.c.
+ */
+#if !defined SYS_DEBUG || defined __DOXYGEN__
+#define SYS_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TIMERS_DEBUG: Enable debugging in timers.c.
+ */
+#if !defined TIMERS_DEBUG || defined __DOXYGEN__
+#define TIMERS_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_DEBUG: Enable debugging for TCP.
+ */
+#if !defined TCP_DEBUG || defined __DOXYGEN__
+#define TCP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug.
+ */
+#if !defined TCP_INPUT_DEBUG || defined __DOXYGEN__
+#define TCP_INPUT_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit.
+ */
+#if !defined TCP_FR_DEBUG || defined __DOXYGEN__
+#define TCP_FR_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit
+ * timeout.
+ */
+#if !defined TCP_RTO_DEBUG || defined __DOXYGEN__
+#define TCP_RTO_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_CWND_DEBUG: Enable debugging for TCP congestion window.
+ */
+#if !defined TCP_CWND_DEBUG || defined __DOXYGEN__
+#define TCP_CWND_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating.
+ */
+#if !defined TCP_WND_DEBUG || defined __DOXYGEN__
+#define TCP_WND_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions.
+ */
+#if !defined TCP_OUTPUT_DEBUG || defined __DOXYGEN__
+#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_RST_DEBUG: Enable debugging for TCP with the RST message.
+ */
+#if !defined TCP_RST_DEBUG || defined __DOXYGEN__
+#define TCP_RST_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths.
+ */
+#if !defined TCP_QLEN_DEBUG || defined __DOXYGEN__
+#define TCP_QLEN_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * UDP_DEBUG: Enable debugging in UDP.
+ */
+#if !defined UDP_DEBUG || defined __DOXYGEN__
+#define UDP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * TCPIP_DEBUG: Enable debugging in tcpip.c.
+ */
+#if !defined TCPIP_DEBUG || defined __DOXYGEN__
+#define TCPIP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * SLIP_DEBUG: Enable debugging in slipif.c.
+ */
+#if !defined SLIP_DEBUG || defined __DOXYGEN__
+#define SLIP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * DHCP_DEBUG: Enable debugging in dhcp.c.
+ */
+#if !defined DHCP_DEBUG || defined __DOXYGEN__
+#define DHCP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * AUTOIP_DEBUG: Enable debugging in autoip.c.
+ */
+#if !defined AUTOIP_DEBUG || defined __DOXYGEN__
+#define AUTOIP_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * DNS_DEBUG: Enable debugging for DNS.
+ */
+#if !defined DNS_DEBUG || defined __DOXYGEN__
+#define DNS_DEBUG LWIP_DBG_OFF
+#endif
+
+/**
+ * IP6_DEBUG: Enable debugging for IPv6.
+ */
+#if !defined IP6_DEBUG || defined __DOXYGEN__
+#define IP6_DEBUG LWIP_DBG_OFF
+#endif
+/**
+ * @}
+ */
+
+/*
+ --------------------------------------------------
+ ---------- Performance tracking options ----------
+ --------------------------------------------------
+*/
+/**
+ * @defgroup lwip_opts_perf Performance
+ * @ingroup lwip_opts_debug
+ * @{
+ */
+/**
+ * LWIP_PERF: Enable performance testing for lwIP
+ * (if enabled, arch/perf.h is included)
+ */
+#if !defined LWIP_PERF || defined __DOXYGEN__
+#define LWIP_PERF 0
+#endif
+/**
+ * @}
+ */
+
+#endif /* LWIP_HDR_OPT_H */
diff --git a/stacks/lwip_stack/release/lwip_helper_files/include/sys.h b/stacks/lwip_stack/release/lwip_helper_files/include/sys.h
new file mode 100644
index 0000000..8eed041
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/include/sys.h
@@ -0,0 +1,455 @@
+/**
+ * @file
+ * OS abstraction layer
+ */
+
+/*
+ * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+ * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+ * OF SUCH DAMAGE.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ */
+
+#ifndef LWIP_HDR_SYS_H
+#define LWIP_HDR_SYS_H
+
+#include "lwip/opt.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if NO_SYS
+
+/* For a totally minimal and standalone system, we provide null
+ definitions of the sys_ functions. */
+ typedef u8_t sys_sem_t;
+ typedef u8_t sys_mutex_t;
+ typedef u8_t sys_mbox_t;
+
+#define sys_sem_new(s, c) ERR_OK
+#define sys_sem_signal(s)
+#define sys_sem_wait(s)
+#define sys_arch_sem_wait(s,t)
+#define sys_sem_free(s)
+#define sys_sem_valid(s) 0
+#define sys_sem_valid_val(s) 0
+#define sys_sem_set_invalid(s)
+#define sys_sem_set_invalid_val(s)
+#define sys_mutex_new(mu) ERR_OK
+#define sys_mutex_lock(mu)
+#define sys_mutex_unlock(mu)
+#define sys_mutex_free(mu)
+#define sys_mutex_valid(mu) 0
+#define sys_mutex_set_invalid(mu)
+#define sys_mbox_new(m, s) ERR_OK
+#define sys_mbox_fetch(m,d)
+#define sys_mbox_tryfetch(m,d)
+#define sys_mbox_post(m,d)
+#define sys_mbox_trypost(m,d)
+#define sys_mbox_free(m)
+#define sys_mbox_valid(m)
+#define sys_mbox_valid_val(m)
+#define sys_mbox_set_invalid(m)
+#define sys_mbox_set_invalid_val(m)
+
+#define sys_thread_new(n,t,a,s,p)
+
+#define sys_msleep(t)
+
+#else /* NO_SYS */
+
+/** Return code for timeouts from sys_arch_mbox_fetch and sys_arch_sem_wait */
+#define SYS_ARCH_TIMEOUT 0xffffffffUL
+
+/** sys_mbox_tryfetch() returns SYS_MBOX_EMPTY if appropriate.
+ * For now we use the same magic value, but we allow this to change in future.
+ */
+#define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT
+
+#include "lwip/err.h"
+#include "arch/sys_arch.h"
+
+/** Function prototype for thread functions */
+ typedef void (*lwip_thread_fn) (void *arg);
+
+/* Function prototypes for functions to be implemented by platform ports
+ (in sys_arch.c) */
+
+/* Mutex functions: */
+
+/** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores
+ should be used instead */
+#ifndef LWIP_COMPAT_MUTEX
+#define LWIP_COMPAT_MUTEX 0
+#endif
+
+#if LWIP_COMPAT_MUTEX
+/* for old ports that don't have mutexes: define them to binary semaphores */
+#define sys_mutex_t sys_sem_t
+#define sys_mutex_new(mutex) sys_sem_new(mutex, 1)
+#define sys_mutex_lock(mutex) sys_sem_wait(mutex)
+#define sys_mutex_unlock(mutex) sys_sem_signal(mutex)
+#define sys_mutex_free(mutex) sys_sem_free(mutex)
+#define sys_mutex_valid(mutex) sys_sem_valid(mutex)
+#define sys_mutex_set_invalid(mutex) sys_sem_set_invalid(mutex)
+
+#else /* LWIP_COMPAT_MUTEX */
+
+/**
+ * @ingroup sys_mutex
+ * Create a new mutex.
+ * Note that mutexes are expected to not be taken recursively by the lwIP code,
+ * so both implementation types (recursive or non-recursive) should work.
+ * @param mutex pointer to the mutex to create
+ * @return ERR_OK if successful, another err_t otherwise
+ */
+ err_t sys_mutex_new (sys_mutex_t * mutex);
+/**
+ * @ingroup sys_mutex
+ * Lock a mutex
+ * @param mutex the mutex to lock
+ */
+ void sys_mutex_lock (sys_mutex_t * mutex);
+/**
+ * @ingroup sys_mutex
+ * Unlock a mutex
+ * @param mutex the mutex to unlock
+ */
+ void sys_mutex_unlock (sys_mutex_t * mutex);
+/**
+ * @ingroup sys_mutex
+ * Delete a semaphore
+ * @param mutex the mutex to delete
+ */
+ void sys_mutex_free (sys_mutex_t * mutex);
+#ifndef sys_mutex_valid
+/**
+ * @ingroup sys_mutex
+ * Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid
+ */
+ int sys_mutex_valid (sys_mutex_t * mutex);
+#endif
+#ifndef sys_mutex_set_invalid
+/**
+ * @ingroup sys_mutex
+ * Set a mutex invalid so that sys_mutex_valid returns 0
+ */
+ void sys_mutex_set_invalid (sys_mutex_t * mutex);
+#endif
+#endif /* LWIP_COMPAT_MUTEX */
+
+/* Semaphore functions: */
+
+/**
+ * @ingroup sys_sem
+ * Create a new semaphore
+ * @param sem pointer to the semaphore to create
+ * @param count initial count of the semaphore
+ * @return ERR_OK if successful, another err_t otherwise
+ */
+ err_t sys_sem_new (sys_sem_t * sem, u8_t count);
+/**
+ * @ingroup sys_sem
+ * Signals a semaphore
+ * @param sem the semaphore to signal
+ */
+ void sys_sem_signal (sys_sem_t * sem);
+/**
+ * @ingroup sys_sem
+ * Wait for a semaphore for the specified timeout
+ * @param sem the semaphore to wait for
+ * @param timeout timeout in milliseconds to wait (0 = wait forever)
+ * @return time (in milliseconds) waited for the semaphore
+ * or SYS_ARCH_TIMEOUT on timeout
+ */
+ u32_t sys_arch_sem_wait (sys_sem_t * sem, u32_t timeout);
+/**
+ * @ingroup sys_sem
+ * Delete a semaphore
+ * @param sem semaphore to delete
+ */
+ void sys_sem_free (sys_sem_t * sem);
+/** Wait for a semaphore - forever/no timeout */
+#define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0)
+#ifndef sys_sem_valid
+/**
+ * @ingroup sys_sem
+ * Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid
+ */
+ int sys_sem_valid (sys_sem_t * sem);
+#endif
+#ifndef sys_sem_set_invalid
+/**
+ * @ingroup sys_sem
+ * Set a semaphore invalid so that sys_sem_valid returns 0
+ */
+ void sys_sem_set_invalid (sys_sem_t * sem);
+#endif
+#ifndef sys_sem_valid_val
+/**
+ * Same as sys_sem_valid() but taking a value, not a pointer
+ */
+#define sys_sem_valid_val(sem) sys_sem_valid(&(sem))
+#endif
+#ifndef sys_sem_set_invalid_val
+/**
+ * Same as sys_sem_set_invalid() but taking a value, not a pointer
+ */
+#define sys_sem_set_invalid_val(sem) sys_sem_set_invalid(&(sem))
+#endif
+
+#ifndef sys_msleep
+/**
+ * @ingroup sys_misc
+ * Sleep for specified number of ms
+ */
+ void sys_msleep (u32_t ms); /* only has a (close to) 1 ms resolution. */
+#endif
+
+/* Mailbox functions. */
+
+/**
+ * @ingroup sys_mbox
+ * Create a new mbox of specified size
+ * @param mbox pointer to the mbox to create
+ * @param size (minimum) number of messages in this mbox
+ * @return ERR_OK if successful, another err_t otherwise
+ */
+ err_t sys_mbox_new (sys_mbox_t * mbox, int size);
+/**
+ * @ingroup sys_mbox
+ * Post a message to an mbox - may not fail
+ * -> blocks if full, only used from tasks not from ISR
+ * @param mbox mbox to posts the message
+ * @param msg message to post (ATTENTION: can be NULL)
+ */
+ void sys_mbox_post (sys_mbox_t * mbox, void *msg);
+/**
+ * @ingroup sys_mbox
+ * Try to post a message to an mbox - may fail if full or ISR
+ * @param mbox mbox to posts the message
+ * @param msg message to post (ATTENTION: can be NULL)
+ */
+ err_t sys_mbox_trypost (sys_mbox_t * mbox, void *msg);
+/**
+ * @ingroup sys_mbox
+ * Wait for a new message to arrive in the mbox
+ * @param mbox mbox to get a message from
+ * @param msg pointer where the message is stored
+ * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever)
+ * @return time (in milliseconds) waited for a message, may be 0 if not waited
+ or SYS_ARCH_TIMEOUT on timeout
+ * The returned time has to be accurate to prevent timer jitter!
+ */
+ u32_t sys_arch_mbox_fetch (sys_mbox_t * mbox, void **msg, u32_t timeout);
+/* Allow port to override with a macro, e.g. special timeout for sys_arch_mbox_fetch() */
+#ifndef sys_arch_mbox_tryfetch
+/**
+ * @ingroup sys_mbox
+ * Wait for a new message to arrive in the mbox
+ * @param mbox mbox to get a message from
+ * @param msg pointer where the message is stored
+ * @return 0 (milliseconds) if a message has been received
+ * or SYS_MBOX_EMPTY if the mailbox is empty
+ */
+ u32_t sys_arch_mbox_tryfetch (sys_mbox_t * mbox, void **msg);
+#endif
+/**
+ * For now, we map straight to sys_arch implementation.
+ */
+#define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg)
+/**
+ * @ingroup sys_mbox
+ * Delete an mbox
+ * @param mbox mbox to delete
+ */
+ void sys_mbox_free (sys_mbox_t * mbox);
+#define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0)
+#ifndef sys_mbox_valid
+/**
+ * @ingroup sys_mbox
+ * Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid
+ */
+ int sys_mbox_valid (sys_mbox_t * mbox);
+#endif
+#ifndef sys_mbox_set_invalid
+/**
+ * @ingroup sys_mbox
+ * Set an mbox invalid so that sys_mbox_valid returns 0
+ */
+ void sys_mbox_set_invalid (sys_mbox_t * mbox);
+#endif
+#ifndef sys_mbox_valid_val
+/**
+ * Same as sys_mbox_valid() but taking a value, not a pointer
+ */
+#define sys_mbox_valid_val(mbox) sys_mbox_valid(&(mbox))
+#endif
+#ifndef sys_mbox_set_invalid_val
+/**
+ * Same as sys_mbox_set_invalid() but taking a value, not a pointer
+ */
+#define sys_mbox_set_invalid_val(mbox) sys_mbox_set_invalid(&(mbox))
+#endif
+
+/**
+ * @ingroup sys_misc
+ * The only thread function:
+ * Creates a new thread
+ * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!)
+ * @param name human-readable name for the thread (used for debugging purposes)
+ * @param thread thread-function
+ * @param arg parameter passed to 'thread'
+ * @param stacksize stack size in bytes for the new thread (may be ignored by ports)
+ * @param prio priority of the new thread (may be ignored by ports) */
+ sys_thread_t sys_thread_new (const char *name, lwip_thread_fn thread,
+ void *arg, int stacksize, int prio);
+
+#endif /* NO_SYS */
+
+/* sys_init() must be called before anything else. */
+ void sys_init (void);
+
+#ifndef sys_jiffies
+/**
+ * Ticks/jiffies since power up.
+ */
+ u32_t sys_jiffies (void);
+#endif
+
+/**
+ * @ingroup sys_time
+ * Returns the current time in milliseconds,
+ * may be the same as sys_jiffies or at least based on it.
+ */
+ u32_t sys_now (void);
+
+/* Critical Region Protection */
+/* These functions must be implemented in the sys_arch.c file.
+ In some implementations they can provide a more light-weight protection
+ mechanism than using semaphores. Otherwise semaphores can be used for
+ implementation */
+#ifndef SYS_ARCH_PROTECT
+/** SYS_LIGHTWEIGHT_PROT
+ * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection
+ * for certain critical regions during buffer allocation, deallocation and memory
+ * allocation and deallocation.
+ */
+#if SYS_LIGHTWEIGHT_PROT
+
+/**
+ * @ingroup sys_prot
+ * SYS_ARCH_DECL_PROTECT
+ * declare a protection variable. This macro will default to defining a variable of
+ * type sys_prot_t. If a particular port needs a different implementation, then
+ * this macro may be defined in sys_arch.h.
+ */
+#define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev
+/**
+ * @ingroup sys_prot
+ * SYS_ARCH_PROTECT
+ * Perform a "fast" protect. This could be implemented by
+ * disabling interrupts for an embedded system or by using a semaphore or
+ * mutex. The implementation should allow calling SYS_ARCH_PROTECT when
+ * already protected. The old protection level is returned in the variable
+ * "lev". This macro will default to calling the sys_arch_protect() function
+ * which should be implemented in sys_arch.c. If a particular port needs a
+ * different implementation, then this macro may be defined in sys_arch.h
+ */
+#define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect()
+/**
+ * @ingroup sys_prot
+ * SYS_ARCH_UNPROTECT
+ * Perform a "fast" set of the protection level to "lev". This could be
+ * implemented by setting the interrupt level to "lev" within the MACRO or by
+ * using a semaphore or mutex. This macro will default to calling the
+ * sys_arch_unprotect() function which should be implemented in
+ * sys_arch.c. If a particular port needs a different implementation, then
+ * this macro may be defined in sys_arch.h
+ */
+#define SYS_ARCH_UNPROTECT(lev) sys_arch_unprotect(lev)
+ sys_prot_t sys_arch_protect (void);
+ void sys_arch_unprotect (sys_prot_t pval);
+
+#else
+
+#define SYS_ARCH_DECL_PROTECT(lev)
+#define SYS_ARCH_PROTECT(lev)
+#define SYS_ARCH_UNPROTECT(lev)
+
+#endif /* SYS_LIGHTWEIGHT_PROT */
+
+#endif /* SYS_ARCH_PROTECT */
+
+/*
+ * Macros to set/get and increase/decrease variables in a thread-safe way.
+ * Use these for accessing variable that are used from more than one thread.
+ */
+
+#ifndef SYS_ARCH_INC
+#define SYS_ARCH_INC(var, val) do { \
+ SYS_ARCH_DECL_PROTECT(old_level); \
+ SYS_ARCH_PROTECT(old_level); \
+ var += val; \
+ SYS_ARCH_UNPROTECT(old_level); \
+ } while(0)
+#endif /* SYS_ARCH_INC */
+
+#ifndef SYS_ARCH_DEC
+#define SYS_ARCH_DEC(var, val) do { \
+ SYS_ARCH_DECL_PROTECT(old_level); \
+ SYS_ARCH_PROTECT(old_level); \
+ var -= val; \
+ SYS_ARCH_UNPROTECT(old_level); \
+ } while(0)
+#endif /* SYS_ARCH_DEC */
+
+#ifndef SYS_ARCH_GET
+#define SYS_ARCH_GET(var, ret) do { \
+ SYS_ARCH_DECL_PROTECT(old_level); \
+ SYS_ARCH_PROTECT(old_level); \
+ ret = var; \
+ SYS_ARCH_UNPROTECT(old_level); \
+ } while(0)
+#endif /* SYS_ARCH_GET */
+
+#ifndef SYS_ARCH_SET
+#define SYS_ARCH_SET(var, val) do { \
+ SYS_ARCH_DECL_PROTECT(old_level); \
+ SYS_ARCH_PROTECT(old_level); \
+ var = val; \
+ SYS_ARCH_UNPROTECT(old_level); \
+ } while(0)
+#endif /* SYS_ARCH_SET */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_SYS_H */
diff --git a/stacks/lwip_stack/release/lwip_helper_files/include/timeouts.h b/stacks/lwip_stack/release/lwip_helper_files/include/timeouts.h
new file mode 100644
index 0000000..005db52
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/include/timeouts.h
@@ -0,0 +1,134 @@
+/**
+ * @file
+ * Timer implementations
+ */
+
+/*
+ * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+ * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+ * OF SUCH DAMAGE.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ * Simon Goldschmidt
+ *
+ */
+#ifndef LWIP_HDR_TIMEOUTS_H
+#define LWIP_HDR_TIMEOUTS_H
+
+#include "lwip/opt.h"
+#include "lwip/err.h"
+#if !NO_SYS
+#include "lwip/sys.h"
+#endif
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifndef LWIP_DEBUG_TIMERNAMES
+#ifdef LWIP_DEBUG
+#define LWIP_DEBUG_TIMERNAMES SYS_DEBUG
+#else /* LWIP_DEBUG */
+#define LWIP_DEBUG_TIMERNAMES 0
+#endif /* LWIP_DEBUG */
+#endif
+
+/** Function prototype for a stack-internal timer function that has to be
+ * called at a defined interval */
+ typedef void (*lwip_cyclic_timer_handler) (void);
+
+/** This struct contains information about a stack-internal timer function
+ that has to be called at a defined interval */
+ struct lwip_cyclic_timer
+ {
+ u32_t interval_ms;
+ lwip_cyclic_timer_handler handler;
+#if LWIP_DEBUG_TIMERNAMES
+ const char *handler_name;
+#endif /* LWIP_DEBUG_TIMERNAMES */
+ };
+
+/** This array contains all stack-internal cyclic timers. To get the number of
+ * timers, use LWIP_ARRAYSIZE() */
+ extern const struct lwip_cyclic_timer lwip_cyclic_timers[];
+
+#if LWIP_TIMERS
+
+/** Function prototype for a timeout callback function. Register such a function
+ * using sys_timeout().
+ *
+ * @param arg Additional argument to pass to the function - set up by sys_timeout()
+ */
+ typedef void (*sys_timeout_handler) (void *arg);
+
+ struct sys_timeo
+ {
+ struct sys_timeo *next;
+ u32_t time;
+ sys_timeout_handler h;
+ void *arg;
+#if LWIP_DEBUG_TIMERNAMES
+ const char *handler_name;
+#endif /* LWIP_DEBUG_TIMERNAMES */
+ };
+
+ void sys_timeouts_init (void);
+
+#if LWIP_DEBUG_TIMERNAMES
+ void sys_timeout_debug (u32_t msecs, sys_timeout_handler handler, void *arg,
+ const char *handler_name);
+#define sys_timeout(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler)
+#else /* LWIP_DEBUG_TIMERNAMES */
+ void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg);
+#endif /* LWIP_DEBUG_TIMERNAMES */
+
+ void sys_untimeout (sys_timeout_handler handler, void *arg);
+ void sys_restart_timeouts (void);
+#if NO_SYS
+ void sys_check_timeouts (void);
+ u32_t sys_timeouts_sleeptime (void);
+#else /* NO_SYS */
+ void sys_timeouts_mbox_fetch (sys_mbox_t * mbox, void **msg);
+#endif /* NO_SYS */
+
+#else /* LWIP_TIMERS */
+ typedef void (*sys_timeout_handler) (void *arg);
+
+ void sys_timeouts_init (void);
+ void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg);
+ void sys_untimeout (sys_timeout_handler handler, void *arg);
+ void sys_timeouts_mbox_fetch (sys_mbox_t * mbox, void **msg);
+ void cyclic_timer (void *arg);
+ void tcpip_tcp_timer (void *arg);
+ void tcp_timer_needed (void);
+
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_TIMEOUTS_H */
diff --git a/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/atomic_32.h b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/atomic_32.h
new file mode 100644
index 0000000..15a058b
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/atomic_32.h
@@ -0,0 +1,53 @@
+/*
+ * atomic_32.h
+ *
+ */
+
+#ifndef ATOMIC_32_H_
+#define ATOMIC_32_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+ typedef struct
+ {
+ volatile int counter;
+ } atomic_t;
+
+#define ATOMIC_INIT(i) {(i)}
+#define atomic_read(v) (*(volatile int *)&(v)->counter)
+#define atomic_set(v, i) (((v)->counter) = (i))
+
+ static inline void atomic_add (int i, atomic_t * v)
+ {
+ __asm__ __volatile__ (
+ /*LOCK_PREFIX "addl %1,%0" */
+ "addl %1,%0":"+m" (v->counter):"ir" (i));
+ }
+
+ static inline void atomic_sub (int i, atomic_t * v)
+ {
+ __asm__ __volatile__ (
+ /*LOCK_PREFIX "subl %1,%0" */
+ "subl %1,%0":"+m" (v->counter):"ir" (i));
+ }
+
+ static __inline__ void atomic_inc (atomic_t * v)
+ {
+ __asm__ __volatile__ (
+ /*LOCK_PREFIX "incl %0" */
+ "incl %0":"+m" (v->counter));
+ }
+
+ static __inline__ void atomic_dec (atomic_t * v)
+ {
+ __asm__ __volatile__ (
+ /*LOCK_PREFIX "decl %0" */
+ "decl %0":"+m" (v->counter));
+ }
+#ifdef __cplusplus
+}
+#endif
+#endif /* ATOMIC_32_H_ */
diff --git a/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/cc.h b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/cc.h
new file mode 100644
index 0000000..4e21a75
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/cc.h
@@ -0,0 +1,82 @@
+#ifndef LWIP_ARCH_CC_H
+#define LWIP_ARCH_CC_H
+
+#include <sys/time.h>
+#include <sys/types.h>
+#include <stdint.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifndef LWIP_MAX_S16_NUM
+#define LWIP_MAX_S16_NUM ((s16_t)0x7fff)
+#endif
+
+#ifndef LWIP_MAX_U16_NUM
+#define LWIP_MAX_U16_NUM ((u16_t)0xFfff)
+#endif
+
+#ifndef LWIP_MAX_U32_NUM
+#define LWIP_MAX_U32_NUM ((u32_t)0xffffffff)
+#endif
+
+#ifndef LWIP_MAX_S32_NUM
+#define LWIP_MAX_S32_NUM ((s32_t)0x7fffffff)
+#endif
+
+#ifndef LWIP_MAX_U64_NUM
+#define LWIP_MAX_U64_NUM ((u64_t)0xffffffffffffffff)
+#endif
+
+#ifndef LWIP_MAX_S64_NUM
+#define LWIP_MAX_S64_NUM ((s64_t)0x7fffffffffffffff)
+#endif
+
+#define NONBLOCK_MODE_FOR_ALG 2 /* it is possible to get fail */
+#define BLOCK_MODE_FOR_ALG 1 /* will block till success */
+#define NONBLOCK_MODE_NOT_FOR_ALG 0
+
+typedef uint64_t u64_t;
+typedef int64_t s64_t;
+
+typedef uint32_t u32_t;
+typedef int32_t s32_t;
+
+typedef uint16_t u16_t;
+typedef int16_t s16_t;
+
+typedef uint8_t u8_t;
+typedef int8_t s8_t;
+
+typedef uintptr_t mem_ptr_t;
+
+#define PACK_STRUCT_FIELD(x) x
+#define PACK_STRUCT_STRUCT
+#define PACK_STRUCT_BEGIN
+#define PACK_STRUCT_END
+
+#define S16_F "d"
+#define U16_F "u"
+#define X16_F "x"
+
+#define S32_F "d"
+#define U32_F "u"
+#define X32_F "x"
+
+#define S64_F "ld"
+#define U64_F "lu"
+#define X64_F "x"
+
+#ifndef BYTE_ORDER
+#define BYTE_ORDER LITTLE_ENDIAN
+#endif
+
+//#define LWIP_PROVIDE_ERRNO
+
+#ifndef LWIP_PLATFORM_DIAG
+#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0)
+#endif
+#ifndef LWIP_DEBUG
+#define LWIP_DEBUG 1
+#endif
+#endif
diff --git a/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/queue.h b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/queue.h
new file mode 100644
index 0000000..238ef05
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/queue.h
@@ -0,0 +1,30 @@
+#ifndef __QUEUE_H__
+#define __QUEUE_H__
+#ifdef __cplusplus
+extern "C"
+{
+
+#endif
+#include "common_mem_base_type.h"
+#ifdef HAL_LIB
+#else
+#include "rte_ring.h"
+#endif
+#include "nsfw_mem_api.h"
+//#include "stackx_dfx_api.h"
+
+#include "sys.h"
+
+ typedef struct queue
+ {
+ PRIMARY_ADDR mring_handle llring;
+ } queue_t;
+
+ err_t queue_push (queue_t * q, void *msg, int isTrypush);
+ void *queue_pop (queue_t * q, u32_t * timeout, int isTryPop);
+
+#ifdef __cplusplus
+
+}
+#endif
+#endif
diff --git a/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/sys_arch.h b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/sys_arch.h
new file mode 100644
index 0000000..92ff049
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/sys_arch.h
@@ -0,0 +1,29 @@
+#ifndef STACKX_ARCH_SYS_ARCH_H
+#define STACKX_ARCH_SYS_ARCH_H
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include <sys/types.h>
+#include <semaphore.h>
+
+#include "cc.h"
+
+/*add by daifen 2012.7.27*/
+ typedef uint64_t sys_thread_t;
+
+ extern u64_t hz_per_ms;
+
+ void stackx_global_lock (void);
+ void stackx_global_unlock (void);
+
+#define SYS_ARCH_PROTECT(lev) stackx_global_lock()
+#define SYS_ARCH_UNPROTECT(lev) stackx_global_unlock()
+#define SYS_ARCH_DECL_PROTECT(lev)
+
+#ifdef __cplusplus
+
+}
+#endif
+#endif
diff --git a/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/win_minmax.h b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/win_minmax.h
new file mode 100644
index 0000000..e1e64ac
--- /dev/null
+++ b/stacks/lwip_stack/release/lwip_helper_files/lwip/arch/win_minmax.h
@@ -0,0 +1,120 @@
+/**
+ * lib/minmax.c: windowed min/max tracker by Kathleen Nichols.
+ *
+ */
+#ifndef MINMAX_H
+#define MINMAX_H
+
+#include "types.h"
+#include "rtp_branch_prediction.h"
+
+/* A single data point for our parameterized min-max tracker */
+struct minmax_sample
+{
+ u32_t t; /* time measurement was taken */
+ u32_t v; /* value measured */
+};
+
+/* State for the parameterized min-max tracker */
+struct minmax
+{
+ struct minmax_sample s[3];
+};
+
+static inline u32_t
+minmax_get (const struct minmax *m)
+{
+ return m->s[0].v;
+}
+
+static inline u32_t
+minmax_reset (struct minmax *m, u32_t t, u32_t meas)
+{
+ struct minmax_sample val = {.t = t,.v = meas };
+
+ m->s[2] = m->s[1] = m->s[0] = val;
+ return m->s[0].v;
+}
+
+/* As time advances, update the 1st, 2nd, and 3rd choices. */
+static u32_t
+minmax_subwin_update (struct minmax *m, u32_t win,
+ const struct minmax_sample *val)
+{
+ u32_t dt = val->t - m->s[0].t;
+
+ if (unlikely (dt > win))
+ {
+ /*
+ * Passed entire window without a new val so make 2nd
+ * choice the new val & 3rd choice the new 2nd choice.
+ * we may have to iterate this since our 2nd choice
+ * may also be outside the window (we checked on entry
+ * that the third choice was in the window).
+ */
+ m->s[0] = m->s[1];
+ m->s[1] = m->s[2];
+ m->s[2] = *val;
+ if (unlikely (val->t - m->s[0].t > win))
+ {
+ m->s[0] = m->s[1];
+ m->s[1] = m->s[2];
+ m->s[2] = *val;
+ }
+ }
+ else if (unlikely (m->s[1].t == m->s[0].t) && dt > win / 4)
+ {
+ /*
+ * We've passed a quarter of the window without a new val
+ * so take a 2nd choice from the 2nd quarter of the window.
+ */
+ m->s[2] = m->s[1] = *val;
+ }
+ else if (unlikely (m->s[2].t == m->s[1].t) && dt > win / 2)
+ {
+ /*
+ * We've passed half the window without finding a new val
+ * so take a 3rd choice from the last half of the window
+ */
+ m->s[2] = *val;
+ }
+ return m->s[0].v;
+}
+
+/* Check if new measurement updates the 1st, 2nd or 3rd choice max. */
+static inline u32_t
+minmax_running_max (struct minmax *m, u32_t win, u32_t t, u32_t meas)
+{
+ struct minmax_sample val = {.t = t,.v = meas };
+
+ if (unlikely (val.v >= m->s[0].v) || /* found new max? */
+ unlikely (val.t - m->s[2].t > win)) /* nothing left in window? */
+ return minmax_reset (m, t, meas); /* forget earlier samples */
+
+ if (unlikely (val.v >= m->s[1].v))
+ m->s[2] = m->s[1] = val;
+ else if (unlikely (val.v >= m->s[2].v))
+ m->s[2] = val;
+
+ return minmax_subwin_update (m, win, &val);
+}
+
+/* Check if new measurement updates the 1st, 2nd or 3rd choice min. */
+static inline u32_t
+minmax_running_min (struct minmax *m, u32_t win, u32_t t, u32_t meas)
+{
+ struct minmax_sample val = {.t = t,.v = meas };
+
+ if (unlikely (val.v <= m->s[0].v) || /* found new min? */
+ unlikely (val.t - m->s[2].t > win)) /* nothing left in window? */
+ return minmax_reset (m, t, meas); /* forget earlier samples */
+
+ if (unlikely (val.v <= m->s[1].v))
+ m->s[2] = m->s[1] = val;
+ else if (unlikely (val.v <= m->s[2].v))
+ m->s[2] = val;
+
+ return minmax_subwin_update (m, win, &val);
+}
+
+#endif
diff --git a/stacks/lwip_stack/release/script/nstack_fun.sh b/stacks/lwip_stack/release/script/nstack_fun.sh
new file mode 100644
index 0000000..bb33a6a
--- /dev/null
+++ b/stacks/lwip_stack/release/script/nstack_fun.sh
@@ -0,0 +1,591 @@
+#!/bin/bash
+
+check_file_size()
+{
+ if [ -n "$1" ]&&[ -f "$1" ]
+ then
+ local log_size=`stat -c %s $1`
+ if [ ${log_size} -gt $MAX_LOG_FILE_SIZE ]
+ then
+ mv $1 $1.bk
+ fi
+ fi
+}
+
+log()
+{
+ check_file_size $LOG_FILE
+
+ #1 line number
+ local printStr="$2"
+ cur_date=`date +'%m%d %H:%M:%S.%6N' -u`
+ pid=$$
+ file=$0
+ local log_head="I${cur_date} ${file##*/}:$1 ${pid}]"
+
+ printf "${log_head} $printStr\n" >> $LOG_FILE 2>/dev/null
+}
+
+get_call_stack()
+{
+ local proc_name="$1"
+ log $LINENO "gdb info in call stack:"
+ gdb -batch -ex "t a a bt" -p `pidof $proc_name`>> $LOG_FILE 2>/dev/null
+ log $LINENO "top in call stack:"
+ top -H -p `pidof $proc_name` -n 1 -b >> $LOG_FILE 2>/dev/null
+ log $LINENO "mpstat in call stack:"
+ mpstat -A >> $LOG_FILE 2>/dev/null
+}
+
+gdb_set()
+{
+ local mod="$1"
+ if [ "$mod" = "stop" ];then
+ gdb -batch -ex "set g_hbt_switch=0" -p `pidof nStackMain`
+ gdb -batch -ex "set g_hbt_switch=0" -p `pidof nStackMaster`
+ log $LINENO "gdb stop"
+ else
+ gdb -batch -ex "set g_hbt_switch=1" -p `pidof nStackMain`
+ gdb -batch -ex "set g_hbt_switch=1" -p `pidof nStackMaster`
+ log $LINENO "gdb start"
+ fi
+}
+
+get_core_mask()
+{
+ local sys_core=`cat /proc/cpuinfo | grep processor | wc -l`
+ log $LINENO "system has ${sys_core} cores"
+ #if sys_core too large 2^$sys_core will overflow; so reset sys_core; z00203440 20170323
+ if [ $sys_core -gt 8 ]
+ then
+ sys_core=8
+ log $LINENO "sys_core too large reset to ${sys_core}"
+ fi
+
+ base=`echo | awk -v ex=$sys_core 'BEGIN{a=2^ex; print a}'`
+ local temp=`expr $base - 1`
+ printf %X $temp
+ return $sys_core
+}
+
+init_log_file()
+{
+ if [ -n $LOG_FILE_DIR ]&&[ ! -f $LOG_FILE_DIR ]
+ then
+ sudo mkdir -p $LOG_FILE_DIR
+ fi
+
+ check_file_size $LOG_FILE
+
+ if [ -n $DPDK_FILE_DIR ]&&[ ! -f $DPDK_FILE_DIR ]
+ then
+ sudo mkdir -p $DPDK_FILE_DIR
+ fi
+
+ check_file_size $DPDK_FILE
+
+ #must create the directory under the current user account
+ if [ -n $RUNTIME_DIR ]&&[ ! -f $RUNTIME_DIR ]
+ then
+ mkdir -p $RUNTIME_DIR
+ fi
+}
+
+delete_log_file() {
+ if [ -n $RUNNING_FILE_DIR ]&&[ -d $RUNNING_FILE_DIR ]&&[ -n $RUNNING_FILE_NAME ]; then
+ rm -rf $RUNNING_FILE_DIR/*${RUNNING_FILE_NAME}*
+ fi
+ if [ -n $RUNNING_FILE_DIR ]&&[ -d $RUNNING_FILE_DIR ]&&[ -n $OPERATION_FILE_NAME ]; then
+ rm -rf $RUNNING_FILE_DIR/*${OPERATION_FILE_NAME}*
+ fi
+ if [ -n $RUNNING_FILE_DIR ]&&[ -d $RUNNING_FILE_DIR ]&&[ -n $GLOG_FAILURE_FILE_NAME ]; then
+ rm -rf $RUNNING_FILE_DIR/*${GLOG_FAILURE_FILE_NAME}*
+ fi
+ if [ -n $RUNNING_FILE_DIR ]&&[ -d $RUNNING_FILE_DIR ]&&[ -n $NSTACK_FAILURE_FILE_NAME ]; then
+ rm -rf $RUNNING_FILE_DIR/*${NSTACK_FAILURE_FILE_NAME}*
+ fi
+ if [ -n $MASTER_FILE_DIR ]&&[ -d $MASTER_FILE_DIR ]&&[ -n $MASTER_FILE_NAME ]; then
+ rm -rf $MASTER_FILE_DIR/*${MASTER_FILE_NAME}*
+ fi
+ if [ -n $MASTER_FILE_DIR ]&&[ -d $MASTER_FILE_DIR ]&&[ -n $GLOG_FAILURE_FILE_NAME ]; then
+ rm -rf $MASTER_FILE_DIR/*${GLOG_FAILURE_FILE_NAME}*
+ fi
+ if [ -n $MASTER_FILE_DIR ]&&[ -d $MASTER_FILE_DIR ]&&[ -n $NSTACK_FAILURE_FILE_NAME ]; then
+ rm -rf $MASTER_FILE_DIR/*${NSTACK_FAILURE_FILE_NAME}*
+ fi
+ if [ -n $LOG_FILE_DIR ]&&[ -d $LOG_FILE_DIR ]&&[ -n $LOG_FILE_NAME ]; then
+ rm -rf $LOG_FILE_DIR/*${LOG_FILE_NAME}*
+ fi
+ if [ -n $DPDK_FILE_DIR ]&&[ -d $DPDK_FILE_DIR ]&&[ -n $DPDK_FILE_NAME ]; then
+ rm -rf $DPDK_FILE_DIR/*${DPDK_FILE_NAME}*
+ fi
+ if [ -n $RUNTIME_DIR ]&&[ -d $RUNTIME_DIR ]; then
+ rm -rf $RUNTIME_DIR
+ fi
+ if [ -n ${MASTER_EXEC_PATH} ]&&[ -d $MASTER_EXEC_PATH ]; then
+ rm -rf $MASTER_EXEC_PATH
+ fi
+}
+
+init_hugepage()
+{
+ log $LINENO "init hugepage..."
+##############################################################
+#
+# TO DO:
+# verify the free pages carefully, but not with 1G pagesize
+#
+#############################################################
+
+ #for 1G hugepage
+
+ # check total hugepage number
+# local nr_pagedir=/sys/devices/system/node/node0/hugepages/hugepages-1048576kB/nr_hugepages
+# if [ ! -f ${nr_pagedir} ]
+# then
+# log $LINENO "system not support 1G huge pages, exit!"
+# exit 1
+# fi
+
+ # local nr_huge_pages=`cat ${nr_pagedir}`
+ # if [ ${nr_huge_pages} -lt 3 ]
+ # then
+ # log $LINENO "total huge pages is not set correctly, current ${nr_huge_pages}, exit!"
+ # exit 1
+ # fi
+
+ # check free hugepage number
+ # local fr_pagedir=/sys/devices/system/node/node0/hugepages/hugepages-1048576kB/free_hugepages
+ # if [ ! -f ${fr_pagedir} ]
+ # then
+ # log $LINENO "system not support 1G huge pages, exit!"
+ # exit 1
+ # fi
+
+ # local fr_huge_pages=`cat ${fr_pagedir}`
+ # if [ ${fr_huge_pages} -lt 3 ]
+ # then
+ # log $LINENO "free huge pages is not set correctly, current ${fr_huge_pages}, exit!"
+ # lsof $HUGE_DIR >> $LOG_FILE 2>/dev/null
+ # exit 1
+ # fi
+
+ # mount | grep $HUGE_DIR >> $LOG_FILE 2>/dev/null
+ # if [ $? -eq 0 ] ; then
+ # log $LINENO "$HUGE_DIR dir exist"
+ # if test $(pgrep -f $1 | wc -l) -eq 0 ; then
+ # log $LINENO "proccess $1 not exist and clean huge files"
+ # if [ -n $HUGE_DIR ]&&[ -d $HUGE_DIR ]; then
+ # rm -rf $HUGE_DIR/*
+ # fi
+ # else
+ # log $LINENO "proccess $1 exist"
+ # fi
+ # else
+ # log $LINENO "$HUGE_DIR not exist and create"
+ # sudo mkdir -p $HUGE_DIR
+ #directory right can't larger than 750
+
+ # cur_user=`whoami`
+ # if [ "root" != "$cur_user" ]
+ # then
+ # non_root_uid=`id -u $cur_user`
+ # non_root_gid=`id -g $cur_user`
+ # sudo mount -t hugetlbfs -o pagesize=1G,uid=$non_root_uid,gid=$non_root_gid none $HUGE_DIR >> $LOG_FILE 2>/dev/null
+ # else
+ # mount -t hugetlbfs -o pagesize=1G none $HUGE_DIR >> $LOG_FILE 2>/dev/null
+ # fi
+ # fi
+}
+
+recover_hugepage()
+{
+ log $LINENO "recover hugepage..."
+
+ if [ -n "$HUGE_DIR" ]&&[ -d "$HUGE_DIR" ]; then
+ rm -rf $HUGE_DIR/*
+ fi
+}
+
+init_network()
+{
+ log $LINENO "init network..."
+
+ recover_network
+
+ sudo modprobe uio
+
+ local script_path=$(cd "$(dirname "$0")"; pwd)
+ local is_igb_uio_loaded=`lsmod | grep igb_uio | wc -l`
+ if [ ${is_igb_uio_loaded} -eq 0 ]
+ then
+ log $LINENO "igb_uio is not installed. install it now."
+ sudo insmod $DPDK_MOD_PATH/igb_uio.ko
+ fi
+
+ # check if there is un-recognized nic
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py -s | grep -A32 "Other network" | \
+ grep unused | awk -F"'" '{print $1, $2}' | while read NIC_BFS BIND_DRIVER_NAME
+ do
+ local TYPE_CHECK_ixgbe=`echo $BIND_DRIVER_NAME |grep "82599ES 10-Gigabit SFI/SFP+ Network Connection"|wc -l`
+ local TYPE_CHECK_ixgbevf=`echo $BIND_DRIVER_NAME |grep "82599 Ethernet Controller Virtual Function"|wc -l`
+ local TYPE_CHECK_vmxnet3=`echo $BIND_DRIVER_NAME |grep "VMXNET3 Ethernet Controller"|wc -l`
+ local TYPE_CHECK_virtio=`echo $BIND_DRIVER_NAME |grep "Virtio network device"|wc -l`
+
+ if [ $TYPE_CHECK_ixgbe -gt 0 ]; then
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py --bind=ixgbe $NIC_BFS
+ elif [ $TYPE_CHECK_ixgbevf -gt 0 ]; then
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py --bind=ixgbevf $NIC_BFS
+ elif [ $TYPE_CHECK_vmxnet3 -gt 0 ]; then
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py --bind=vmxnet3 $NIC_BFS
+ elif [ $TYPE_CHECK_virtio -gt 0 ]; then
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py --bind=virtio-pci $NIC_BFS
+ fi
+
+ done
+}
+
+recover_network()
+{
+ log $LINENO "recover network..."
+
+ if [ -z "$DPDK_NIC_LIST_FILE" ]||[ ! -f "$DPDK_NIC_LIST_FILE" ]
+ then
+ log $LINENO "$DPDK_NIC_LIST_FILE is not exist. There is no nic used by nstack to unbind."
+ else
+ log $LINENO "The NIC(s) to unbind: "
+ cat $DPDK_NIC_LIST_FILE | awk -F" '|' | drv=| unused=" '{print $1,$4}' >> $LOG_FILE 2>/dev/null
+ cat $DPDK_NIC_LIST_FILE | awk -F" '|' | drv=| unused=" '{print $1,$4}' | while read NIC_BFS BIND_DRIVER_TYPE
+ do
+ sudo $DPDK_TOOL_DIR/dpdk-devbind.py --bind=$BIND_DRIVER_TYPE $NIC_BFS >> $LOG_FILE 2>/dev/null
+ done
+ rm $DPDK_NIC_LIST_FILE
+ fi
+
+ touch $DPDK_NIC_LIST_FILE
+ chmod 600 $DPDK_NIC_LIST_FILE
+}
+
+
+check_args_main()
+{
+if [ -z $HUGE_DIR ]||[ -z $MEM_SIZE ]||[ -z $RTP_CORE_MASK ]||[ -z $SLEEP_INTERVAL ]||\
+ [ -z $BIND_CPU ]||[ -z $START_TYPE ]
+then
+ log $LINENO "nStackMain Args is null"
+ return 1
+fi
+
+# check CORE_MASK -- see in get_core_mask()
+# check HUGE_DIR
+if [ -z $HUGE_DIR ]||[ ! -d $HUGE_DIR ]; then
+ log $LINENO "HUGE_DIR="$HUGE_DIR" is invalid"
+ return 1
+fi
+
+# check MEM_SIZE
+if [ $MEM_SIZE -lt 2048 ]||[ $MEM_SIZE -gt 32768 ]; then
+ log $LINENO "MEM_SIZE="$MEM_SIZE" is invalid"
+ return 1
+fi
+
+# check RTP_CORE_MASK
+if [ $RTP_CORE_MASK -lt 1 ]; then
+ log $LINENO "RTP_CORE_MASK="$RTP_CORE_MASK" is invalid"
+ return 1
+fi
+
+# check SLEEP_INTERVAL
+if [ $SLEEP_INTERVAL -lt 0 ]; then
+ log $LINENO "SLEEP_INTERVAL="$SLEEP_INTERVAL" is invalid"
+ return 1
+fi
+
+# check BIND_CPU
+if [ $BIND_CPU -lt 0 ]; then
+ log $LINENO "BIND_CPU="$BIND_CPU" is invalid"
+ return 1
+fi
+
+# check START_TYPE
+if [ $START_TYPE -lt 0 ]||[ $START_TYPE -gt 5 ]; then
+ log $LINENO "START_TYPE="$START_TYPE" is invalid"
+ return 1
+fi
+
+return 0
+}
+
+run_nStackMain()
+{
+
+ log $LINENO "run nstack main..."
+
+ sudo setcap CAP_IPC_OWNER,CAP_FOWNER,CAP_NET_ADMIN,CAP_IPC_LOCK,CAP_NET_RAW,CAP_SYS_RAWIO,CAP_SYS_ADMIN,CAP_CHOWN,CAP_SYS_NICE=eip ./bin/nStackMain 2>/dev/null
+
+ local script_path=$(cd "$(dirname "$0")"; pwd)
+ export NSTACK_CONFIG_PATH=${script_path}/../configure
+ export LD_LIBRARY_PATH=${script_path}/lib64/:$LD_LIBRARY_PATH
+ export NSTACK_LOG_ON=INF
+
+ log $LINENO "$env NSTACK_CONFIG_PATH=$NSTACK_CONFIG_PATH"
+ log $LINENO "$env DPDK_TOOL_DIR=$DPDK_TOOL_DIR"
+ log $LINENO "$env LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
+ log $LINENO "$env DPDK_LIB_PATH=$DPDK_LIB_PATH"
+ log $LINENO "./bin/nStackMain -c $1 -n 4 --huge-dir=$2 -m $3 stack -c $4 -sleep $5 -bind_cpu $6"
+ check_file_size $DPDK_FILE
+ cd ..; cd bin/
+ ./nStackMain -c $1 -n 4 --huge-dir=$2 -m $3 stack -c $4 -sleep $5 -bind_cpu $6 >> $DPDK_FILE &
+}
+
+
+stop_nStackProcess()
+{
+ log $LINENO "$1 exiting..."
+
+ local i=0
+
+ while [ ${i} -lt $2 ]
+ do
+ #pid=`ps aux | grep $1 |grep -v grep| awk '{print $2}'`
+ pid=`pidof $1`
+ if [ "x${pid}" != "x" ]
+ then
+ kill -9 $pid 2>/dev/null
+ else
+ break
+ fi
+ i=`expr ${i} + 1`
+ sleep 1
+ done
+}
+
+stop_nStackApps()
+{
+ log $LINENO "stop the apps that use the shared nstackhuge memory..."
+
+ app_pid=`lsof $HUGE_DIR | awk '{print $2}'`
+ if [ "x${app_pid}" != "x" ]
+ then
+ kill -9 ${app_pid} 2>/dev/null
+ fi
+}
+
+get_nstack_bin()
+{
+ local app=$1
+ master_pid=`pidof $app | head -n 1`
+ if [ "x${master_pid}" != "x" ];then
+ sudo readlink -f "/proc/${master_pid}/exe" | sed "s/$app$//g" 2>/dev/null
+ fi
+}
+
+
+
+get_abs_path()
+{
+ local input_path=$1
+ if [ -d "$input_path" -o -f "$input_path" ]; then
+ echo "$(dirname $(readlink -e $input_path))/$(basename $input_path)"
+ return 0
+ fi
+ echo $input_path
+ return 1
+}
+
+
+
+CONFIG_FILE="nStackConfig.json"
+VAR_FILE="nstack_var.sh"
+
+modify_nstack_log_path()
+{
+ if echo $1 |grep -Eq '^((/[a-zA-Z_]+[a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)*/?)|/)$' > /dev/null
+ then
+ local parameter=$1
+ else
+ log $LINENO "the path is invalid, use the default config path!"
+ return
+ fi
+
+ if [ ! -d $1 ]; then
+ log $LINENO "the folder is not existed, use the default config!"
+ return
+ fi
+
+ if [ ! -w $1 ]; then
+ log $LINENO "the folder has no permission, use the default config!"
+ return
+ fi
+
+ local script_path=$(cd "$(dirname "$0")"; pwd)
+ local config_name=${script_path}/configure/$CONFIG_FILE
+
+ if [ ! -f $config_name ]; then
+ log $LINENO "$CONFIG_FILE no exit! use default config in code."
+ return
+ fi
+
+ sed -i 's#\("stackpool_log_path": "\).*#\1'"$1"'",#g' ${config_name}
+ sed -i 's#\("master_log_path": "\).*#\1'"$1"'",#g' ${config_name}
+ sed -i 's#\("nstack_log_path": "\).*#\1'"$1"'",#g' ${config_name}
+ sed -i 's#\("dpdk_log_path": "\).*#\1'"$1"'"#g' ${config_name}
+}
+
+modify_log_var()
+{
+ local script_path=$(cd "$(dirname "$0")"; pwd)
+ local config_name=${script_path}/configure/$CONFIG_FILE
+
+ if [ ! -f $config_name ]; then
+ log $LINENO "$CONFIG_FILE no exit! use default config in code."
+ return
+ fi
+
+ local running_log_path=`grep -Po '"stackpool_log_path": ".*?"' $config_name | sed -n -e 's/"//gp' | awk -F' ' '{print $2}'`
+ local master_log_path=`grep -Po '"master_log_path": ".*?"' $config_name | sed -n -e 's/"//gp' | awk -F' ' '{print $2}'`
+ local nstack_log_path=`grep -Po '"nstack_log_path": ".*?"' $config_name | sed -n -e 's/"//gp' | awk -F' ' '{print $2}'`
+ local dpdk_log_path=`grep -Po '"dpdk_log_path": ".*?"' $config_name | sed -n -e 's/"//gp' | awk -F' ' '{print $2}'`
+
+#modify the nstack_var.sh
+ local var_config_name=${script_path}/script/$VAR_FILE
+
+ if [ ! -f $var_config_name ]; then
+ log $LINENO "$VAR_FILE not exist , exit!"
+ exit 1
+ fi
+
+#check the path from json if it is OK.
+ if [ -n "$running_log_path" ]&&[ -w "$running_log_path" ]; then
+ sed -i "s:RUNNING_FILE_DIR=.*:RUNNING_FILE_DIR=${running_log_path}:g" $var_config_name
+ else
+ log $LINENO "stackpool_log_path:$running_log_path in $CONFIG_FILE is invalid, use the default config!"
+ fi
+
+ if [ -n "$master_log_path" ]&&[ -w "$master_log_path" ]; then
+ sed -i "s:MASTER_FILE_DIR=.*:MASTER_FILE_DIR=${master_log_path}:g" $var_config_name
+ else
+ log $LINENO "master_log_path:$master_log_path in $CONFIG_FILE is invalid, use the default config!"
+ fi
+
+ if [ -n "$nstack_log_path" ]&&[ -w "$nstack_log_path" ]; then
+ sed -i "s:LOG_FILE_DIR=.*:LOG_FILE_DIR=${nstack_log_path}:g" $var_config_name
+ else
+ log $LINENO "nstack_log_path:$nstack_log_path in $CONFIG_FILE is invalid, use the default config!"
+ fi
+
+ if [ -n "$dpdk_log_path" ]&&[ -w "$dpdk_log_path" ]; then
+ sed -i "s:DPDK_FILE_DIR=.*:DPDK_FILE_DIR=${dpdk_log_path}:g" $var_config_name
+ else
+ log $LINENO "dpdk_log_path:$dpdk_log_path in $CONFIG_FILE is invalid, use the default config!"
+ fi
+}
+
+
+modify_local_ip_env()
+{
+
+#modify the nstack_var.sh
+ local var_config_name=${script_path}/script/$VAR_FILE
+
+ if [ ! -f $var_config_name ]; then
+ log $LINENO "$VAR_FILE not exist , exit!"
+ exit 1
+ fi
+
+ sed -i "s:VM_ID=.*:VM_ID=${nstack_alarm_local_ip}:g" $var_config_name 2>/dev/null
+}
+
+
+delete_pid_file()
+{
+ if [ -n "$PID_FILE" ]&&[ -f "$PID_FILE" ]
+ then
+ rm -rf ${PID_FILE}
+ fi
+}
+
+save_pid_file()
+{
+ if [ ! -d ${PID_FILE_DIR} ];
+ then
+ sudo mkdir -p ${PID_FILE_DIR}
+ chmod 750 ${PID_FILE_DIR}
+ fi
+
+ if [ -f ${PID_FILE} ];
+ then
+ cur_pid=`cat ${PID_FILE}`
+ if [ ${cur_pid} != $1 ];
+ then
+ rm -rf ${PID_FILE}
+ else
+ return
+ fi
+ fi
+
+ touch ${PID_FILE}
+ echo $1 > $PID_FILE
+
+ chown paas:paas $PID_FILE
+ chmod 640 $PID_FILE
+}
+
+write_pid_to_file()
+{
+ retry=3
+ i=0
+ fail=1
+
+ while [ ${i} -lt ${retry} ]
+ do
+ PID=`pidof nStackMaster`
+ if [ ${PID} ]
+ then
+ fail=0
+ break
+ fi
+
+ i=`expr ${i} + 1`
+
+ sleep 1
+ done
+
+ if [ ${fail} -ne 0 ]
+ then
+ return 1
+ fi
+
+ if [ ! -d ${PID_FILE_DIR} ];
+ then
+ sudo mkdir -p ${PID_FILE_DIR}
+ chmod 750 ${PID_FILE_DIR}
+ fi
+
+ touch ${PID_FILE}
+ echo $PID > $PID_FILE
+ #check log file right
+ chown paas:paas $PID_FILE
+ chmod 640 $PID_FILE
+ return 0
+}
+
+
+
+install_config()
+{
+ # set nStackConfig values
+ if [ -n "$DEF_SOCK_NUM" ] ;then
+ sed -i "s/\"socket_num\":[ \t0-9]*,/\"socket_num\":$DEF_SOCK_NUM,/g" ./configure/nStackConfig.json
+ fi
+}
+
+copy_config()
+{
+ # $1 for src nStackServer path
+ # $2 for dst nStackServer path
+
+ # NOTE: set src socket_num value into dst path config file, this is for copying old configuration from old version to new version path when upgrading.
+ SRC_SOCK_NUM=`grep 'socket_num' $1/configure/nStackConfig.json | awk -F"," '{for (i=1;i<=NF;++i) print $i}' | awk 'gsub("\"socket_num\":","") {sub("^[ \t]*","");sub("[ \t]*$",""); print $0}'`
+ sed -i "s/\"socket_num\":[ \t0-9]*,/\"socket_num\":$SRC_SOCK_NUM,/g" $2/configure/nStackConfig.json
+}
diff --git a/stacks/lwip_stack/release/script/nstack_var.sh b/stacks/lwip_stack/release/script/nstack_var.sh
new file mode 100644
index 0000000..15ef2f0
--- /dev/null
+++ b/stacks/lwip_stack/release/script/nstack_var.sh
@@ -0,0 +1,63 @@
+#!/bin/bash
+
+PID_FILE_DIR=/var/ICTS_BASE/run
+PID_FILE=${PID_FILE_DIR}/nstack.pid
+
+RUNNING_FILE_DIR=/var/log/nStack
+RUNNING_FILE_NAME=running.log
+
+OPERATION_FILE_NAME=operation.log
+NSTACK_CTRL_LOG_FILE_NAME=omc_ctrl.log
+GLOG_FAILURE_FILE_NAME=fail_dump.log
+NSTACK_FAILURE_FILE_NAME=nstack_error.log
+
+MASTER_FILE_DIR=/var/log/nStack
+MASTER_FILE_NAME=master.log
+
+LOG_FILE_DIR=/var/log/nStack
+LOG_FILE=${LOG_FILE_DIR}/nstack.log
+LOG_FILE_NAME=nstack.log
+
+DPDK_FILE_DIR=/var/log/nstack-dpdk
+DPDK_FILE=${DPDK_FILE_DIR}/nstack_dpdk.log
+DPDK_FILE_NAME=nstack_dpdk.log
+
+#this is env variable, it is for nstack usage, it will be modified from ./start_nstack -i hostinfo.ini
+
+export VM_ID=agent-node-x
+
+export DPDK_INSTALL_PATH="/root/dpdk/dpdk-18.02"
+export DPDK_LIB_PATH=${DPDK_INSTALL_PATH}/x86_64-native-linuxapp-gcc/lib
+export DPDK_TOOL_DIR=${DPDK_INSTALL_PATH}/usertools
+export DPDK_MOD_PATH=${DPDK_INSTALL_PATH}/x86_64-native-linuxapp-gcc/kmod
+
+cur_user=`whoami`
+if [ "root" != "${cur_user}" ]
+then
+ HOME_DIR=$HOME
+ if [ -z "${HOME}" ]
+ then
+ HOME_DIR=/var/run
+ fi
+else
+ HOME_DIR=/var/run
+fi
+RUNTIME_DIR=$HOME_DIR/ip_module
+
+DPDK_NIC_LIST_FILE=$RUNTIME_DIR/.nstack_dpdk_nic_list
+
+#single file is 50M=50*1024*1024
+MAX_LOG_FILE_SIZE=52428800
+HUGE_PAGES=2048
+HUGE_DIR=/mnt/nstackhuge
+SLEEP_INTERVAL=100 # tcpip thread sleep time, unit: us
+BIND_CPU=0
+MEM_SIZE=2048
+RTP_CORE_MASK=2
+
+MASTER_EXEC_PATH="/product/gpaas/nStackMaster/bin"
+RUN_NSTACK_FILE=run_nstack.sh
+
+
+#default config definitions
+DEF_SOCK_NUM=8192
diff --git a/stacks/lwip_stack/release/script/run_nstack_main.sh b/stacks/lwip_stack/release/script/run_nstack_main.sh
new file mode 100644
index 0000000..2bd9e0d
--- /dev/null
+++ b/stacks/lwip_stack/release/script/run_nstack_main.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+DIR=`S=\`readlink "$0"\`; [ -z "$S" ] && S=$0; dirname $S`
+cd $DIR
+
+. ./nstack_var.sh
+. ./nstack_fun.sh
+
+########################################################
+# check parameter
+
+log $LINENO "dir=$DIR"
+
+########################################################
+# init netrork:unbind->/* modprobe uio->insmod igb_uio */->bind
+init_network
+
+########################################################
+# start nstack main
+CORE_MASK=1
+log $LINENO "start run nstackmain"
+log $LINENO "COREMASK=$CORE_MASK, HUGE_DIR=$1, MEM_SIZE=$2, RTP_CORE_MASK=$RTP_CORE_MASK, SLEEP_INTERVAL=$SLEEP_INTERVAL, BIND_CPU=$BIND_CPU"
+
+run_nStackMain $CORE_MASK $1 $2 $RTP_CORE_MASK $SLEEP_INTERVAL $BIND_CPU
+
+exit 0
diff --git a/stacks/lwip_stack/release/script/run_nstack_master.sh b/stacks/lwip_stack/release/script/run_nstack_master.sh
new file mode 100644
index 0000000..8da0d49
--- /dev/null
+++ b/stacks/lwip_stack/release/script/run_nstack_master.sh
@@ -0,0 +1,29 @@
+#!/bin/sh
+
+DIR=`S=\`readlink "$0"\`; [ -z "$S" ] && S=$0; dirname $S`
+cd $DIR
+. ./nstack_var.sh
+
+
+if [ -n "${MASTER_EXEC_PATH}" ]; then
+ mkdir -p $MASTER_EXEC_PATH
+ chown -R paas: $MASTER_EXEC_PATH
+ chmod 750 $MASTER_EXEC_PATH
+ cp ../bin/nStackMaster $MASTER_EXEC_PATH -rf
+ cp ../configure/nStackConfig.json $MASTER_EXEC_PATH -rf
+ ln -s -f $(cd "$(dirname "$0")"; pwd)/run_nstack_main.sh $MASTER_EXEC_PATH/${RUN_NSTACK_FILE}
+ cd $MASTER_EXEC_PATH
+fi
+
+runnStackMaster(){
+ sudo setcap CAP_IPC_OWNER,CAP_NET_ADMIN,CAP_DAC_OVERRIDE=eip ./nStackMaster
+
+ script_path=$(cd "$(dirname "$0")"; pwd)
+ export NSTACK_CONFIG_PATH=${script_path}
+
+ ./nStackMaster -c $1 -n 4 --huge-dir=$2 -m $3 --proc-type=$4 >> ${DPDK_FILE}
+}
+
+runnStackMaster $1 $2 $3 $4 &
+
+exit 0
diff --git a/stacks/lwip_stack/release/send_alarm.sh b/stacks/lwip_stack/release/send_alarm.sh
new file mode 100644
index 0000000..46ea413
--- /dev/null
+++ b/stacks/lwip_stack/release/send_alarm.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+cur_dir=$(cd "$(dirname "$0")"; pwd)
+alarm_history=${cur_dir}/.nstack_fault_alarm
+
+. ./script/nstack_var.sh
+. ./script/nstack_fun.sh
+
+if [ ! -f ${alarm_history} ]; then
+ ./nStackCtrl --module alm -n nsMain -t abnormal
+ log $LINENO "nstack is not running ok, send fault alarm"
+ touch ${alarm_history}
+else
+ log $LINENO "nstack is not running ok, send fault alarm already"
+fi
+
+exit 0 \ No newline at end of file
diff --git a/stacks/lwip_stack/release/start_nstack.sh b/stacks/lwip_stack/release/start_nstack.sh
new file mode 100644
index 0000000..c005f25
--- /dev/null
+++ b/stacks/lwip_stack/release/start_nstack.sh
@@ -0,0 +1,124 @@
+#!/bin/bash
+
+. ./script/nstack_var.sh
+. ./script/nstack_fun.sh
+
+script_path=$(cd "$(dirname "$0")"; pwd)
+config_name=${script_path}/script/nstack_var.sh
+if [ ! -e $config_name ]; then
+ log $LINENO "nstack_var.sh not exit, plz check!"
+ exit 1
+fi
+
+########################################################
+##get the log info from the parameter of ./start -l XXX -a XXX ###
+nstack_log_path=""
+hostinfo_path=""
+while getopts "l:i:a:" arg
+do
+ case $arg in
+ l)
+ nstack_log_path="$OPTARG"
+ ;;
+ i)
+ hostinfo_path="$OPTARG"
+ ;;
+ esac
+done
+
+hostinfo_stat=0
+
+(
+flock -e -n 200
+if [ $? -eq 1 ]
+then
+ log $LINENO "another process is running now, exit"
+ exit 1
+fi
+
+########################################################
+# modify the nstack & dpdk log path config: nStackConfig.json
+if [ -n "$nstack_log_path" ]; then
+ modify_nstack_log_path $nstack_log_path
+fi
+
+if [ -n "$hostinfo_path" -a -e "$hostinfo_path" -a -r "$hostinfo_path" ]; then
+ nstack_alarm_local_ip=($(awk -F '=' '/\['AGENT'\]/{a=1}a==1&&$1"="~/^(\s*)(VM_ID)(\s*)(=)/{print $2 ;exit}' $hostinfo_path))
+ modify_local_ip_env
+else
+ hostinfo_stat=1
+fi
+
+
+########################################################
+#set the log path in nstack_var.sh#####
+modify_log_var
+) 200>>./lockfile
+
+if [ -f "lockfile" ]; then
+ rm lockfile
+fi
+
+. ./script/nstack_var.sh
+
+
+########################################################
+# init_log_file:nstack.log and dpdk.log
+# if need print log, the messgae need add after init_log_file
+init_log_file
+
+if [ "$hostinfo_stat" -ne 0 ]; then
+ log $LINENO "please use correct -i parameter for start_nstack.sh"
+ log $LINENO "host info path:$hostinfo_path"
+ hostinfo_stat=0
+fi
+
+log $LINENO "######################start nstack######################"
+
+########################################################
+# check application running
+process_nstack_main=nStackMain
+
+pid_nstack=`pidof $process_nstack_main`
+
+nstack_ctrl_path=${script_path}/bin
+
+pgrep nStackMain
+main_run_status=$?
+if [ ${main_run_status} -eq 0 ]; then
+ log $LINENO "nStackMain is running ok, please stop it first!"
+ save_pid_file ${pid_master}
+ exit 0
+fi
+
+huge_files=`ls /mnt/nstackhuge`
+if [ "x${huge_files}" != "x" ]
+then
+ if [ "x${pid_nstack}" = "x" ]
+ then
+ log $LINENO "huge page file exist and nStackMain not exist"
+ exit 1
+ fi
+fi
+
+
+########################################################
+# set hugepage
+init_hugepage $process_nstack_main
+
+
+########################################################
+# install config
+install_config
+
+########################################################
+core_mask=1
+START_TYPE="primary"
+log $LINENO "./script/run_nstack_main.sh ${core_mask} $HUGE_DIR $MEM_SIZE $START_TYPE"
+cd script
+./run_nstack_main.sh $HUGE_DIR $MEM_SIZE
+
+print_pid=$(ps -ux | grep nStackMain | awk '{print $2}' | awk 'NR == 2')
+echo "nStackMain PID:$print_pid"
+log $LINENO "nstack start success"
+exit 0
diff --git a/stacks/lwip_stack/release/stop_nstack.sh b/stacks/lwip_stack/release/stop_nstack.sh
new file mode 100644
index 0000000..9b9fe94
--- /dev/null
+++ b/stacks/lwip_stack/release/stop_nstack.sh
@@ -0,0 +1,49 @@
+#!/bin/bash
+
+. ./script/nstack_var.sh
+. ./script/nstack_fun.sh
+
+script_path=$(cd "$(dirname "$0")"; pwd)
+config_name=${script_path}/script/nstack_var.sh
+if [ ! -e $config_name ]; then
+ log $LINENO "$config_name not exit, plz pay attention and add back!,or it has resourcce leak."
+fi
+
+cur_user=`whoami`
+
+########################################################
+# init_log_file:nstack.log and dpdk.log
+init_log_file
+log $LINENO "#######################stop nstack#######################"
+
+#############################################
+# step1 stop nstack master
+retry=3
+stop_nStackProcess nStackMaster $retry
+
+#############################################
+# step2 stop nstack
+stop_nStackProcess nStackMain $retry
+
+
+#############################################
+# step3 stop all apps that usg the nstack hugepage
+if [ ${cur_user} = "root" ]; then
+ stop_nStackApps
+else
+ log $LINENO "not root, app not stopped"
+fi
+
+#############################################
+# step4 delete the huge page files created by nstack
+recover_hugepage
+
+#############################################
+# step5 recover the nic configuration
+recover_network
+
+#############################################
+# step6 delete pid file
+delete_pid_file
+
+exit 0
diff --git a/stacks/lwip_stack/release/uninstall.sh b/stacks/lwip_stack/release/uninstall.sh
new file mode 100644
index 0000000..92ae5fe
--- /dev/null
+++ b/stacks/lwip_stack/release/uninstall.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+
+. ./script/nstack_var.sh
+. ./script/nstack_fun.sh
+
+########################################################
+# init_log_file:nstack.log and dpdk.log
+init_log_file
+log $LINENO "#######################uninstall nstack#######################"
+
+
+#############################################
+# step1 stop the applications that use the shared huge memory of nstack
+stop_nStackApps
+
+#############################################
+# step2 delete the huge page files created by nstack
+recover_hugepage
+
+
+#############################################
+# step3 recover the nic configuration
+recover_network
+
+
+#############################################
+# step4 delete nstack log files
+delete_log_file
+
+
+# log file has been deleted, should print on screen now
+echo "uninstall nStack successfully!"
+
+exit 0
diff --git a/stacks/lwip_stack/release/upgrade_nstack.sh b/stacks/lwip_stack/release/upgrade_nstack.sh
new file mode 100644
index 0000000..9302da6
--- /dev/null
+++ b/stacks/lwip_stack/release/upgrade_nstack.sh
@@ -0,0 +1,452 @@
+#!/bin/bash
+
+. ./script/nstack_var.sh
+. ./script/nstack_fun.sh
+
+VERSION_CHK=0
+UPG_MASTER=0
+
+# OLD_VERSION indicates the nStackServer version, in order to support Version upgrade and rollback feature
+# OLD_VERSION=1 B031~newest
+# OLD_VERSION=0 B020~B030
+OLD_VERSION=1
+cur_user=`whoami`
+
+upg_pre_chk()
+{
+ ##########check input info###########################
+ if [ -z "${DST_VER_PATH}" ]; then
+ log $LINENO "dst ${DST_VER_PATH} path error!"
+ return 1
+ fi
+
+ if [ "x${UPG_RBK}" != "x1" -a "x${UPG_RBK}" != "x2" ]; then
+ log $LINENO "type error ${UPG_RBK}!"
+ return 1
+ fi
+
+ ##########check src version info######################
+ SRC_STOP_FILE=${SRC_VER_PATH}/stop_nstack.sh
+ if [ ! -f "$SRC_STOP_FILE" ]; then
+ log $LINENO "${SRC_STOP_FILE} path error!"
+ return 1
+ fi
+
+ MASTER_PATH=`get_nstack_bin nStackMaster`
+ if [ -z "${MASTER_PATH}" ]; then
+ log $LINENO "master not start"
+ return 1
+ fi
+
+ if [ ! -d "${MASTER_PATH}${MASTERBIN}" ]; then
+ log $LINENO "${MASTER_PATH} path error!"
+ return 1
+ fi
+
+ SRC_VERSION=`get_version 1`
+ if [ -z "${SRC_VERSION}" ]; then
+ log $LINENO "get srcVersion error"
+ exit 1
+ fi
+
+ ###########check dst version info######################
+ DST_RUN_FILE=${DST_VER_PATH}/script/run_nstack_main.sh
+ if [ ! -f "$DST_RUN_FILE" ]; then
+ log $LINENO "${DST_RUN_FILE} path error. Try the path of older nstack version then."
+ DST_RUN_FILE=${DST_VER_PATH}/bin/run_nstack_main.sh
+ OLD_VERSION=0
+ if [ ! -f "$DST_RUN_FILE" ]; then
+ log $LINENO "${DST_RUN_FILE} older path error!"
+ return 1
+ fi
+ fi
+
+ DST_STOP_FILE=${DST_VER_PATH}/stop_nstack.sh
+ if [ ! -f "$DST_STOP_FILE" ]; then
+ log $LINENO "${DST_STOP_FILE} path error!"
+ return 1
+ fi
+
+ DST_STAT_FILE=${DST_VER_PATH}/start_nstack.sh
+ if [ ! -f "$DST_STAT_FILE" ]; then
+ log $LINENO "${DST_STAT_FILE} path error!"
+ return 1
+ fi
+
+ if [ ! -x "${DST_VER_PATH}/bin/nStackCtrl" ]; then
+ log $LINENO "${DST_VER_PATH} path nStackCtrl exec error!"
+ return 1
+ fi
+
+ DST_VERSION=`get_version 4 ${DST_VER_PATH}/bin/nStackCtrl`
+ if [ -z "${DST_VERSION}" ]; then
+ log $LINENO "get dstversion error"
+ return 1
+ fi
+}
+
+restart_upgrade()
+{
+ local monipid=`pidof monit`
+ local stop_moni=0
+ if [ ! -z "${monipid}" ]; then
+ for i in `seq 60`
+ do
+ if [ ${cur_user} = "paas" ]; then
+ stop_fin=`/var/ICTS_BASE/Monit/bin/monit summary | grep nstack | grep "Not monitored"`
+ else
+ stop_fin=`su paas -s /bin/bash -c "/var/ICTS_BASE/Monit/bin/monit summary" | grep nstack | grep "Not monitored"`
+ fi
+ if [ -n "${stop_fin}" ]; then
+ break;
+ fi
+
+ if [ $stop_moni -eq 0 ]; then
+ if [ ${cur_user} = "paas" ]; then
+ /var/ICTS_BASE/Monit/bin/monit unmonitor nstack
+ else
+ su paas -s /bin/bash -c "/var/ICTS_BASE/Monit/bin/monit unmonitor nstack"
+ fi
+ stop_moni=1
+ log $LINENO "stop monit"
+ fi
+
+ sleep 1
+ done
+ cd ${SRC_VER_PATH}
+ ./stop_nstack.sh
+ cd -
+ cd ${DST_VER_PATH}
+ if [ -n "${LOG_PATH}" ]; then
+ ./start_nstack.sh -l $LOG_PATH -i $hostinfo_path
+ else
+ ./start_nstack.sh -i $hostinfo_path
+ fi
+ cd -
+
+ log $LINENO "with monit restart"
+ if [ $stop_moni -eq 1 ]; then
+ if [ ${cur_user} = "paas" ]; then
+ /var/ICTS_BASE/Monit/bin/monit monitor nstack
+ else
+ su paas -s /bin/bash -c "/var/ICTS_BASE/Monit/bin/monit monitor nstack"
+ fi
+ log $LINENO "monit restart"
+ fi
+ else
+ cd ${SRC_VER_PATH}
+ ./stop_nstack.sh
+ cd -
+ cd ${DST_VER_PATH}
+ if [ -n "${LOG_PATH}" ]; then
+ ./start_nstack.sh -l $LOG_PATH -i $hostinfo_path
+ else
+ ./start_nstack.sh -i $hostinfo_path
+ fi
+ cd -
+ log $LINENO "none monit restart"
+ fi
+ return 0
+}
+
+run_upgrade()
+{
+
+ if [ -n "${DST_RUN_FILE}" ]; then
+ if [ $OLD_VERSION -ge 1 ]; then
+ ln -s -f "$DST_RUN_FILE" "${DST_VER_PATH}/script/${RUN_NSTACK_FILE}"
+ else
+ ln -s -f "$DST_RUN_FILE" "${DST_VER_PATH}/bin/${RUN_NSTACK_FILE}"
+ fi
+ if [ $? -ne 0 ]; then
+ log $LINENO "dst version link failed!"
+ return 1
+ fi
+ fi
+
+ # copy old config to avoid config change issue
+ copy_config $SRC_VER_PATH $DST_VER_PATH
+
+ ./bin/nStackCtrl --module vermgr -t $UPG_RBK -s $SRC_VERSION -d $DST_VERSION
+ ret=$?
+ if [ $ret -eq 121 ]; then
+ restart_upgrade
+ WAIT_TIME=50
+ RESTART_MASTER=1
+ return 0
+ fi
+
+ if [ $ret -ne 0 ]; then
+ log $LINENO "nStackCtrl send vermsg err $ret code"
+ return 1
+ fi
+
+ nStackMain_pid=`pidof nStackMain`
+ if [ -n "${DST_RUN_FILE}" ]; then
+ ln -s -f "$DST_RUN_FILE" "${MASTER_PATH}${RUN_NSTACK_FILE}"
+ if [ $? -ne 0 ]; then
+ log $LINENO "link failed!"
+ kill -9 $nStackMain_pid
+ return 1
+ fi
+ fi
+ kill -9 $nStackMain_pid
+ return 0
+}
+
+after_upg_chk()
+{
+ for i in `seq $WAIT_TIME`
+ do
+ NEW_DST_VERSION=`get_version 1`
+ if [ -n "${NEW_DST_VERSION}" ]; then
+ if [ "$NEW_DST_VERSION" != "$DST_VERSION" ]; then
+ log $LINENO "new version:$NEW_DST_VERSION maybe error! expect version is:$DST_VERSION"
+ else
+ break;
+ fi
+ fi
+ sleep 1
+ done
+
+ if [ -z "${NEW_DST_VERSION}" ]; then
+ log $LINENO "nStackCtrl get dstVersion error"
+ return 1
+ fi
+
+ if [ "$NEW_DST_VERSION" != "$DST_VERSION" -a $VERSION_CHK -eq 1 ]; then
+ log $LINENO "new version:$NEW_DST_VERSION maybe error! expect version is:$DST_VERSION"
+ return 1
+ fi
+
+ DST_MAIN_PATH=`get_nstack_bin nStackMain`
+ if [ -z "${DST_MAIN_PATH}" ]; then
+ log $LINENO "main not start"
+ return 1
+ fi
+
+ if [ "$DST_MAIN_PATH" != "${DST_VER_PATH}/bin/" ]; then
+ log $LINENO "main start failed run;$DST_MAIN_PATH expect:${DST_VER_PATH}/script !"
+ return 1
+ fi
+}
+
+
+run_upgrade_master()
+{
+ core_mask=`get_core_mask`
+ START_TYPE="secondary"
+ ./bin/nStackCtrl --module vermgr -t $UPG_RBK -s $SRC_VERSION -d $DST_VERSION -p 2
+ ret=$?
+ if [ $ret -ne 0 ]; then
+ log $LINENO "nStackMaster nStackCtrl send vermsg err $ret code"
+ return 1
+ fi
+
+ nStackMaster_pid=`pidof nStackMaster`
+ kill -9 $nStackMaster_pid
+ cd ${DST_VER_PATH}/script/
+ ./run_nstack_master.sh ${core_mask} $HUGE_DIR $MEM_SIZE $START_TYPE
+ log $LINENO "./script/run_nstack_master.sh ${core_mask} $HUGE_DIR $MEM_SIZE $START_TYPE"
+ cd -
+ return 0
+}
+
+
+after_upg_master_chk()
+{
+ for i in `seq 10`
+ do
+ NEW_MAS_VERSION=`get_version 2`
+ if [ -n "${NEW_MAS_VERSION}" ]; then
+ if [ "$NEW_MAS_VERSION" != "$DST_VERSION" ]; then
+ log $LINENO "new version:$NEW_MAS_VERSION maybe error! expect version is:$DST_VERSION"
+ else
+ break;
+ fi
+ fi
+ sleep 1
+ done
+
+ if [ -z "${NEW_MAS_VERSION}" ]; then
+ log $LINENO "nStackCtrl get dstVersion error"
+ return 1
+ fi
+
+ if [ "$NEW_MAS_VERSION" != "$DST_VERSION" -a $VERSION_CHK -eq 1 ]; then
+ log $LINENO "new version:$NEW_MAS_VERSION maybe error! expect version is:$DST_VERSION"
+ return 1
+ fi
+
+ DST_MAS_PATH=`get_nstack_bin nStackMaster`
+ if [ -z "${DST_MAS_PATH}" ]; then
+ log $LINENO "master not start"
+ return 1
+ fi
+
+ if [ "$DST_MAS_PATH" != "${DST_VER_PATH}/script/" ]; then
+ log $LINENO "main start failed run;$DST_MAS_PATH expect:${DST_VER_PATH}/script !"
+ return 1
+ fi
+ return 0
+}
+
+opr_suc()
+{
+ log $LINENO "operation successful $SRC_VERSION to $NEW_DST_VERSION"
+}
+
+mod_log_path()
+{
+ local dst_proc=$1
+ local dst_log_path=$2
+ ./bin/nStackCtrl --module setlog -n maspath -v ${dst_log_path} -p $dst_proc
+ ret=$?
+ if [ $ret -ne 0 ]; then
+ log $LINENO "mod_log_path error err $ret code"
+ return 1
+ fi
+ return 0
+}
+
+ini_file_path="invalid_path_upgrade"
+
+while getopts 's:d:t:l:i:' opt
+do
+ case $opt in
+ s)
+ SRC_VER_PATH=`get_abs_path $OPTARG`
+ ;;
+ :)
+ echo "-$OPTARG needs an argument"
+ exit 1
+ ;;
+ d)
+ DST_VER_PATH=`get_abs_path $OPTARG`
+ ;;
+ :)
+ echo "-$OPTARG needs an argument"
+ exit 1
+ ;;
+ t)
+ UPG_RBK=$OPTARG
+ ;;
+ :)
+ echo "-$OPTARG needs an argument"
+ exit 1
+ ;;
+ l)
+ LOG_PATH=`get_abs_path $OPTARG`
+ ;;
+ :)
+ echo "-$OPTARG needs an argument"
+ exit 1
+ ;;
+ i)
+ ini_file_path=`get_abs_path $OPTARG`
+ ;;
+ :)
+ echo "-$OPTARG needs an argument"
+ exit 1
+ ;;
+ *)
+ echo "command not recognized"
+ usage
+ exit 1
+ ;;
+ esac
+done
+
+if [ -z $ini_file_path ]; then
+ hostinfo_path="invalid_path_upgrade"
+ else
+ hostinfo_path=$ini_file_path
+fi
+
+(
+flock -e -n 201
+if [ $? -eq 1 ]
+then
+ log $LINENO "another upgrade process is running now, exit"
+ exit 1
+fi
+
+if [ -n "${LOG_PATH}" ]; then
+ modify_nstack_log_path ${LOG_PATH}
+fi
+modify_log_var
+) 201>>./uplockfile
+
+if [ -f "uplockfile" ]; then
+ rm uplockfile
+fi
+
+. ./script/nstack_var.sh
+
+RESTART_MASTER=0
+WAIT_TIME=60
+
+log $LINENO "######################upgrade nstack######################"
+log $LINENO "src ver path ${SRC_VER_PATH},dst ver path ${DST_VER_PATH}, type ${UPG_RBK}, log path ${LOG_PATH}"
+
+upg_pre_chk
+ret=$?
+if [ $ret -ne 0 ]; then
+ log $LINENO "pre_chk error err $ret code"
+ exit 1
+fi
+
+if [ "${DST_VERSION}" = "${SRC_VERSION}" -a $VERSION_CHK -eq 1 ]; then
+ log $LINENO "version equal ${DST_VERSION} ${SRC_VERSION}"
+ exit 0
+fi
+log $LINENO "prepare ok"
+
+log $LINENO "src ver $SRC_VERSION with master path $MASTER_PATH,dst ver $DST_VERSION,dst run file $DST_RUN_FILE, type ${UPG_RBK}"
+run_upgrade
+ret=$?
+if [ $ret -ne 0 ]; then
+ log $LINENO "run_proc error err $ret code"
+ exit 1
+fi
+
+log $LINENO "wait new version start"
+sleep 2
+after_upg_chk
+ret=$?
+if [ $ret -ne 0 ]; then
+ log $LINENO "after_chk error err $ret code"
+ exit 1
+fi
+
+if [ $RESTART_MASTER -ne 0 ]; then
+ log $LINENO "master has restart!"
+ opr_suc
+ exit 0
+fi
+
+if [ $UPG_MASTER -eq 0 ]; then
+ if [ -n "${LOG_PATH}" ]; then
+ mod_log_path 2 ${LOG_PATH}
+ fi
+ opr_suc
+ exit 0
+fi
+
+run_upgrade_master
+ret=$?
+if [ $ret -ne 0 ]; then
+ log $LINENO "run_proc master error err $ret code"
+ exit 1
+fi
+
+log $LINENO "wait new version master start"
+sleep 2
+after_upg_master_chk
+ret=$?
+if [ $ret -ne 0 ]; then
+ log $LINENO "after_chk master error err $ret code"
+ exit 1
+fi
+
+opr_suc
diff --git a/stacks/lwip_stack/release_tar.sh b/stacks/lwip_stack/release_tar.sh
new file mode 100644
index 0000000..6c2928f
--- /dev/null
+++ b/stacks/lwip_stack/release_tar.sh
@@ -0,0 +1,86 @@
+if [ ! -d "./nStackServer" ]; then
+ mkdir ./nStackServer
+else
+ rm -rf ./nStackServer/*
+fi
+
+if [ ! -d "./nStackClient" ]; then
+ mkdir ./nStackClient
+else
+ rm -rf ./nStackClient/*
+fi
+
+if [ ! -d "./nStackTools" ]; then
+ mkdir ./nStackTools
+else
+ rm -rf ./nStackTools/*
+fi
+
+if [ -f "./nStackServer.tar.gz" ]; then
+ rm -rf ./nStackServer.tar.gz
+fi
+
+if [ -f "./nStackClient.tar.gz" ]; then
+ rm -rf ./nStackClient.tar.gz
+fi
+
+if [ -f "./nStackTools.tar.gz" ]; then
+ rm -rf ./nStackTools.tar.gz
+fi
+
+mkdir ./nStackServer/lib64
+cp ./release/lib64/libnstack.so ./release/lib64/libnStackAPI.so ./release/lib64/libnstackcmd.so ./release/lib64/libsecurec.so ./nStackServer/lib64
+mkdir ./nStackServer/bin
+cp ./release/bin/nStackCtrl ./release/bin/nStackMain ./release/bin/nStackMaster ./release/bin/set_permission.sh ./nStackServer/bin
+mkdir ./nStackServer/conf
+cp ./release/conf/nstack.monitrc ./release/conf/nstack_ctl ./release/conf/srvnstack ./nStackServer/conf
+mkdir ./nStackServer/configure
+cp ./release/configure/ip_data.json ./release/configure/network_data_tonStack.json ./release/configure/nStackConfig.json ./nStackServer/configure
+mkdir ./nStackServer/script
+cp -d ./release/script/nstack_fun.sh ./release/script/nstack_var.sh ./release/script/run_nstack_main.sh ./release/script/run_nstack_master.sh ./nStackServer/script
+mkdir ./nStackServer/tools
+cp ./release/tools/nping ./nStackServer/tools/
+
+cp ./release/check_status.sh ./release/send_alarm.sh ./release/start_nstack.sh ./release/stop_nstack.sh ./release/graceful_stop_nstack.sh ./release/uninstall.sh ./release/upgrade_nstack.sh ./nStackServer/
+
+dos2unix ./nStackServer/*.sh
+find ./nStackServer -type f | grep -E "*.sh|*.py" | xargs chmod +x
+
+mkdir ./nStackClient/lib64
+cp ./release/lib64/libnstack.so ./release/lib64/libnStackAPI.so ./release/lib64/libsecurec.so ./nStackClient/lib64
+mkdir ./nStackClient/include
+cp ./release/include/nstack_custom_api.h ./nStackClient/include
+
+cp ./release/tools/nping ./release/tools/ntcpdump ./nStackTools/
+
+# set permission
+chown -R paas: ./nStackServer/
+chown -R paas: ./nStackClient/
+chown -R paas: ./nStackTools/
+
+chmod 750 ./nStackServer
+chmod 550 ./nStackServer/bin/
+chmod 750 ./nStackServer/configure
+chmod 750 ./nStackServer/script
+chmod 750 ./nStackServer/conf
+chmod 750 ./nStackServer/lib64
+chmod 750 ./nStackServer/tools
+chmod 750 ./nStackClient
+chmod 750 ./nStackClient/include
+chmod 750 ./nStackClient/lib64
+chmod 750 ./nStackTools
+
+chmod 750 ./nStackServer/bin/nStack*
+chmod 750 ./nStackServer/*.sh
+chmod 750 ./nStackServer/bin/*.sh
+chmod 750 ./nStackServer/conf/*
+chmod 750 ./nStackServer/script/*.sh
+chmod 640 ./nStackServer/lib64/*
+chmod 640 ./nStackServer/configure/*
+chmod 500 ./nStackServer/bin/set_permission.sh
+chmod 750 ./nStackTools/*
+
+
+tar -zcvf nStackServer.tar.gz nStackServer
+tar -zcvf nStackClient.tar.gz nStackClient
+tar -zcvf nStackTools.tar.gz nStackTools
diff --git a/stacks/lwip_stack/run_stackx.txt b/stacks/lwip_stack/run_stackx.txt
new file mode 100644
index 0000000..7322635
--- /dev/null
+++ b/stacks/lwip_stack/run_stackx.txt
@@ -0,0 +1,131 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+#build DPDK
+#Note: build path /root/dpdk/ , install path /root/dpdk_install/tmp
+===================================================================
+if [ -d /root/dpdk_install/tmp ]; then
+ rm -rf /root/dpdk_install/tmp
+fi
+
+mkdir -p /root/dpdk
+
+cd /root/dpdk
+rm -rf dpdk-16.04/
+wget https://fast.dpdk.org/rel/dpdk-16.04.tar.xz
+tar xvf dpdk-16.04.tar.xz
+cd dpdk-16.04/
+
+sed -i 's!CONFIG_RTE_EXEC_ENV=.*!CONFIG_RTE_EXEC_ENV=y!1' config/common_base
+sed -i 's!CONFIG_RTE_BUILD_SHARED_LIB=.*!CONFIG_RTE_BUILD_SHARED_LIB=y!1' config/common_base
+sed -i 's!CONFIG_RTE_LIBRTE_EAL=.*!CONFIG_RTE_LIBRTE_EAL=y!1' config/common_base
+
+make install T=x86_64-native-linuxapp-gcc DESTDIR=/root/dpdk_install/tmp
+cd x86_64-native-linuxapp-gcc
+make
+
+cp -r /root/dpdk/dpdk-16.04/tools/dpdk_nic_bind.py /root/dpdk/dpdk-16.04/tools/dpdk-devbind.py
+
+mount -t hugetlbfs -o pagesize=1G none /mnt/nstackhuge/
+mkdir /var/run/ip_module
+
+#verify hugepages 8GB free hugepages are required
+=================================================
+cat /proc/meminfo
+
+#build DMM
+============
+#got to DMM/
+
+cd thirdparty/glog/glog-0.3.4/
+sudo autoreconf -ivf
+
+cd -
+cd build/
+
+cmake ..
+make -j 8
+
+#build stackx
+================
+cd ../thirdparty/glog/glog-0.3.4/
+sudo autoreconf -ivf
+
+cd -
+cd ../stacks/lwip_stack/build/
+
+cmake ..
+make -j 8
+
+#run app
+========
+cd ../
+chmod +x release_tar.sh
+./release_tar.sh
+
+tar -zxf nStackServer.tar.gz
+
+cd nStackServer/
+cp configure/*.json bin/
+
+##make json file changes
+#I have copied the working configs in the path /home/sharath/working_config/
+
+#server
+cp -r /home/sharath/working_config/server/ip_data.json bin/
+cp -r /home/sharath/working_config/server/network_data_tonStack.json bin/
+cp -r /home/sharath/working_config/server/nStackConfig.json bin/
+
+#client
+cp -r /home/sharath/working_config/client/ip_data.json bin/
+cp -r /home/sharath/working_config/client/network_data_tonStack.json bin/
+cp -r /home/sharath/working_config/client/nStackConfig.json bin/
+
+#dpdk download path : /root/dpdk/dpdk-16.04/
+sed -i 's!export DPDK_INSTALL_PATH.*!export DPDK_INSTALL_PATH="/root/dpdk/dpdk-16.04"!1' ../release/script/nstack_var.sh
+
+cd ../../../release/bin/
+cp ../configure/*.json .
+
+#server
+cp -r /home/sharath/working_config/server/module_config.json .
+cp -r /home/sharath/working_config/server/nStackConfig.json .
+cp -r /home/sharath/working_config/server/rd_config.json .
+
+#client
+cp -r /home/sharath/working_config/client/module_config.json .
+cp -r /home/sharath/working_config/client/nStackConfig.json .
+cp -r /home/sharath/working_config/client/rd_config.json .
+
+cd -
+./stop_nstack.sh
+./start_nstack.sh
+
+#verify process up
+ps aux | grep nS
+
+cd bin
+./nStackCtrl -a add -p ./network_data_tonStack.json -t network
+./nStackCtrl -a add -p ./ip_data.json -t ip
+
+cd ../../../../release/bin/
+cp ../../stacks/lwip_stack/release/lib64/libnstack.so .
+
+#server
+./vs_epoll -p 20000 -d 192.168.1.207 -a 10000 -s 192.168.1.206 -l 200 -t 5000000 -i 0 -f 1 -r 20000 -n 1 -w 10 -u 10000 -e 10 -x 1
+
+#client
+./vc_epoll -p 20000 -d 192.168.1.206 -a 10000 -s 192.168.1.207 -l 200 -t 50000 -i 1000 -f 1 -r 20000 -n 1 -w 10 -u 10000 -e 10 -x 1
diff --git a/stacks/lwip_stack/src/CMakeLists.txt b/stacks/lwip_stack/src/CMakeLists.txt
new file mode 100644
index 0000000..6aacf07
--- /dev/null
+++ b/stacks/lwip_stack/src/CMakeLists.txt
@@ -0,0 +1,62 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+SET(RTP_DIRECTORIES "${PROJECT_SOURCE_DIR}/src/include/")
+
+INCLUDE_DIRECTORIES(
+ framework/log/
+ framework/include/
+ framework/common/include/
+ framework/common/base/include/
+ ${RTP_DIRECTORIES}
+ ${RTP_DIRECTORIES}/generic
+ ../../SecureC/include/
+ ../../../thirdparty/glog/glog-0.3.4/src/
+)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g -fPIC -m64 -mssse3 -std=gnu89")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wshadow -Wfloat-equal -Wformat=2")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector -fstack-protector-all")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-z,relro,-z,now -Wl,--disable-new-dtags,--rpath,../lib64")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-z,noexecstack -mcmodel=medium")
+
+if(WITH_HAL_LIB)
+SET(RTP_CONFIG ${PROJECT_SOURCE_DIR}/src/include/rtp_config.h)
+else()
+ SET(RTP_CONFIG ${CMAKE_CURRENT_LIST_DIR}/../../../src/framework/common/base/include/common/common_sys_config.h)
+endif()
+SET(COMPLE_CONFIG ${PROJECT_SOURCE_DIR}/src/include/compile_config.h)
+ADD_DEFINITIONS(-include ${RTP_CONFIG})
+ADD_DEFINITIONS(-include ${COMPLE_CONFIG})
+ADD_DEFINITIONS(-D_GNU_SOURCE)
+ADD_DEFINITIONS(-DDPDK_MODULE=0)
+#ADD_DEFINITIONS(-DNSTACK_RSRDMA)
+LINK_DIRECTORIES(${LIB_PATH_SHARED} ${LIB_PATH_STATIC})
+
+if(WITH_SECUREC_LIB)
+LINK_LIBRARIES(pthread dl securec)
+else()
+LINK_LIBRARIES(pthread dl)
+endif()
+
+ADD_SUBDIRECTORY(maintain)
+ADD_SUBDIRECTORY(io_adpt)
+ADD_SUBDIRECTORY(sbr)
+#ADD_SUBDIRECTORY(nStackCtrl)
+ADD_SUBDIRECTORY(nStackMain)
+ADD_SUBDIRECTORY(tools)
+ADD_SUBDIRECTORY(alarm)
+#ADD_SUBDIRECTORY(nstackcmd)
diff --git a/stacks/lwip_stack/src/alarm/CMakeLists.txt b/stacks/lwip_stack/src/alarm/CMakeLists.txt
new file mode 100644
index 0000000..3de07b0
--- /dev/null
+++ b/stacks/lwip_stack/src/alarm/CMakeLists.txt
@@ -0,0 +1,34 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+FILE(GLOB_RECURSE ALARM *.c)
+
+LINK_LIBRARIES(m dl rt dmm_api)
+if(WITH_SECUREC_LIB)
+INCLUDE_DIRECTORIES(
+ ./
+ ${JSON_C_SRC}
+ ${SECUREC_SRC}
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+)
+else()
+INCLUDE_DIRECTORIES(
+ ./
+ ${JSON_C_SRC}
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+)
+endif()
+ADD_LIBRARY(nStackAlarm STATIC ${ALARM})
diff --git a/stacks/lwip_stack/src/alarm/alarm.c b/stacks/lwip_stack/src/alarm/alarm.c
new file mode 100644
index 0000000..5f89cdd
--- /dev/null
+++ b/stacks/lwip_stack/src/alarm/alarm.c
@@ -0,0 +1,863 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "types.h"
+#include "nsfw_mgr_com_api.h"
+#include "nsfw_fd_timer_api.h"
+#include "alarm.h"
+#include "alarm_api.h"
+#include<time.h>
+#include<sys/time.h>
+#include "nsfw_init.h"
+#include "nstack_log.h"
+#include "json.h"
+#include "nstack_securec.h"
+#include <stdlib.h>
+#include "nstack_dmm_adpt.h"
+
+char g_vmid[MAX_VMID_LEN + 1] = "agent-node-x";
+
+extern nsfw_timer_info *nsfw_timer_reg_timer (u32 timer_type, void *data,
+ nsfw_timer_proc_fun fun,
+ struct timespec time_left);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif /* __cplusplus */
+
+// note:the first element is reserved
+alarm_data g_alarm_data[ALARM_EVENT_MAX] = { };
+
+alarm_result
+ms_alarm_check_func (void *para)
+{
+ alarm_result ret_alarm;
+ int para_value = (long) para;
+
+ ret_alarm.alarm_id_get = ALARM_EVENT_NSTACK_MAIN_ABNORMAL;
+
+ if (para_value == ALARM_PRODUCT)
+ {
+ ret_alarm.alarm_flag_get = ALARM_PRODUCT;
+ }
+ else if (para_value == ALARM_CLEAN)
+ {
+ ret_alarm.alarm_flag_get = ALARM_CLEAN;
+ }
+ else
+ {
+ ret_alarm.alarm_id_get = ALARM_EVENT_MAX;
+ }
+
+ ret_alarm.alarm_reason_get = ALARM_REASON_NSMAIN;
+
+ return ret_alarm;
+
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : period check alarm expire handle function
+********************************************************************/
+
+int
+ns_alarm_timer_resend_fun (u32 timer_type, void *argv)
+{
+ int i;
+ struct timespec time_left;
+ alarm_data *alarm_value;
+
+ for (i = ALARM_EVENT_BASE; i < ALARM_EVENT_MAX; i++)
+ {
+ alarm_value = &g_alarm_data[i];
+
+ if ((alarm_value->valid_flag == 1)
+ && (alarm_value->send_succ_flag == ALARM_SEND_FAIL))
+ {
+ /* nStack only send nsMain normal alarm */
+ ns_send_alarm_inner (alarm_value->_alarm_id,
+ (void *) (alarm_value->_alarm_flag), 1, 0);
+ }
+ }
+
+ time_left.tv_sec = ALARM_RESEND_TIMER_LENGTH;
+ time_left.tv_nsec = 0;
+ nsfw_timer_info *timer_info =
+ nsfw_timer_reg_timer (0, NULL, ns_alarm_timer_resend_fun, time_left);
+ if (NULL == timer_info)
+ {
+ NSAM_LOGERR ("nsfw_timer_reg_timer fail");
+ }
+
+ return 0;
+}
+
+void
+ns_alarm_set_sendFlag (enum_alarm_id alarmId, int flag)
+{
+ if ((alarmId <= 0) || (alarmId >= ALARM_EVENT_MAX)
+ || (0 == g_alarm_data[alarmId].valid_flag) || ((flag != ALARM_SEND_FAIL)
+ && (flag !=
+ ALARM_SEND_SUCC)))
+ {
+ NSAM_LOGERR ("alarm_id is invalid or not reg or flag invalid");
+ return;
+ }
+ g_alarm_data[alarmId].send_succ_flag = flag;
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : alarm module init
+********************************************************************/
+int
+ns_alarm_module_init (void *param)
+{
+ u32 proc_type = (u32) ((long long) param);
+ enum_alarm_id i = ALARM_EVENT_BASE;
+ alarm_reason j = ALARM_REASON_BEGIN;
+ const char *pst_vm_id = NULL;
+ alarm_para tcp_alarm_para;
+ struct timespec time_left;
+
+ for (i = ALARM_EVENT_BASE; i < ALARM_EVENT_MAX; i++)
+ {
+ g_alarm_data[i]._alarm_type = ALARM_SEND_ONCE;
+
+ for (j = ALARM_REASON_BEGIN; j < ALARM_REASON_MAX; j++)
+ {
+ g_alarm_data[i]._alarm_para.func_alarm_check[j] = NULL;
+ g_alarm_data[i]._alarm_para.alarm_reason_set[j] = ALARM_REASON_MAX;
+ g_alarm_data[i].alarm_time_laps[j] = 0;
+ }
+ g_alarm_data[i]._alarm_para.period_alarm.time_length = 0;
+ g_alarm_data[i]._alarm_id = i;
+ g_alarm_data[i].valid_flag = 0;
+ g_alarm_data[i]._alarm_flag = ALARM_CLEAN;
+ g_alarm_data[i].alarm_reason_cnt = 0;
+ g_alarm_data[i].send_succ_flag = ALARM_SEND_SUCC;
+ }
+
+ switch (proc_type)
+ {
+ case NSFW_PROC_MAIN:
+
+ case NSFW_PROC_MASTER:
+ case NSFW_PROC_CTRL:
+
+ /* [S138713][p00329905][20171219]modify ip address to vm id */
+ pst_vm_id = getenv ("VM_ID");
+
+ if (INVALID_STR_LEN (pst_vm_id, MIN_VM_ID_LEN, MAX_VM_ID_LEN))
+ {
+ NSAM_LOGWAR
+ ("invalid VM_ID,please check env VM_ID]vm_id=%s, proc_type=%u",
+ pst_vm_id, proc_type);
+ }
+ else
+ {
+ int retVal = STRNCPY_S (g_vmid, MAX_VMID_LEN + 1, pst_vm_id,
+ strlen (pst_vm_id));
+
+ if (EOK != retVal)
+ {
+ NSAM_LOGERR ("STRNCPY_S failed]ret=%d", retVal);
+ }
+ }
+
+ tcp_alarm_para.period_alarm.time_length = 0; /* 5 second period */
+ tcp_alarm_para.alarm_reason_count = 1; /*both resource */
+
+ tcp_alarm_para.func_alarm_check[0] = ms_alarm_check_func;
+ tcp_alarm_para.alarm_reason_set[0] = ALARM_REASON_NSMAIN;
+ (void) ns_reg_alarm (ALARM_EVENT_NSTACK_MAIN_ABNORMAL, ALARM_SEND_ONCE,
+ &tcp_alarm_para);
+
+ time_left.tv_sec = ALARM_INIT_RESEND_TIMER_LENGTH;
+ time_left.tv_nsec = 0;
+ nsfw_timer_info *timer_info =
+ nsfw_timer_reg_timer (0, NULL, ns_alarm_timer_resend_fun, time_left);
+ if (NULL == timer_info)
+ {
+ NSAM_LOGERR ("nsfw_timer_reg_timer fail");
+ }
+
+ break;
+ default:
+ break;
+ }
+
+ return 0;
+}
+
+#define JSON_NEW_OBJ(obj, cb, para1, para2)\
+ {\
+ obj = json_object_new_object();\
+ if (obj == NULL)\
+ {\
+ (void)cb(para1);\
+ (void)cb(para2);\
+ return -1;\
+ }\
+ }
+
+#define JSON_NEW_STRING_OBJ(str, obj, cb, para1, para2)\
+ {\
+ obj = json_object_new_string((str));\
+ if (obj == NULL)\
+ {\
+ (void)cb(para1);\
+ (void)cb(para2);\
+ return -1;\
+ }\
+ }
+
+#define JSON_NEW_STRING_OBJ_1(val, obj, cb, para1, para2,para3)\
+ {\
+ obj = json_object_new_string((val));\
+ if (obj == NULL)\
+ {\
+ (void)cb(para1);\
+ (void)cb(para2);\
+ (void)cb(para3);\
+ return -1;\
+ }\
+ }
+
+#define JSON_NEW_INT_OBJ(val, obj, cb, para1, para2)\
+ {\
+ obj = json_object_new_int((val));\
+ if (obj == NULL)\
+ {\
+ (void)cb(para1);\
+ (void)cb(para2);\
+ return -1;\
+ }\
+ }
+
+/*****************************************************************************
+* Prototype : ns_get_alarm_body
+* Description : get body by alarm parameter
+* Input : char *buf
+* int buf_len
+* alarm_result alarm_res
+* Output : None
+* Return Value : int
+*****************************************************************************/
+int
+ns_get_alarm_body (char *buf, int buf_len, alarm_result alarm_res)
+{
+#define ALARM_NAME_LENGTH 100
+#define COMPONENT_NAME "nStack"
+ int retVal;
+ size_t str_len;
+ int alarm_id = alarm_res.alarm_id_get + 27000;
+ struct timeval t_val;
+ struct tm now_time;
+ char *alarm_string = NULL, *alarm_reason_info = NULL, *alarm_desc = NULL;
+ json_object *temp_jso = NULL, *alarm_info = NULL;
+ alarm_info_s_out *alarmpara_out = NULL;
+ int perceivedSeverity_value = 0;
+ char *action_string = NULL;
+ if (buf == NULL || (buf_len < (int) sizeof (alarm_info_s_out)))
+ {
+ NSAM_LOGERR ("input para invalid");
+ return -1;
+ }
+ alarmpara_out = (alarm_info_s_out *) buf;
+
+ /*use sizeof(alarmpara_out->alarmId) instead of devil figure 16 */
+ retVal =
+ SPRINTF_S (alarmpara_out->alarmId, sizeof (alarmpara_out->alarmId), "%d",
+ alarm_id);
+ if (-1 == retVal)
+ {
+ NSAM_LOGERR ("SPRINTF_S failed]ret=%d", retVal);
+ return -1;
+ }
+
+ (void) gettimeofday (&t_val, NULL);
+ time_t t_sec = (time_t) t_val.tv_sec;
+ /*return value check */
+ if (NULL == localtime_r (&t_sec, &now_time))
+ {
+ NSAM_LOGERR ("localtime_r failed]");
+ return -1;
+ }
+
+ /*use sizeof(alarmpara_out->alarmtime) instead of devil figure 32 */
+ retVal =
+ SPRINTF_S (alarmpara_out->alarmtime, sizeof (alarmpara_out->alarmtime),
+ "%4d%02d%02d%02d%02d%02d%06ld", now_time.tm_year + 1900,
+ now_time.tm_mon + 1, now_time.tm_mday, now_time.tm_hour,
+ now_time.tm_min, now_time.tm_sec, (long) t_val.tv_usec);
+ if (-1 == retVal)
+ {
+ NSAM_LOGERR ("SPRINTF_S failed]ret=%d", retVal);
+ return -1;
+ }
+
+ retVal =
+ STRNCPY_S (alarmpara_out->comptentname,
+ sizeof (alarmpara_out->comptentname), COMPONENT_NAME,
+ strlen (COMPONENT_NAME));
+ if (EOK != retVal)
+ {
+ NSAM_LOGERR ("STRNCPY_S failed]ret=%d", retVal);
+ return -1;
+ }
+
+ switch (alarm_res.alarm_reason_get)
+ {
+ case ALARM_REASON_SOCKET:
+ /* alarmName and reason info is incorrect */
+ alarm_reason_info = "socketResource";
+ if (alarm_res.alarm_flag_get == ALARM_PRODUCT)
+ {
+ alarm_string = "networkResourceOverload";
+ alarm_desc = "more than 80 percent used";
+ perceivedSeverity_value = 2;
+ action_string = "alarm";
+ }
+ else
+ {
+ alarm_string = "networkResourceNormal";
+ alarm_desc = "less than 60 percent used";
+ perceivedSeverity_value = 5;
+ action_string = "clear";
+ }
+
+ break;
+ case ALARM_REASON_MSG_BUF:
+ alarm_reason_info = "SendBufResource";
+ if (alarm_res.alarm_flag_get == ALARM_PRODUCT)
+ {
+ alarm_string = "networkResourceOverload";
+ alarm_desc = "more than 80 percent used";
+ perceivedSeverity_value = 2;
+ action_string = "alarm";
+ }
+ else
+ {
+ alarm_string = "networkResourceNormal";
+ alarm_desc = "less than 60 percent used";
+ perceivedSeverity_value = 5;
+ action_string = "clear";
+ }
+
+ break;
+ case ALARM_REASON_NSMAIN:
+ /* process status alarm change from event to alarm/clear */
+ alarm_reason_info = "networkProcStatus";
+ if (alarm_res.alarm_flag_get == ALARM_PRODUCT)
+ {
+ alarm_string = "network-data-down";
+ alarm_desc = "networkProcDown";
+ perceivedSeverity_value = 2;
+ action_string = "alarm";
+ }
+ else
+ {
+ alarm_string = "network-data-up";
+ alarm_desc = "networkProcUp";
+ perceivedSeverity_value = 5;
+ action_string = "clear";
+ }
+
+ break;
+ default:
+ NSAM_LOGERR ("alarm_reason incorrect]ret=%d",
+ alarm_res.alarm_reason_get);
+ return -1;
+ }
+
+ str_len = 0;
+
+ json_object *alarmlist = json_object_new_object ();
+ if (NULL == alarmlist)
+ {
+ NSAM_LOGERR ("alarmlist is NULL");
+ return -1;
+ }
+
+ json_object *alarmItem = json_object_new_object ();
+
+ if (NULL == alarmItem)
+ {
+ NSAM_LOGERR ("alarmItem is NULL");
+ (void) json_object_put (alarmlist);
+ return -1;
+ }
+
+ JSON_NEW_STRING_OBJ ("ICTS_BASE=1", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "neDN", temp_jso);
+ JSON_NEW_STRING_OBJ ("service", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "neType", temp_jso);
+ JSON_NEW_STRING_OBJ ("ICTS_BASE", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "neName", temp_jso);
+ JSON_NEW_STRING_OBJ ("service", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "objectClass", temp_jso);
+ JSON_NEW_STRING_OBJ ("nStack", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "moDN", temp_jso);
+ JSON_NEW_STRING_OBJ ("nStack", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "moName", temp_jso);
+ JSON_NEW_STRING_OBJ ("default", temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "userId", temp_jso);
+
+ JSON_NEW_INT_OBJ (alarm_id, temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "alarmId", temp_jso);
+
+ JSON_NEW_INT_OBJ (10001, temp_jso, json_object_put, alarmlist, alarmItem);
+ json_object_object_add (alarmItem, "groupId", temp_jso);
+
+ JSON_NEW_STRING_OBJ (g_vmid, temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "objectInstance", temp_jso);
+ JSON_NEW_INT_OBJ (8, temp_jso, json_object_put, alarmlist, alarmItem);
+ json_object_object_add (alarmItem, "eventType", temp_jso);
+
+ JSON_NEW_STRING_OBJ (alarm_string, temp_jso, json_object_put, alarmlist,
+ alarmItem);
+ json_object_object_add (alarmItem, "alarmName", temp_jso);
+
+ JSON_NEW_INT_OBJ (perceivedSeverity_value, temp_jso, json_object_put,
+ alarmlist, alarmItem);
+
+ json_object_object_add (alarmItem, "perceivedSeverity", temp_jso);
+
+ JSON_NEW_OBJ (alarm_info, json_object_put, alarmlist, alarmItem);
+ JSON_NEW_STRING_OBJ_1 (alarm_reason_info, temp_jso, json_object_put,
+ alarmlist, alarmItem, alarm_info);
+ json_object_object_add (alarm_info, "reason", temp_jso);
+ JSON_NEW_STRING_OBJ_1 (alarm_desc, temp_jso, json_object_put, alarmlist,
+ alarmItem, alarm_info);
+ json_object_object_add (alarm_info, "desc", temp_jso);
+ json_object_object_add (alarmItem, "alarmInfo", alarm_info);
+
+ JSON_NEW_STRING_OBJ (action_string, temp_jso, json_object_put, alarmlist,
+ alarmItem);
+
+ json_object_object_add (alarmlist, "data", alarmItem);
+
+ json_object_object_add (alarmlist, "action", temp_jso);
+
+ const char *str = json_object_to_json_string (alarmlist);
+ if (str == NULL)
+ {
+ NSMON_LOGERR ("json_object_to_json_string fail");
+ (void) json_object_put (alarmlist);
+ return -1;
+ }
+
+ str_len = strlen (str);
+
+ if (str_len >= ALARM_PARA_LENGTH_OUTER)
+ {
+ NSAM_LOGERR ("str_len >= ALARM_PARA_LENGTH_OUTER");
+ (void) json_object_put (alarmlist);
+ return -1;
+ }
+
+ retVal =
+ STRNCPY_S (alarmpara_out->alarmcontent, ALARM_PARA_LENGTH_OUTER, str,
+ str_len + 1);
+
+ if (EOK != retVal)
+ {
+ NSAM_LOGERR ("STRNCPY_S failed]ret=%d", retVal);
+ (void) json_object_put (alarmlist);
+ return -1;
+ }
+
+ (void) json_object_put (alarmlist);
+
+ return 0;
+
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : send alarm to thirdparty alarm module, now only log
+********************************************************************/
+int
+ns_send_alarm_to_alarm_module (alarm_result alarm_res)
+{
+ int retVal = -1;
+
+ nsfw_mgr_msg *req_msg =
+ nsfw_mgr_msg_alloc (MGR_MSG_LARGE_ALARM_RSP, NSFW_PROC_ALARM);
+
+ if (NULL == req_msg)
+ {
+ NSAM_LOGERR ("mgr_msg_alloc fail]alarm_id=%d", alarm_res.alarm_id_get);
+ return -1;
+ }
+
+ if (req_msg->msg_len < (NSFW_MGR_MSG_HDR_LEN + sizeof (alarm_info_s_out)))
+ {
+ NSAM_LOGERR ("mgr_msg_alloc length fail]alarm_id=%d",
+ alarm_res.alarm_id_get);
+ nsfw_mgr_msg_free (req_msg);
+ return -1;
+ }
+ /* husky agent receive alarm info using fixed length */
+ req_msg->msg_len = (NSFW_MGR_MSG_HDR_LEN + sizeof (alarm_info_s_out));
+
+ retVal =
+ ns_get_alarm_body ((char *) req_msg->msg_body,
+ NSFW_MGR_LARGE_MSG_BODY_LEN, alarm_res);
+
+ if (-1 == retVal)
+ {
+ NSAM_LOGERR ("ns_get_alarm_body fail]alarm_id=%d",
+ alarm_res.alarm_id_get);
+ nsfw_mgr_msg_free (req_msg);
+ return -1;
+ }
+
+ u8 ret = nsfw_mgr_send_msg (req_msg);
+
+ if (FALSE == ret)
+ {
+ NSAM_LOGERR ("nsfw_mgr_send_msg fail]alarm_id=%d,reason=%d,flag=%d",
+ alarm_res.alarm_id_get, alarm_res.alarm_reason_get,
+ alarm_res.alarm_flag_get);
+ ns_alarm_set_sendFlag (alarm_res.alarm_id_get, ALARM_SEND_FAIL);
+ nsfw_mgr_msg_free (req_msg);
+ return -1;
+ }
+
+ NSAM_LOGINF ("nsfw_mgr_send_msg succ]alarm_id=%d,reason=%d,flag=%d",
+ alarm_res.alarm_id_get, alarm_res.alarm_reason_get,
+ alarm_res.alarm_flag_get);
+ ns_alarm_set_sendFlag (alarm_res.alarm_id_get, ALARM_SEND_SUCC);
+
+ nsfw_mgr_msg_free (req_msg);
+
+ return 0;
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : alarm product common func
+********************************************************************/
+void
+ns_send_alarm_inner (enum_alarm_id alarm_id, void *para, int check_times,
+ int check_state_flag)
+{
+ alarm_data *alarm_value = NULL;
+ alarm_result alarm_id_report;
+ int alarm_idx;
+ int alarm_loop;
+ int temp_alarm_time_laps;
+ int abnormal_alarm_flag = 0, normal_alarm_flag =
+ 0, total_abnormal_alarm_flag = 0;
+ int need_check_flag = check_state_flag;
+ int ret = 0;
+
+ if ((alarm_id <= 0) || (alarm_id >= ALARM_EVENT_MAX)
+ || (0 == g_alarm_data[alarm_id].valid_flag))
+ {
+ NSAM_LOGERR ("alarm_id is invalid or not reg");
+ return;
+ }
+
+ alarm_id_report.alarm_id_get = ALARM_EVENT_MAX;
+
+ alarm_idx = alarm_id;
+
+ alarm_value = &g_alarm_data[alarm_idx];
+
+ for (alarm_loop = 0; alarm_loop < alarm_value->alarm_reason_cnt;
+ alarm_loop++)
+ {
+ abnormal_alarm_flag = 0;
+ if (ALARM_PERIOD_CHECK == alarm_value->_alarm_type)
+ {
+ if (NULL ==
+ alarm_value->_alarm_para.func_alarm_check_period[alarm_loop])
+ {
+ NSAM_LOGERR ("alarm id func_alarm_check is invalid]alarm_id=%d",
+ alarm_id);
+ return;
+ }
+ alarm_id_report =
+ alarm_value->_alarm_para.func_alarm_check_period[alarm_loop] ();
+ }
+ else if (ALARM_SEND_ONCE == alarm_value->_alarm_type)
+ {
+ if (NULL == alarm_value->_alarm_para.func_alarm_check[alarm_loop])
+ {
+ NSAM_LOGERR ("alarm id func_alarm_check is invalid]alarm_id=%d",
+ alarm_id);
+ return;
+ }
+ alarm_id_report =
+ alarm_value->_alarm_para.func_alarm_check[alarm_loop] (para);
+ }
+
+ if ((alarm_id_report.alarm_id_get <= ALARM_EVENT_BASE)
+ || alarm_id_report.alarm_id_get >= ALARM_EVENT_MAX)
+ {
+ NSAM_LOGDBG ("don't satisfy alarm condition");
+ return;
+ }
+
+ alarm_idx = alarm_id_report.alarm_id_get;
+
+ if (ALARM_EVENT_NSTACK_MAIN_ABNORMAL == alarm_idx)
+ {
+ need_check_flag = 0;
+ }
+ /* for send current status alarm, needn't check count also status. */
+ /* for sending current state alarm, needn't check current state */
+ if ((alarm_id_report.alarm_flag_get == ALARM_PRODUCT)
+ && (((alarm_value->alarm_time_laps[alarm_loop] < check_times)
+ && (alarm_value->_alarm_flag != ALARM_PRODUCT))
+ || (need_check_flag == 0)))
+ {
+ if ((0 == check_state_flag)
+ || ++(alarm_value->alarm_time_laps[alarm_loop]) >= check_times)
+ {
+ alarm_value->_alarm_flag = ALARM_PRODUCT;
+ abnormal_alarm_flag = 1;
+ total_abnormal_alarm_flag++;
+ }
+
+ }
+ else if ((alarm_id_report.alarm_flag_get == ALARM_CLEAN)
+ && ((alarm_value->_alarm_flag == ALARM_PRODUCT)
+ || (need_check_flag == 0)))
+ {
+ if ((1 == check_state_flag)
+ && (alarm_value->alarm_time_laps[alarm_loop] > 0))
+ {
+ --alarm_value->alarm_time_laps[alarm_loop];
+ }
+ if ((alarm_value->alarm_time_laps[alarm_loop] <= 0)
+ || (0 == check_state_flag))
+ {
+ normal_alarm_flag++;
+ }
+ }
+
+ temp_alarm_time_laps = alarm_value->alarm_time_laps[alarm_loop];
+
+ /* can't product same alarm multi times */
+ /* only overload alarm can send */
+ if (abnormal_alarm_flag != 1)
+ {
+ NSAM_LOGDBG
+ ("don't satisfy alarm condition]alarm_idx=%d,alarm_time_laps=%d",
+ alarm_idx, temp_alarm_time_laps);
+ continue;
+ }
+
+ ret = ns_send_alarm_to_alarm_module (alarm_id_report);
+
+ if (-1 == ret)
+ {
+ ns_alarm_set_sendFlag (alarm_id, ALARM_SEND_FAIL);
+ }
+ else
+ {
+ ns_alarm_set_sendFlag (alarm_id, ALARM_SEND_SUCC);
+ }
+ /* for alarm current status, only can send one */
+ /* if it have multi-scearo, only can send a overload alarm */
+ if (0 == need_check_flag)
+ {
+ break;
+ }
+
+ }
+
+ if ((total_abnormal_alarm_flag == 0)
+ && (alarm_value->alarm_reason_cnt == normal_alarm_flag))
+ {
+ alarm_value->_alarm_flag = ALARM_CLEAN;
+ ret = ns_send_alarm_to_alarm_module (alarm_id_report);
+ if (-1 == ret)
+ {
+ ns_alarm_set_sendFlag (alarm_id, ALARM_SEND_FAIL);
+ }
+ else
+ {
+ ns_alarm_set_sendFlag (alarm_id, ALARM_SEND_SUCC);
+ }
+ }
+
+ return;
+
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : API, any app want to product alarm,need call this function
+********************************************************************/
+void
+ns_send_alarm (enum_alarm_id alarm_id, void *para)
+{
+ ns_send_alarm_inner (alarm_id, para, 1, 1);
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : period check alarm expire handle function
+********************************************************************/
+int
+ns_alarm_timer_proc_fun (u32 timer_type, void *argv)
+{
+ struct timespec time_left;
+ if (NULL == argv)
+ {
+ NSAM_LOGERR ("abnormal: argv is NULL ");
+ return -1;
+ }
+
+ alarm_data *alarm_value = (alarm_data *) argv;
+
+ if (alarm_value->_alarm_type == ALARM_PERIOD_CHECK)
+ {
+ ns_send_alarm_inner (alarm_value->_alarm_id, NULL,
+ ALARM_PERIOD_CHECK_TIMES, 1);
+ time_left.tv_sec = alarm_value->_alarm_para.period_alarm.time_length;
+ time_left.tv_nsec = 0;
+ nsfw_timer_info *timer_info =
+ nsfw_timer_reg_timer (0, (void *) (u64) alarm_value,
+ ns_alarm_timer_proc_fun, time_left);
+ if (NULL == timer_info)
+ {
+ NSAM_LOGERR ("nsfw_timer_reg_timer fail");
+ return -1;
+ }
+ }
+ NSAM_LOGDBG ("abnormal: alarm is not period ");
+
+ return 0;
+
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : app reg alarm info to alarm module
+********************************************************************/
+int
+ns_reg_alarm (enum_alarm_id alarm_id, alarm_type alarmType,
+ alarm_para * alarmPara)
+{
+ alarm_data *alarm_value = NULL;
+ alarm_reason loop = ALARM_REASON_BEGIN;
+ struct timespec time_left;
+
+ if ((alarm_id <= ALARM_EVENT_BASE) || (alarm_id >= ALARM_EVENT_MAX)
+ || (NULL == alarmPara)
+ || (alarmPara->alarm_reason_count > ALARM_REASON_MAX))
+ {
+ NSAM_LOGERR ("para invalid]alarm_id=%d ", alarm_id);
+ return -1;
+ }
+
+ for (loop = ALARM_REASON_BEGIN; loop < alarmPara->alarm_reason_count;
+ loop++)
+ {
+ if (NULL == alarmPara->func_alarm_check[loop])
+ {
+ NSAM_LOGERR ("para invalid]func_alarm_check=NULL,loop=%d", loop);
+ return -1;
+ }
+ }
+
+ alarm_value = &g_alarm_data[alarm_id];
+ alarm_value->_alarm_type = alarmType;
+ alarm_value->_alarm_para.period_alarm.time_length =
+ alarmPara->period_alarm.time_length;
+ alarm_value->_alarm_id = alarm_id;
+ alarm_value->alarm_reason_cnt = alarmPara->alarm_reason_count;
+ alarm_value->_alarm_flag = ALARM_CLEAN;
+
+ for (loop = ALARM_REASON_BEGIN; loop < alarmPara->alarm_reason_count;
+ loop++)
+ {
+ alarm_value->alarm_time_laps[loop] = alarmPara->alarm_reason_set[loop];
+ alarm_value->_alarm_para.func_alarm_check[loop] =
+ alarmPara->func_alarm_check[loop];
+ alarm_value->_alarm_para.func_alarm_check_period[loop] =
+ alarmPara->func_alarm_check_period[loop];
+ alarm_value->alarm_time_laps[loop] = 0;
+ }
+
+ alarm_value->valid_flag = 1;
+
+ if (ALARM_PERIOD_CHECK == alarmType)
+ {
+ time_left.tv_sec = alarm_value->_alarm_para.period_alarm.time_length;
+ time_left.tv_nsec = 0;
+ nsfw_timer_info *timer_info =
+ nsfw_timer_reg_timer (0, (void *) (u64) alarm_value,
+ ns_alarm_timer_proc_fun, time_left);
+ if (NULL == timer_info)
+ {
+ NSAM_LOGERR ("nsfw_timer_reg_timer fail");
+ }
+ }
+
+ return 0;
+}
+
+/*******************************************************************
+* Copyright 2017, Huawei Tech. Co., Ltd.
+* ALL RIGHTS RESERVED
+*Description : send alarm as per current state
+********************************************************************/
+void
+ns_send_init_alarm (enum_alarm_id alarm_id)
+{
+ if ((alarm_id <= 0) || (alarm_id >= ALARM_EVENT_MAX))
+ {
+ NSAM_LOGDBG ("alarm_id is invalid");
+ return;
+ }
+ ns_send_alarm_inner (alarm_id,
+ (void *) (g_alarm_data[alarm_id]._alarm_flag), 1, 0);
+}
+
+NSFW_MODULE_NAME (NSFW_ALARM_MODULE)
+NSFW_MODULE_PRIORITY (10)
+NSFW_MODULE_DEPENDS (NSTACK_DMM_MODULE)
+NSFW_MODULE_INIT (ns_alarm_module_init)
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif /* __cplusplus */
diff --git a/stacks/lwip_stack/src/alarm/alarm.h b/stacks/lwip_stack/src/alarm/alarm.h
new file mode 100644
index 0000000..4c5f692
--- /dev/null
+++ b/stacks/lwip_stack/src/alarm/alarm.h
@@ -0,0 +1,80 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _ALARM_H_
+#define _ALARM_H_
+
+#include <stdint.h>
+#include "alarm_api.h"
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+/* alarm clean time = 1*3 */
+
+#define ALARM_RESEND_TIMER_LENGTH 60
+#define ALARM_INIT_RESEND_TIMER_LENGTH 40
+
+#define ALARM_SEND_SUCC 1
+#define ALARM_SEND_FAIL 0
+
+#define ALARM_PARA_LENGTH_OUTER 2048
+
+#define ALARM_PERIOD_CHECK_TIMES 3
+
+#define MAX_VMID_LEN 256
+
+#define MIN_VM_ID_LEN 1
+#define MAX_VM_ID_LEN 256
+
+#define INVALID_STR_LEN(_str, _min_len, _maxlen) (NULL == _str || strlen(_str) < _min_len || strlen(_str) > _maxlen)
+
+typedef struct _alarm_data
+{
+ alarm_para _alarm_para;
+ alarm_type _alarm_type;
+ enum_alarm_id _alarm_id;
+ int alarm_time_laps[ALARM_REASON_MAX];
+ alarm_flag _alarm_flag;
+ int alarm_reason_cnt;
+ int valid_flag;
+ int send_succ_flag;
+
+} alarm_data;
+
+typedef struct _alarm_info_s_out
+{
+ char alarmId[16];
+ char comptentname[32];
+ char alarmtime[32];
+ char alarmcontent[ALARM_PARA_LENGTH_OUTER];
+} alarm_info_s_out;
+
+int ns_send_alarm_to_alarm_module (alarm_result alarm_res);
+
+void ns_send_alarm_inner (enum_alarm_id alarm_id, void *para, int check_times,
+ int check_state_flag);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/alarm/alarm_api.h b/stacks/lwip_stack/src/alarm/alarm_api.h
new file mode 100644
index 0000000..8c7aca1
--- /dev/null
+++ b/stacks/lwip_stack/src/alarm/alarm_api.h
@@ -0,0 +1,107 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _ALARM_API_H_
+#define _ALARM_API_H_
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#define NSFW_ALARM_MODULE "nstack_alarm"
+
+/* alarm ID for every event, when need add new alarm, here add a alarm_id define */
+typedef enum _alarm_id
+{
+ ALARM_EVENT_BASE,
+ ALARM_EVENT_NSTACK_RESOURCE_ALARM,
+ ALARM_EVENT_NSTACK_NO_USE,
+ ALARM_EVENT_NSTACK_MAIN_ABNORMAL,
+ ALARM_EVENT_MAX
+} enum_alarm_id;
+
+/* support both type alarm:
+ 1. support other module call func:ns_send_alarm to product alarm;
+ 2. alarm module call function periodly to check whether need product alarm */
+typedef enum _alarm_type
+{
+ ALARM_PERIOD_CHECK,
+ ALARM_SEND_ONCE
+} alarm_type;
+
+typedef enum _alarm_flag
+{
+ ALARM_PRODUCT,
+ ALARM_CLEAN,
+ ALARM_MAX
+} alarm_flag;
+
+typedef enum _alarm_reason
+{
+ ALARM_REASON_BEGIN,
+ ALARM_REASON_SOCKET = 0,
+ ALARM_REASON_MSG_BUF,
+ ALARM_REASON_NSMAIN,
+ ALARM_REASON_MAX
+} alarm_reason;
+
+typedef struct _alarm_result
+{
+ enum_alarm_id alarm_id_get;
+ alarm_reason alarm_reason_get;
+ alarm_flag alarm_flag_get;
+} alarm_result;
+
+/* check whether need product alarm,if return 0, then product alarm */
+typedef alarm_result (*alarm_check_func) (void *para);
+typedef alarm_result (*alarm_check_func_period) (void);
+
+typedef struct _alarm_para
+{
+ union
+ {
+ int time_length;
+ } period_alarm;
+ union
+ {
+ alarm_check_func func_alarm_check[ALARM_REASON_MAX];
+ alarm_check_func_period func_alarm_check_period[ALARM_REASON_MAX];
+ };
+
+ alarm_reason alarm_reason_set[ALARM_REASON_MAX];
+ int alarm_reason_count;
+
+} alarm_para;
+
+/* for any alarm added, firstly call following function to reg */
+int ns_reg_alarm (enum_alarm_id alarm_id, alarm_type _alarm_type,
+ alarm_para * _alarm_para);
+
+void ns_send_init_alarm (enum_alarm_id alarm_id);
+
+/* other module call this func to product alarm, here para is same as alarm_check_func's para */
+void ns_send_alarm (enum_alarm_id alarm_id, void *para);
+int ns_alarm_module_init (void *param);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/include/nsfw_msg.h b/stacks/lwip_stack/src/include/nsfw_msg.h
new file mode 100644
index 0000000..e5254d3
--- /dev/null
+++ b/stacks/lwip_stack/src/include/nsfw_msg.h
@@ -0,0 +1,203 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef MSG_H
+#define MSG_H
+#include "types.h"
+#include "common_mem_api.h"
+#include "nsfw_rti.h"
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#define MAX_MSG_SIZE 512
+COMPAT_PROTECT (MAX_MSG_SIZE, 512);
+#define MAX_MSG_PARAM_SIZE 128
+COMPAT_PROTECT (MAX_MSG_PARAM_SIZE, 128);
+
+#define MSG_ASYN_POST 0
+#define MSG_SYN_POST 1
+
+typedef struct
+{
+ u16 module_type;
+ u16 major_type;
+ u16 minor_type;
+ u16 op_type; /* MSG_SYN_POST or MSG_ASYN_POST */
+ sys_sem_st op_completed;
+ i32 err;
+ PRIMARY_ADDR void *msg_from; /* use it to free msg */
+ i64 receiver;
+ i64 comm_receiver;
+ nsfw_res res_chk;
+ u32 src_pid;
+ u32 recycle_pid; /* use it in recycle */
+ u64 span_pid;
+ i64 extend_member_bit;
+} msg_param;
+
+typedef struct msg_t
+{
+ msg_param param;
+ i8 msg_param_pad[MAX_MSG_PARAM_SIZE - sizeof (msg_param)]; /* sizeof(msg_param) + sizeof(msg_param_pad) = MAX_MSG_PARAM_SIZE */
+ i64 buffer[(MAX_MSG_SIZE - MAX_MSG_PARAM_SIZE) / 8];
+}
+data_com_msg;
+
+#define MAX_MODULE_TYPE 64
+#define MAX_MAJOR_TYPE 256
+#define MAX_MINOR_TYPE 256
+
+struct rti_queue
+{
+ /* corresponding to enum spl_tcpip_msg_type */
+ volatile u64 tcpip_msg_enq[MAX_MAJOR_TYPE];
+ volatile u64 tcpip_msg_enq_fail[MAX_MAJOR_TYPE];
+ u64 tcpip_msg_deq[MAX_MAJOR_TYPE];
+
+ /* corresponding to enum api_msg_type, this is sub-type of SPL_TCPIP_NEW_MSG_API */
+ volatile u64 api_msg_enq[MAX_MINOR_TYPE];
+ volatile u64 api_msg_enq_fail[MAX_MINOR_TYPE];
+ u64 api_msg_deq[MAX_MINOR_TYPE];
+
+ u64 extend_member_bit;
+};
+
+enum MSG_MODULE_TYPE
+{
+ MSG_MODULE_IP,
+ MSG_MODULE_SBR,
+ MSG_MODULE_HAL,
+ MSG_MODULE_SPL,
+ MSG_MODULE_TIMER,
+ MSG_MODULE_MT,
+ MSG_MODULE_DFX,
+ MSG_MODULE_MAX = MAX_MODULE_TYPE
+};
+
+typedef int (*msg_fun) (data_com_msg * m);
+
+/* *INDENT-OFF* */
+extern msg_fun g_msg_module_fun_array[MAX_MODULE_TYPE];
+extern msg_fun g_msg_module_major_fun_array[MAX_MODULE_TYPE][MAX_MAJOR_TYPE];
+extern msg_fun g_msg_module_major_minor_fun_array[MAX_MODULE_TYPE][MAX_MAJOR_TYPE][MAX_MINOR_TYPE];
+extern msg_fun g_msg_unsupport_fun;
+/* *INDENT-ON* */
+
+#define REGIST_MSG_MODULE_FUN(module, fun) \
+ static void regist_ ## module ## _function (void) \
+ __attribute__((__constructor__)); \
+ static void regist_ ## module ## _function (void) \
+ { \
+ g_msg_module_fun_array[module] = fun; \
+ } \
+
+#define REGIST_MSG_MODULE_MAJOR_FUN(module, major, fun) \
+ static void regist_ ## module ## major ## _function (void) \
+ __attribute__((__constructor__)); \
+ static void regist_ ## module ## major ## _function (void) \
+ { \
+ g_msg_module_major_fun_array[module][major] = fun; \
+ } \
+
+#define REGIST_MSG_MODULE_MAJOR_MINOR_FUN(module, major, minor, fun) \
+ static void regist_ ## module ## major ## minor ## _function (void) \
+ __attribute__((__constructor__)); \
+ static void regist_ ## module ## major ## minor ## _function (void) \
+ { \
+ g_msg_module_major_minor_fun_array[module][major][minor] = fun; \
+ } \
+
+#define REGIST_MSG_UNSUPPORT_FUN(fun) \
+ static void regist_msg_unsupport_function (void) \
+ __attribute__((__constructor__)); \
+ static void regist_msg_unsupport_function (void) \
+ { \
+ g_msg_unsupport_fun = fun; \
+ }
+
+static inline int
+unsupport_msg (data_com_msg * m)
+{
+ if (g_msg_unsupport_fun)
+ {
+ return g_msg_unsupport_fun (m);
+ }
+
+ return -1;
+}
+
+/*****************************************************************************
+* Prototype : call_msg_fun
+* Description : call msg fun
+* Input : data_com_msg* m
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline int
+call_msg_fun (data_com_msg * m)
+{
+ u16 module = m->param.module_type;
+ u16 major = m->param.major_type;
+ u16 minor = m->param.minor_type;
+
+ if ((module >= MAX_MODULE_TYPE) || (major >= MAX_MAJOR_TYPE)
+ || (minor >= MAX_MINOR_TYPE))
+ {
+ return unsupport_msg (m);
+ }
+
+ nsfw_rti_stat_macro (NSFW_STAT_PRIMARY_DEQ, m);
+
+ if (g_msg_module_fun_array[module]
+ && (g_msg_module_fun_array[module] (m) != 0))
+ {
+ return -1;
+ }
+
+ if (g_msg_module_major_fun_array[module][major]
+ && (g_msg_module_major_fun_array[module][major] (m) != 0))
+ {
+ return -1;
+ }
+
+ if (g_msg_module_major_minor_fun_array[module][major][minor])
+ {
+ return g_msg_module_major_minor_fun_array[module][major][minor] (m);
+ }
+
+ if (!g_msg_module_fun_array[module]
+ && !g_msg_module_major_fun_array[module][major]
+ && !g_msg_module_major_minor_fun_array[module][major][minor])
+ {
+ return unsupport_msg (m);
+ }
+
+ return 0;
+}
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/include/nsfw_msg_api.h b/stacks/lwip_stack/src/include/nsfw_msg_api.h
new file mode 100644
index 0000000..85dca49
--- /dev/null
+++ b/stacks/lwip_stack/src/include/nsfw_msg_api.h
@@ -0,0 +1,309 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef MSG_API_H
+#define MSG_API_H
+#include "nsfw_msg.h"
+#include "nsfw_mem_api.h"
+#include "nstack_log.h"
+#include "nsfw_rti.h"
+#include "common_mem_api.h"
+#include "nsfw_recycle_api.h"
+#include "common_pal_bitwide_adjust.h"
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#define SET_MSG_ERR(m, error) ((m)->param.err = (error))
+#define GET_MSG_ERR(m) ((m)->param.err)
+
+/* for sync message from sbr we should signal sem */
+#define SYNC_MSG_ACK(m) sys_sem_s_signal(&((m)->param.op_completed))
+
+/* for async message from sbr we should free the message */
+#define ASYNC_MSG_FREE(m) msg_free(m)
+
+#define MSG_ENTRY(_ptr, _type, _member) container_of((void *)_ptr, _type, _member)
+
+#ifndef NSTACK_STATIC_CHECK
+/*****************************************************************************
+* Prototype : msg_malloc
+* Description : malloc msg
+* Input : mring_handle mhandle
+* Output : None
+* Return Value : static inline data_com_msg*
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline data_com_msg *
+msg_malloc (mring_handle mhandle)
+{
+ if (!mhandle)
+ {
+ NSFW_LOGERR ("mhandle is null");
+ return NULL;
+ }
+
+ data_com_msg *m = NULL;
+ if (nsfw_mem_ring_dequeue (mhandle, (void **) &m) != 1)
+ {
+ return NULL;
+ }
+
+ m->param.recycle_pid = get_sys_pid ();
+ res_alloc (&m->param.res_chk);
+ return m;
+}
+
+/*****************************************************************************
+* Prototype : msg_free
+* Description : free msg
+* Input : data_com_msg* m
+* mring_handle mhandle
+* Output : None
+* Return Value : static inline void
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline void
+msg_free (data_com_msg * m)
+{
+ if (!m)
+ {
+ NSFW_LOGERR ("m is NULL");
+ return;
+ }
+
+ mring_handle mhandle = ADDR_SHTOL (m->param.msg_from);
+ if (!mhandle)
+ {
+ return;
+ }
+
+ if (res_free (&m->param.res_chk))
+ {
+ NSFW_LOGERR ("m refree!]m=%p", m);
+ return;
+ }
+
+ m->param.recycle_pid = 0;
+
+ if (nsfw_mem_ring_enqueue (mhandle, (void *) m) != 1)
+ {
+ NSFW_LOGERR ("nsfw_mem_ring_enqueue failed,this can not happen");
+ }
+}
+
+/*****************************************************************************
+* Prototype : msg_post
+* Description : post msg
+* Input : data_com_msg* m
+* mring_handle mhandle
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline int
+msg_post (data_com_msg * m, mring_handle mhandle)
+{
+ int ret;
+ if (!m || !mhandle)
+ {
+ NSFW_LOGERR ("param is not ok]m=%p,mhandle=%p", m, mhandle);
+ return -1;
+ }
+
+ while (1)
+ {
+ ret = nsfw_mem_ring_enqueue (mhandle, (void *) m);
+ switch (ret)
+ {
+ case 1:
+ if (MSG_SYN_POST == m->param.op_type)
+ {
+ sys_arch_sem_s_wait (&m->param.op_completed, 0);
+ }
+
+ return 0;
+ case 0:
+ continue;
+ default:
+ nsfw_rti_stat_macro (NSFW_STAT_PRIMARY_ENQ_FAIL, m);
+ return -1;
+ }
+ }
+}
+
+#define MSG_POST_FAILED 50
+/*****************************************************************************
+* Prototype : msg_post_with_lock_rel
+* Description : post msg to tcpip thread in mgrcom thread
+* Input : data_com_msg* m
+* mring_handle mhandle
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline int
+msg_post_with_lock_rel (data_com_msg * m, mring_handle mhandle)
+{
+ int ret;
+ int try_count = 0;
+ if (!m || !mhandle)
+ {
+ NSFW_LOGERR ("param is not ok]m=%p,mhandle=%p", m, mhandle);
+ return -1;
+ }
+
+ while (1)
+ {
+ ret = nsfw_mem_ring_enqueue (mhandle, (void *) m);
+ switch (ret)
+ {
+ case 1:
+ if (MSG_SYN_POST == m->param.op_type)
+ {
+ sys_arch_sem_s_wait (&m->param.op_completed, 0);
+ }
+
+ return 0;
+ case 0:
+ try_count++;
+ if (try_count > MSG_POST_FAILED)
+ {
+ try_count = 0;
+ nsfw_recycle_rechk_lock ();
+ }
+ sys_sleep_ns (0, 1000000);
+ continue;
+ default:
+ nsfw_rti_stat_macro (NSFW_STAT_PRIMARY_ENQ_FAIL, m);
+ return -1;
+ }
+ }
+}
+
+/*****************************************************************************
+* Prototype : msg_try_post
+* Description : try post msg
+* Input : data_com_msg* m
+* mring_handle mhandle
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline int
+msg_try_post (data_com_msg * m, mring_handle mhandle)
+{
+ if (!m || !mhandle)
+ {
+ NSFW_LOGERR ("param is not ok]m=%p,mhandle=%p", m, mhandle);
+ return -1;
+ }
+
+ int ret = nsfw_mem_ring_enqueue (mhandle, (void *) m);
+ if (1 == ret)
+ {
+ if (MSG_SYN_POST == m->param.op_type)
+ {
+ sys_arch_sem_s_wait (&m->param.op_completed, 0);
+ }
+
+ return 0;
+ }
+
+ return -1;
+}
+
+/*****************************************************************************
+* Prototype : msg_fetch
+* Description : fetch msg
+* Input : mring_handle mhandle
+* data_com_msg** m
+* u32 num
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline int
+msg_fetch (mring_handle mhandle, data_com_msg ** m, u32 num)
+{
+ if (!m || !mhandle)
+ {
+ NSFW_LOGERR ("param is not ok]m=%p,mhandle=%p", m, mhandle);
+ return -1;
+ }
+
+ int ret;
+ while (1)
+ {
+ ret = nsfw_mem_ring_dequeuev (mhandle, (void *) m, num);
+ if (ret > 0)
+ {
+ break;
+ }
+ }
+
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : msg_try_fetch
+* Description : try fetch msg
+* Input : mring_handle mhandle
+* data_com_msg** m
+* u32 num
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*****************************************************************************/
+static inline int
+msg_try_fetch (mring_handle mhandle, data_com_msg ** m, u32 num)
+{
+ if (!m || !mhandle)
+ {
+ NSFW_LOGERR ("param is not ok]m=%p,mhandle=%p", m, mhandle);
+ return -1;
+ }
+
+ return nsfw_mem_ring_dequeuev (mhandle, (void *) m, num);
+}
+
+#else
+data_com_msg *msg_malloc (mring_handle mhandle);
+void msg_free (data_com_msg * m);
+int msg_post (data_com_msg * m, mring_handle mhandle);
+int msg_try_post (data_com_msg * m, mring_handle mhandle);
+int msg_fetch (mring_handle mhandle, data_com_msg ** m, u32 num);
+int msg_try_fetch (mring_handle mhandle, data_com_msg ** m, u32 num);
+int msg_post_with_lock_rel (data_com_msg * m, mring_handle mhandle);
+#endif
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/include/nsfw_mt_config.h b/stacks/lwip_stack/src/include/nsfw_mt_config.h
new file mode 100644
index 0000000..e1a7899
--- /dev/null
+++ b/stacks/lwip_stack/src/include/nsfw_mt_config.h
@@ -0,0 +1,292 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _FW_MT_CONFIG_H
+#define _FW_MT_CONFIG_H
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#define NSFW_CONFIG_MODULE "nsfw_config"
+#define NSTACK_SHARE_CONFIG "nstack_share_config"
+
+#define CFG_PATH "NSTACK_CONFIG_PATH"
+#define CFG_FILE_NAME "nStackConfig.json"
+#define MAX_FILE_NAME_LEN 512
+#define CFG_BUFFER_LEN 2048
+#define MAX_CFG_ITEM 128
+#define CFG_ITEM_LENGTH 64
+
+enum NSTACK_BASE_CFG
+{
+ CFG_BASE_SOCKET_NUM = 0,
+ CFG_BASE_RING_SIZE,
+ CFG_BASE_HAL_PORT_NUM,
+ CFG_BASE_ARP_STALE_TIME,
+ CFG_BASE_ARP_BC_RETRANS_NUM,
+ MAX_BASE_CFG
+};
+COMPAT_PROTECT (MAX_BASE_CFG, 5);
+
+enum NSTACK_CUSTOM_CFG
+{
+ /* mBuf config */
+ CFG_MBUF_DATA_SIZE,
+ CFG_TX_MBUF_NUM,
+ CFG_RX_MBUF_NUM,
+
+ /* memory pool config */
+ CFG_MP_TCPSEG_NUM,
+ CFG_MP_MSG_NUM,
+
+ /* RING config */
+ CFG_HAL_TX_RING_SIZE,
+ CFG_HAL_RX_RING_SIZE,
+ CFG_MBOX_RING_SIZE,
+ CFG_SPL_MAX_RING_SIZE,
+
+ /* PCB config */
+ CFG_TCP_PCB_NUM,
+ CFG_UDP_PCB_NUM,
+ CFG_RAW_PCB_NUM,
+
+ CFG_ARP_QUEUE_NUM,
+
+ MAX_CUSTOM_CFG
+};
+COMPAT_PROTECT (CFG_SPL_MAX_RING_SIZE, 8);
+
+enum EN_CFG_SEG
+{
+ CFG_SEG_BASE = 0,
+ CFG_SEG_LOG,
+ CFG_SEG_PATH,
+ CFG_SEG_PRI,
+ CFG_SEG_MAX
+};
+
+enum EN_CFG_ITEM_TYPE
+{
+ CFG_ITEM_TYPE_INT = 0,
+ CFG_ITEM_TYPE_STRING
+};
+
+enum EN_SEG_BASE_ITEM
+{
+ CFG_SEG_BASE_SOCKET_NUM = 0,
+ CFG_SEG_BASE_ARP_STALE_TIME,
+ CFG_SEG_BASE_ARP_BC_RETRANS_NUM,
+ CFG_SEG_BASE_MAX
+};
+
+enum EN_SEG_THREAD_PRI_ITEM
+{
+ CFG_SEG_THREAD_PRI_POLICY = 0,
+ CFG_SEG_THREAD_PRI_PRI,
+ CFG_SEG_THREAD_PRI_MAX
+};
+
+typedef void (*custom_check_fn) (void *pitem);
+
+// pack size?
+struct cfg_item_info
+{
+ char *name;
+ int type;
+ int min_value;
+ int max_value;
+ int default_value;
+ char *default_str;
+ custom_check_fn custom_check;
+ union
+ {
+ int value;
+ char *pvalue;
+ };
+};
+
+typedef struct _cfg_module_param
+{
+ u32 proc_type;
+ i32 argc;
+ u8 **argv;
+} cfg_module_param;
+
+extern u32 g_custom_cfg_items[MAX_CUSTOM_CFG];
+extern u32 g_base_cfg_items[MAX_BASE_CFG];
+
+#define get_base_cfg(tag) g_base_cfg_items[(tag)]
+#define get_custom_cfg(tag) g_custom_cfg_items[(tag)]
+#define set_custom_cfg_item(tag, value) g_custom_cfg_items[(tag)] = (value)
+
+/* stackx config data definition */
+
+/* app socket num */
+#define DEF_APP_SOCKET_NUM 1024
+
+/* socket num config */
+#define SOCKET_NUM_PER_THREAD 1024 /* socket number per thread */
+COMPAT_PROTECT (SOCKET_NUM_PER_THREAD, 1024);
+
+/*
+ MAX_SOCKET_NUM: max socket fd number one app can use, it should equal the max socket
+ number nstack support(CUR_CFG_SOCKET_NUM)
+*/
+
+#define DEF_SOCKET_NUM 1024 /* default socket number */
+COMPAT_PROTECT (DEF_SOCKET_NUM, 1024);
+#define MIN_SOCKET_NUM 1024 /* min socket number */
+
+#define MAX_SOCKET_NUM 8192 /* default: 8K sockets */
+
+#define CUR_CFG_SOCKET_NUM get_base_cfg(CFG_BASE_SOCKET_NUM) /* max socket numbere nstack support */
+
+#define DEF_ARP_STACLE_TIME 300 /* default arp stale time: second */
+#define MIN_ARP_STACLE_TIME 30 /* min arp stale time: second */
+#define MAX_ARP_STACLE_TIME 1200 /* max arp stale time: second */
+#define ARP_STALE_TIME get_base_cfg(CFG_BASE_ARP_STALE_TIME)
+
+#define DEF_ARP_BC_RETRANS_NUM 5 /* default arp broadcast retransmission times */
+#define MIN_ARP_BC_RETRANS_NUM 1 /* min arp broadcast retransmission times */
+#define MAX_ARP_BC_RETRANS_NUM 20 /* max arp broadcast retransmission times */
+#define ARP_BC_RETRANS_NUM get_base_cfg(CFG_BASE_ARP_BC_RETRANS_NUM)
+
+/* application mumber config */
+#define APP_POOL_NUM 32 /* max application number */
+COMPAT_PROTECT (APP_POOL_NUM, 32);
+
+/* thread number config */
+#define DEF_THREAD_NUM 1 /* default stackx thread number */
+#define MIN_THREAD_NUM 1 /* min thread number */
+#define MAX_THREAD_NUM 1 /* max thread number */
+COMPAT_PROTECT (MAX_THREAD_NUM, 1);
+
+/* hash size */
+#define MAX_TCP_HASH_SIZE 4096
+
+/* hal port number config */
+#define DEF_HAL_PORT_NUM 20 /* port number */
+COMPAT_PROTECT (DEF_HAL_PORT_NUM, 20);
+#define MIN_HAL_PORT_NUM 1
+#define MAX_HAL_PORT_NUM 255
+#define CUR_CFG_HAL_PORT_NUM get_base_cfg(CFG_BASE_HAL_PORT_NUM)
+
+/* vm number config */
+#define MAX_VF_NUM 4 /* max vf number */
+COMPAT_PROTECT (MAX_VF_NUM, 4);
+
+/* base ring size config */
+#define DEF_RING_BASE_SIZE 2048 /* base ring size */
+COMPAT_PROTECT (DEF_RING_BASE_SIZE, 2048);
+#define MIN_RING_BASE_SIZE 1024
+#define MAX_RING_BASE_SIZE 4096
+#define POOL_RING_BASE_SIZE get_base_cfg(CFG_BASE_RING_SIZE)
+
+/* mbuf data size config */
+#define DEF_MBUF_DATA_SIZE 2048 /* mbuf data size */
+COMPAT_PROTECT (DEF_MBUF_DATA_SIZE, 2048);
+#define TX_MBUF_MAX_LEN get_custom_cfg(CFG_MBUF_DATA_SIZE)
+
+/* tx mbuf pool size config */
+#define DEF_TX_MBUF_POOL_SIZE (4*POOL_RING_BASE_SIZE) /* tx mbuf pool size */
+
+#define TX_MBUF_POOL_SIZE get_custom_cfg(CFG_TX_MBUF_NUM)
+
+/* rx mbuf pool size config */
+#define DEF_RX_MBUF_POOL_SIZE (8*POOL_RING_BASE_SIZE) /* rx mbuf pool size */
+
+#define RX_MBUF_POOL_SIZE get_custom_cfg(CFG_RX_MBUF_NUM)
+
+/* hal netif rx/tx ring size config */
+#define DEF_HAL_RX_RING_SIZE 2048 /* hal rx ring size */
+
+#define DEF_HAL_TX_RING_SIZE 2048 /* hal tx ring size */
+#define HAL_RX_RING_SIZE get_custom_cfg(CFG_HAL_RX_RING_SIZE)
+#define HAL_TX_RING_SIZE get_custom_cfg(CFG_HAL_TX_RING_SIZE)
+
+/* stackx recv ring size config */
+#define DEF_SPL_MAX_RING_SIZE 1024
+COMPAT_PROTECT (DEF_SPL_MAX_RING_SIZE, 1024);
+
+#define SPL_MAX_RING_SIZE get_custom_cfg(CFG_SPL_MAX_RING_SIZE) /* ring size config, used in recv ring(per socket) */
+
+/* pcb number config */
+#define DEF_TCP_PCB_NUM 4096 /* tcp pcb number, per thread */
+COMPAT_PROTECT (DEF_TCP_PCB_NUM, 4096);
+#define DEF_UDP_PCB_NUM 512 /* udp pcb number, per thread */
+COMPAT_PROTECT (DEF_UDP_PCB_NUM, 512);
+#define DEF_RAW_PCB_NUM 600 /* raw pcb number, per thread */
+COMPAT_PROTECT (DEF_RAW_PCB_NUM, 600);
+
+#define DEF_ARP_QUEUE_NUM 300
+#define LARGE_ARP_QUEUE_NUM (512*1024)
+
+#define SPL_MEMP_NUM_TCP_PCB get_custom_cfg(CFG_TCP_PCB_NUM)
+
+#define SPL_MEMP_NUM_UDP_PCB get_custom_cfg(CFG_UDP_PCB_NUM)
+#define SPL_MEMP_NUM_RAW_PCB get_custom_cfg(CFG_RAW_PCB_NUM)
+
+#define SPL_MEMP_NUM_ARP_QUEUE get_custom_cfg(CFG_ARP_QUEUE_NUM)
+
+/* tcp seg number config */
+#define DEF_MEMP_NUM_TCP_SEG (2*APP_POOL_NUM*DEF_TX_MBUF_POOL_SIZE)
+#define SPL_MEMP_NUM_TCP_SEG get_custom_cfg(CFG_MP_TCPSEG_NUM) /* tcp segment number, per thread */
+
+/* stackx internal msg number config */
+#define DEF_TX_MSG_POOL_SIZE (DEF_TX_MBUF_POOL_SIZE*APP_POOL_NUM + MAX_VF_NUM*DEF_RX_MBUF_POOL_SIZE + DEF_RING_BASE_SIZE)
+
+#define TX_MSG_POOL_SIZE get_custom_cfg(CFG_MP_MSG_NUM) /* msg number, used by stackx internal, per thread */
+
+/* mbox ring size config */
+#define DEF_MBOX_RING_SIZE (DEF_RING_BASE_SIZE/4)
+COMPAT_PROTECT (DEF_MBOX_RING_SIZE, 512);
+
+#define MBOX_RING_SIZE get_custom_cfg(CFG_MBOX_RING_SIZE) /* mbox ring size config, per thread */
+
+/*some probem if CUSOTM_RECV_RING_SIZE more than 4096*/
+#define CUSOTM_RECV_RING_SIZE 4096
+COMPAT_PROTECT (CUSOTM_RECV_RING_SIZE, 4096);
+
+/*==============================================*
+ * constants or macros define *
+ *----------------------------------------------*/
+#define set_cfg_info(tag, item, min, max, def) { \
+ g_cfg_item_info[tag][item].min_value = (min); \
+ g_cfg_item_info[tag][item].max_value = (max); \
+ g_cfg_item_info[tag][item].default_value = (def);\
+ g_cfg_item_info[tag][item].value = (def);\
+}
+
+#define get_cfg_info(tag, item) g_cfg_item_info[tag][item].value
+
+u32 get_cfg_share_mem_size ();
+
+int get_share_cfg_from_mem (void *mem);
+
+int set_share_cfg_to_mem (void *mem);
+
+void config_module_init (cfg_module_param * param);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/include/nsfw_rti.h b/stacks/lwip_stack/src/include/nsfw_rti.h
new file mode 100644
index 0000000..6b81942
--- /dev/null
+++ b/stacks/lwip_stack/src/include/nsfw_rti.h
@@ -0,0 +1,66 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef RTI_H
+#define RTI_H
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#define nsfw_rti_stat_macro(type, m) if (1 == g_dfx_switch) { nsfw_rti_stat(type, m); }
+
+typedef enum nsfw_rti_stat_type
+{
+ NSFW_STAT_PRIMARY_ENQ,
+ NSFW_STAT_PRIMARY_ENQ_FAIL,
+ NSFW_STAT_PRIMARY_DEQ,
+} nsfw_rti_stat_type_t;
+
+typedef struct nsfw_app_info
+{
+ int nsocket_fd;
+ int sbr_fd;
+
+ int hostpid;
+ int pid;
+ int ppid;
+
+ u64 reserve1;
+ u64 reserve2;
+ u64 reserve3;
+ u64 reserve4;
+
+ u64 extend_member_bit;
+} nsfw_app_info_t;
+
+struct rti_queue;
+struct msg_t;
+
+extern char g_dfx_switch;
+extern struct rti_queue *g_nsfw_rti_primary_stat;
+
+void nsfw_rti_stat (nsfw_rti_stat_type_t statType, const struct msg_t *m);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/io_adpt/CMakeLists.txt b/stacks/lwip_stack/src/io_adpt/CMakeLists.txt
new file mode 100644
index 0000000..ae18116
--- /dev/null
+++ b/stacks/lwip_stack/src/io_adpt/CMakeLists.txt
@@ -0,0 +1,31 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+FILE(GLOB_RECURSE HAL *.c)
+
+if(WITH_HAL_LIB)
+else()
+endif()
+
+
+INCLUDE_DIRECTORIES(
+ ./
+ ${PROJECT_SOURCE_DIR}/src/include/
+ ${PROJECT_SOURCE_DIR}/src/include/generic/
+ /usr/include/dpdk/
+)
+LINK_LIBRARIES(m dl rt dmm_api)
+ADD_LIBRARY(nStackHal STATIC ${HAL})
diff --git a/stacks/lwip_stack/src/io_adpt/dpdk.c b/stacks/lwip_stack/src/io_adpt/dpdk.c
new file mode 100644
index 0000000..63ffde1
--- /dev/null
+++ b/stacks/lwip_stack/src/io_adpt/dpdk.c
@@ -0,0 +1,2315 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <stdint.h>
+#include <sched.h>
+#include <dlfcn.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <net/if.h>
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <pwd.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <fnmatch.h>
+#include <linux/ethtool.h>
+#include <linux/sockios.h>
+
+#include <rte_config.h>
+#include <rte_ethdev.h>
+#include <rte_mbuf.h>
+#include <rte_eth_bond.h>
+#include "nsfw_init.h"
+#include "hal.h"
+#include "nstack_securec.h"
+#include <rte_ethdev_driver.h>
+
+#define DPDK_NON_ROOT_USER_NAME "paas"
+#define DPDK_TOOL_ENV "DPDK_TOOL_DIR"
+#define DPDK_NIC_LIST_FILE "%s/ip_module/.nstack_dpdk_nic_list"
+#define SOCKET_ID_0 0
+
+NSTACK_STATIC struct passwd *dpdk_non_root_user;
+NSTACK_STATIC char dpdk_tool_path[HAL_MAX_PATH_LEN] = { 0 };
+
+/* Default configuration for rx and tx thresholds etc. */
+NSTACK_STATIC const struct rte_eth_rxconf rx_conf_default_igb = {
+ .rx_thresh = {
+ .pthresh = 8,
+ .hthresh = 8,
+ .wthresh = 1, //not bigger than 1
+ },
+};
+
+/*
+ * These default values are optimized for use with the Intel(R) 82576 1 GbE
+ * Controller and the DPDK e1000 PMD. Consider using other values for other
+ * network controllers and/or network drivers.
+ */
+NSTACK_STATIC const struct rte_eth_txconf tx_conf_default_igb = {
+ .tx_thresh = {
+ .pthresh = 8,
+ .hthresh = 1,
+ .wthresh = 16,
+ },
+ .tx_free_thresh = 0, /* Use PMD default values */
+ .tx_rs_thresh = 0, /* Use PMD default values */
+};
+
+/*
+ * RX and TX Prefetch, Host, and Write-back threshold values should be
+ * carefully set for optimal performance. Consult the network
+ * controller's datasheet and supporting DPDK documentation for guidance
+ * on how these parameters should be set.
+ */
+
+/* Default configuration for rx and tx thresholds etc. */
+NSTACK_STATIC const struct rte_eth_rxconf rx_conf_default_ixgbe = {
+ .rx_thresh = {
+ .pthresh = 8,
+ .hthresh = 8,
+ .wthresh = 4,
+ },
+ .rx_free_thresh = 0,
+};
+
+/*
+ * These default values are optimized for use with the Intel(R) 82599 10 GbE
+ * Controller and the DPDK ixgbe PMD. Consider using other values for other
+ * network controllers and/or network drivers.
+ */
+NSTACK_STATIC const struct rte_eth_txconf tx_conf_default_ixgbe = {
+ .tx_thresh = {
+ .pthresh = 36,
+ .hthresh = 0,
+ .wthresh = 0,
+ },
+ .tx_free_thresh = 0, /* Use PMD default values */
+ .tx_rs_thresh = 0, /* Use PMD default values */
+ .txq_flags = 0,
+};
+
+/* the port configuration of normal port */
+NSTACK_STATIC struct rte_eth_conf port_conf_default_normal = {
+ .rxmode = {
+ .mq_mode = ETH_RSS,
+ .max_rx_pkt_len = ETHER_MAX_LEN,
+ .split_hdr_size = 0,
+ .header_split = 0,
+ .hw_ip_checksum = 1,
+ .hw_vlan_filter = 1,
+ .hw_vlan_strip = 1,
+ .jumbo_frame = 0,
+ .hw_strip_crc = 0,
+ },
+ .rx_adv_conf = {
+ .rss_conf = {
+ .rss_key = NULL,
+ .rss_hf = (ETH_RSS_IPV4 | ETH_RSS_NONFRAG_IPV4_TCP | ETH_RSS_NONFRAG_IPV4_UDP), //rss hash key
+ },
+ },
+ .txmode = {
+ .mq_mode = ETH_DCB_NONE,
+ },
+ .intr_conf = {
+ .lsc = 0,
+ },
+};
+
+/* the port configuration of virtio port */
+NSTACK_STATIC struct rte_eth_conf port_conf_default_virtio = {
+ .rxmode = {
+ .mq_mode = ETH_RSS,
+ .max_rx_pkt_len = ETHER_MAX_LEN,
+ .split_hdr_size = 0,
+ .header_split = 0,
+ .hw_ip_checksum = 0, /* Virtio NIC doesn't support HW IP CheckSUM */
+ .hw_vlan_filter = 1,
+ .hw_vlan_strip = 1,
+ .jumbo_frame = 0,
+ .hw_strip_crc = 0,
+ },
+ .rx_adv_conf = {
+ .rss_conf = {
+ .rss_key = NULL,
+ .rss_hf = (ETH_RSS_IPV4 | ETH_RSS_NONFRAG_IPV4_TCP | ETH_RSS_NONFRAG_IPV4_UDP), //rss hash key
+ },
+ },
+ .txmode = {
+ .mq_mode = ETH_DCB_NONE,
+ },
+ .intr_conf = {
+ .lsc = 0,
+ },
+};
+
+/* the port configuration of bond port */
+NSTACK_STATIC struct rte_eth_conf port_conf_default_bond = {
+ .rxmode = {
+ .mq_mode = ETH_MQ_RX_NONE,
+ .max_rx_pkt_len = ETHER_MAX_LEN,
+ .split_hdr_size = 0,
+ .header_split = 0,
+ /**< Header Split disabled */
+ .hw_ip_checksum = 0,
+ /**< IP checksum offload enabled */
+ .hw_vlan_filter = 1,
+ /**< VLAN filtering enabled */
+ .hw_vlan_strip = 1,
+ .jumbo_frame = 0,
+ /**< Jumbo Frame Support disabled */
+ .hw_strip_crc = 0,
+ /**< CRC stripped by hardware */
+ },
+ .rx_adv_conf = {
+ .rss_conf = {
+ .rss_key = NULL,
+ .rss_hf = ETH_RSS_IP,
+ },
+ },
+ .txmode = {
+ .mq_mode = ETH_MQ_TX_NONE,
+ },
+};
+
+/*****************************************************************************
+* Prototype : hal_rte_eth_rx_burst
+* Description : a copy of rte_eth_rx_burst, because this function invokes
+ a global(rte_eth_devices), which cannt be access by dlsym
+ symbols
+* Input : uint8_t port_id
+* uint16_t queue_id
+* struct rte_mbuf **rx_pkts
+* const uint16_t nb_pkts
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+NSTACK_STATIC inline uint16_t
+hal_rte_eth_rx_burst (uint8_t port_id, uint16_t queue_id,
+ struct rte_mbuf **rx_pkts, const uint16_t nb_pkts)
+{
+#ifdef RTE_ETHDEV_RXTX_CALLBACKS
+ struct rte_eth_rxtx_callback *cb;
+#endif
+ int16_t nb_rx;
+
+ struct rte_eth_dev *dev = &rte_eth_devices[port_id];
+
+ if (NULL == dev->rx_pkt_burst)
+ {
+ NSHAL_LOGERR ("dev->rx_pkt_burst is NULL,dev=%p", dev);
+ return 0;
+ }
+
+#ifdef RTE_LIBRTE_ETHDEV_DEBUG
+ RTE_ETH_VALID_PORTID_OR_ERR_RET (port_id, 0);
+ RTE_FUNC_PTR_OR_ERR_RET (*dev->rx_pkt_burst, 0);
+
+ if (queue_id >= dev->data->nb_rx_queues)
+ {
+ RTE_PMD_DEBUG_TRACE ("Invalid RX queue_id=%d\n", queue_id);
+ return 0;
+ }
+#endif
+ nb_rx = (*dev->rx_pkt_burst) (dev->data->rx_queues[queue_id],
+ rx_pkts, nb_pkts);
+
+#ifdef RTE_ETHDEV_RXTX_CALLBACKS
+ cb = dev->post_rx_burst_cbs[queue_id];
+
+ if (unlikely (cb != NULL))
+ {
+ do
+ {
+ nb_rx = cb->fn.rx (port_id, queue_id, rx_pkts, nb_rx,
+ nb_pkts, cb->param);
+ cb = cb->next;
+ }
+ while (cb != NULL);
+ }
+#endif
+
+ return (uint16_t) nb_rx;
+}
+
+/*****************************************************************************
+* Prototype : hal_rte_eth_tx_burst
+* Description : a copy of rte_eth_tx_burst, because this function invokes
+
+* Input : uint8_t port_id
+* uint16_t queue_id
+* struct rte_mbuf **tx_pkts
+* uint16_t nb_pkts
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+NSTACK_STATIC inline uint16_t
+hal_rte_eth_tx_burst (uint8_t port_id, uint16_t queue_id,
+ struct rte_mbuf ** tx_pkts, uint16_t nb_pkts)
+{
+#ifdef RTE_ETHDEV_RXTX_CALLBACKS
+ struct rte_eth_rxtx_callback *cb;
+#endif
+
+ struct rte_eth_dev *dev = &rte_eth_devices[port_id];
+
+ if (NULL == dev->tx_pkt_burst)
+ {
+ NSHAL_LOGERR ("dev->tx_pkt_burst is NULL");
+ return 0;
+ }
+
+#ifdef RTE_LIBRTE_ETHDEV_DEBUG
+ RTE_ETH_VALID_PORTID_OR_ERR_RET (port_id, 0);
+ RTE_FUNC_PTR_OR_ERR_RET (*dev->tx_pkt_burst, 0);
+
+ if (queue_id >= dev->data->nb_tx_queues)
+ {
+ RTE_PMD_DEBUG_TRACE ("Invalid TX queue_id=%d\n", queue_id);
+ return 0;
+ }
+#endif
+
+#ifdef RTE_ETHDEV_RXTX_CALLBACKS
+ cb = dev->pre_tx_burst_cbs[queue_id];
+
+ if (unlikely (cb != NULL))
+ {
+ do
+ {
+ nb_pkts = cb->fn.tx (port_id, queue_id, tx_pkts, nb_pkts,
+ cb->param);
+ cb = cb->next;
+ }
+ while (cb != NULL);
+ }
+#endif
+
+ return (*dev->tx_pkt_burst) (dev->data->tx_queues[queue_id], tx_pkts,
+ nb_pkts);
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_hugepage_size
+ Description : get the free hugepage size
+ Input : the dir of the nstack hugepage
+ Output : free hugepage size
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+int
+dpdk_read_hugepage_size (int *freehuge)
+{
+ int fd_huge;
+ int len;
+ char buf[5] = { '\0' };
+ fd_huge =
+ open ("/sys/kernel/mm/hugepages/hugepages-1048576kB/free_hugepages",
+ O_RDONLY);
+ if (fd_huge < 0)
+ {
+ NSHAL_LOGERR ("errno=%d", errno);
+ return -1;
+ }
+
+ len = read (fd_huge, buf, sizeof (buf));
+ if (len < 0)
+ {
+ NSHAL_LOGERR ("errno=%d", errno);
+ close (fd_huge); //fix codeDEX 124547
+ return -1;
+ }
+ *freehuge = buf[0] - '0';
+ NSHAL_LOGINF ("hugepage size=%d", *freehuge);
+ close (fd_huge);
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_clear_hugedir
+ Description : clear the hugepage which is used by dpdk
+ Input : the dir of the nstack hugepage
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_clear_hugedir (const char *hugedir)
+{
+ DIR *dir;
+ struct dirent *dirent_dpdk;
+ int dir_fd, fd, lck_result, lk_result;
+ const char filter[] = "*mapns*"; /* matches hugepage files */
+
+ /* open directory */
+ dir = opendir (hugedir);
+ if (!dir)
+ {
+ NSHAL_LOGERR ("the path %s is not exist, errno = %d", hugedir, errno);
+ goto error;
+ }
+ dir_fd = dirfd (dir);
+
+ dirent_dpdk = readdir (dir);
+ if (!dirent_dpdk)
+ {
+ NSHAL_LOGERR ("the dir %s can not read, errno = %d", hugedir, errno);
+ goto error;
+ }
+
+ while (dirent_dpdk != NULL)
+ {
+ /* skip files that don't match the hugepage pattern */
+ if (fnmatch (filter, dirent_dpdk->d_name, 0) > 0)
+ {
+ NSHAL_LOGWAR ("the file name %s is not match mapns, errno = %d",
+ dirent_dpdk->d_name, errno);
+ dirent_dpdk = readdir (dir);
+ continue;
+ }
+
+ /* try and lock the file */
+ fd = openat (dir_fd, dirent_dpdk->d_name, O_RDONLY);
+
+ /* skip to next file */
+ if (fd == -1)
+ {
+ NSHAL_LOGERR ("the file name %s can not be lock, errno = %d",
+ dirent_dpdk->d_name, errno);
+ dirent_dpdk = readdir (dir);
+ continue;
+ }
+
+ /* non-blocking lock */
+ lck_result = flock (fd, LOCK_EX | LOCK_NB);
+
+ /* if lock succeeds, unlock and remove the file */
+ if (lck_result != -1)
+ {
+ NSHAL_LOGWAR
+ ("the file name %s can be lock and will delete, errno = %d",
+ dirent_dpdk->d_name, errno);
+ lck_result = flock (fd, LOCK_UN);
+ if (-1 == lck_result)
+ NSHAL_LOGERR ("the file name %s unlock fail, errno = %d",
+ dirent_dpdk->d_name, errno);
+ lk_result = unlinkat (dir_fd, dirent_dpdk->d_name, 0);
+ if (-1 == lk_result)
+ NSHAL_LOGERR ("the file name %s is unlinkat fail, errno = %d",
+ dirent_dpdk->d_name, errno);
+ }
+ close (fd);
+ dirent_dpdk = readdir (dir);
+ }
+
+ (void) closedir (dir);
+ return 0;
+
+error:
+ if (dir)
+ (void) closedir (dir);
+
+ return -1;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_init_global
+ Description : DPDK global init
+ Input : int argc
+ char** argv
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_init_global (int argc, char **argv)
+{
+ //int ret;
+ const char hugepath[] = "/mnt/nstackhuge";
+ //int freeHuge = 0;
+ //int retryCount = 10;
+
+ if (-1 == dpdk_clear_hugedir (hugepath))
+ {
+ NSHAL_LOGERR ("clear hugedir fail, try again!");
+ sys_sleep_ns (0, 100000000);
+ (void) dpdk_clear_hugedir (hugepath);
+ }
+ NSHAL_LOGINF ("init global succ");
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_init_env
+ Description : init dpdk run env
+ Input : void
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_init_env (void)
+{
+ int ret;
+ size_t len_size;
+ char *dpdk_env;
+ char *dpdk_path;
+
+ /* Get dpdk_tool_path */
+ dpdk_env = getenv (DPDK_TOOL_ENV);
+ if (NULL == dpdk_env)
+ {
+ NSHAL_LOGERR ("please set enviroment:%s before start this stack"
+ "\nthe value of the %s must be the path of dpdk tools",
+ DPDK_TOOL_ENV, DPDK_TOOL_ENV);
+ return -1;
+ }
+
+ /* modify ugly len_size judgement and strcpy */
+ /* check len_size for malloc */
+ len_size = strlen (dpdk_env);
+ if (0 == len_size || len_size >= HAL_MAX_PATH_LEN)
+ {
+ NSHAL_LOGERR ("fail to dpdk_env strlen(DPDK_TOOL_ENV)");
+ return -1;
+ }
+
+ /* DPDK_TOOL_ENV's value will be use as popen's paramter,we need check's validity */
+ dpdk_path = realpath (dpdk_env, NULL);
+ if (NULL == dpdk_path)
+ {
+ NSHAL_LOGERR ("env:%s value incorrect]value=%s,errno=%d", DPDK_TOOL_ENV,
+ dpdk_env, errno);
+ return -1;
+ }
+
+ len_size = strlen (dpdk_path);
+ if (0 == len_size || len_size >= HAL_MAX_PATH_LEN)
+ {
+ NSHAL_LOGERR ("fail to dpdk_path strlen(DPDK_TOOL_ENV)");
+ return -1;
+ }
+
+ ret = STRCPY_S (dpdk_tool_path, HAL_MAX_PATH_LEN, dpdk_path);
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRCPY_S failed]ret=%d", ret);
+ return -1;
+ }
+
+ if (!hal_is_script_valid (dpdk_tool_path))
+ {
+ NSHAL_LOGERR ("dpdk_tool_path is invalid]dpdk_tool_path=%s",
+ dpdk_tool_path);
+ return -1;
+ }
+
+ /* get non-root user's id */
+ dpdk_non_root_user = getpwnam (DPDK_NON_ROOT_USER_NAME);
+ if (dpdk_non_root_user)
+ {
+ NSHAL_LOGINF ("non-root]name=%s,uid=%u,gid=%u,errno=%d",
+ dpdk_non_root_user->pw_name, dpdk_non_root_user->pw_uid,
+ dpdk_non_root_user->pw_gid, errno);
+ }
+ else
+ {
+ NSHAL_LOGERR ("non-root]cannot find user %s", DPDK_NON_ROOT_USER_NAME);
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_init_local
+ Description : DPDK local init
+ Input : void
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_init_local (void)
+{
+ int ret;
+
+ ret = dpdk_init_env ();
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("dpdk_init_env failed");
+ return -1;
+ }
+
+ NSHAL_LOGINF ("init local succ");
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_set_port
+ Description : check and save the port num
+ Input : netif_inst_t* inst
+ int port
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_set_port (netif_inst_t * inst, uint8_t port)
+{
+ if (port >= rte_eth_dev_count ())
+ {
+ NSHAL_LOGERR ("the number of port=%d is more than rte_eth_dev_count=%d",
+ port, rte_eth_dev_count ());
+ return -1;
+ }
+
+ inst->data.dpdk_if.port_id = port;
+
+ return 0;
+
+}
+
+/*****************************************************************************
+ Prototype : dpdk_set_nic_name
+ Description : check and save nic name
+ Input : netif_inst_t* inst
+ const char* name
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_set_nic_name (netif_inst_t * inst, const char *name)
+{
+ int ret;
+
+ /* sizeof(pointer) always = 8 in 64 bit system */
+ ret =
+ STRCPY_S (inst->data.dpdk_if.nic_name,
+ sizeof (inst->data.dpdk_if.nic_name), name);
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRCPY_S set nic_name failed]ret=%d", ret);
+ return -1;
+ }
+
+ if (!hal_is_script_valid (inst->data.dpdk_if.nic_name))
+ {
+ NSHAL_LOGERR ("nic_name is invalid");
+ return -1;
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_driver_name
+ Description : get and save driver name
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_driver_name (netif_inst_t * inst)
+{
+ int ret_len, ret;
+ char script_cmmd[HAL_SCRIPT_LENGTH];
+ char driver_name[HAL_SCRIPT_LENGTH] = { 0 };
+
+ ret = hal_snprintf (script_cmmd, sizeof (script_cmmd),
+ "readlink -f /sys/class/net/" "%s"
+ "/device/driver| awk -F'/' '{print $6}'",
+ inst->data.dpdk_if.nic_name);
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("hal_snprintf failed");
+ return -1;
+ }
+
+ ret_len =
+ hal_run_script (script_cmmd, driver_name, sizeof (driver_name) - 1);
+
+ if (ret_len > HAL_MAX_DRIVER_NAME_LEN)
+ {
+ ret_len = HAL_MAX_DRIVER_NAME_LEN;
+ }
+
+ if (ret_len <= 0)
+ {
+ NSHAL_LOGERR ("%s does't have a driver", driver_name);
+
+ ret =
+ STRNCPY_S (inst->data.dpdk_if.driver_name,
+ sizeof (inst->data.dpdk_if.driver_name), "NULL",
+ sizeof ("NULL"));
+
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRNCPY_S failed]ret=%d.", ret);
+ return -1;
+ }
+
+ return -1;
+ }
+ else
+ {
+ ret =
+ STRNCPY_S (inst->data.dpdk_if.driver_name,
+ sizeof (inst->data.dpdk_if.driver_name), driver_name,
+ ret_len);
+
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRNCPY_S failed]ret=%d.", ret);
+ return -1;
+ }
+
+ inst->data.dpdk_if.driver_name[(ret_len - 1)] = '\0';
+
+ return 0;
+ }
+}
+
+/*****************************************************************************
+ Prototype : dpdk_set_pci_permission
+ Description : set pci permission
+ Input : char *pci_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_set_pci_permission (char *pci_addr)
+{
+ DIR *dir_desc;
+ char file_path[HAL_SCRIPT_LENGTH] = { 0 }, dir_path[HAL_SCRIPT_LENGTH] =
+ {
+ 0};
+ struct dirent *ent;
+ struct stat statbuf;
+ int ret;
+
+ ret =
+ SNPRINTF_S (dir_path, sizeof (dir_path), sizeof (dir_path) - 1,
+ "/sys/bus/pci/devices/%s", pci_addr);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("SNPRINTF_S fail");
+ return -1;
+ }
+
+ if ((dir_desc = opendir (dir_path)) == NULL)
+ {
+ NSHAL_LOGERR ("opendir fail:errno=%d", errno);
+ return -1;
+ }
+
+ while ((ent = readdir (dir_desc)) != NULL)
+ {
+ if (strstr (ent->d_name, "resource"))
+ {
+ ret =
+ SNPRINTF_S (file_path, sizeof (file_path), sizeof (file_path) - 1,
+ "%s/%s", dir_path, ent->d_name);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("SNPRINTF_S fail");
+ (void) closedir (dir_desc);
+ return -1;
+ }
+
+ if (!lstat (file_path, &statbuf) && !S_ISDIR (statbuf.st_mode))
+ {
+ ret =
+ chown (file_path, dpdk_non_root_user->pw_uid,
+ dpdk_non_root_user->pw_gid);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chown fail]file_path=%s,ret=%d,errno=%d",
+ file_path, ret, errno);
+ (void) closedir (dir_desc);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chown succ]file_path=%s,ret=%d", file_path, ret);
+ ret = chmod (file_path, 0640);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chmod fail]file_path=%s,ret=%d,errno=%d",
+ file_path, ret, errno);
+ (void) closedir (dir_desc);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chmod succ]file_path=%s,ret=%d", file_path, ret);
+ }
+ }
+ }
+
+ (void) closedir (dir_desc);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_pci_addr
+ Description : get and save pci addr
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_pci_addr (netif_inst_t * inst)
+{
+ int ret, pci_len;
+ struct ethtool_drvinfo edata = { 0 };
+ struct ifreq ifr;
+ int fd = -1;
+
+ /* use ioctl to get pci address instead of call dpdk-devbind.py to reduce time cost */
+ ret = MEMSET_S (&ifr, sizeof (ifr), 0, sizeof (ifr));
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("MEMSET_S fail");
+ return -1;
+ }
+ edata.cmd = ETHTOOL_GDRVINFO;
+ ret =
+ STRCPY_S (ifr.ifr_name, sizeof (ifr.ifr_name),
+ inst->data.dpdk_if.nic_name);
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRCPY_S fail");
+ return -1;
+ }
+
+ ifr.ifr_data = (char *) (&edata);
+ if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
+ {
+ NSHAL_LOGERR ("cannot init socket, errno=%d", errno);
+ return -1;
+ }
+ if (ioctl (fd, SIOCETHTOOL, &ifr) < 0)
+ {
+ NSHAL_LOGERR ("ioctl to the device %s err, errno=%d",
+ inst->data.dpdk_if.nic_name, errno);
+ close (fd);
+ return -1;
+ }
+ close (fd);
+
+ pci_len = strlen (edata.bus_info);
+ if (pci_len == 0
+ || pci_len > (int) sizeof (inst->data.dpdk_if.pci_addr) - 1)
+ {
+ NSHAL_LOGERR ("does't have a pci_addr");
+ inst->data.dpdk_if.pci_addr[0] = '\0';
+ return -1;
+ }
+
+ NSHAL_LOGINF ("nic_name=%s,nic_pci_addr=%s", inst->data.dpdk_if.nic_name,
+ edata.bus_info);
+
+ ret =
+ STRNCPY_S (inst->data.dpdk_if.pci_addr,
+ sizeof (inst->data.dpdk_if.pci_addr), edata.bus_info, pci_len);
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRNCPY_S failed]ret=%d.", ret);
+ return -1;
+ }
+
+ if (!hal_is_script_valid (inst->data.dpdk_if.pci_addr))
+ {
+ NSHAL_LOGERR ("pci_addr is invalid]pci_addr=%s",
+ inst->data.dpdk_if.pci_addr);
+ return -1;
+ }
+
+ if (dpdk_non_root_user && getuid ())
+ {
+ ret = dpdk_set_pci_permission (inst->data.dpdk_if.pci_addr);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("dpdk_set_pci_permission fail");
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_mlx_linkup
+ Description : linkup the port for mlx
+ In bonding mode, mlx4 NICs should be set up manually,
+ in order to make bond port up
+ Input : char* name
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_mlx_linkup (char *name)
+{
+ struct ifreq st_ifreq;
+ int sock;
+ int retVal;
+
+ if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
+ {
+ NSHAL_LOGERR ("socket fail]errno=%d", errno);
+ return 2;
+ }
+
+ retVal = STRCPY_S (st_ifreq.ifr_name, sizeof (st_ifreq.ifr_name), name);
+
+ if (EOK != retVal)
+ {
+ NSHAL_LOGERR ("STRCPY_S fail]");
+ close (sock);
+ return 1;
+ }
+
+ if (ioctl (sock, (uint64_t) SIOCGIFFLAGS, &st_ifreq) < 0)
+ {
+ NSHAL_LOGERR ("ioctl SIOCGIFFLAGS fail]errno=%d", errno);
+ close (sock);
+ return 3;
+ }
+
+ st_ifreq.ifr_flags |= IFF_UP;
+ st_ifreq.ifr_flags |= IFF_RUNNING;
+
+ if (ioctl (sock, (uint64_t) SIOCSIFFLAGS, &st_ifreq) < 0)
+ {
+ NSHAL_LOGERR ("ioctl SIOCSIFFLAGS fail]errno=%d", errno);
+ close (sock);
+ return 3;
+ }
+
+ close (sock);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_nonmlx_linkdown
+ Description : linkdown the port for nonmlx
+ Input : char* name
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_nonmlx_linkdown (char *name)
+{
+ int ret, ret_len;
+ char script_cmmd[HAL_SCRIPT_LENGTH];
+ char result_buf[HAL_SCRIPT_LENGTH];
+
+ ret =
+ hal_snprintf (script_cmmd, sizeof (script_cmmd), "sudo ifconfig %s down",
+ name);
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("spl_snprintf failed]");
+ return -1;
+ }
+
+ ret_len = hal_run_script (script_cmmd, result_buf, sizeof (result_buf));
+ NSHAL_LOGINF ("ifconfig]script_cmmd=%s,ret_len=%d", script_cmmd, ret_len);
+ if (0 > ret_len)
+ {
+ NSHAL_LOGERR ("cannot able to ifconfig %s down", name);
+ return -1;
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_uio_by_pci_addr
+ Description : get uio
+ Input : char *pci_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_uio_by_pci_addr (char *pci_addr)
+{
+ int i, ret, ret_len;
+ char script_cmmd[HAL_SCRIPT_LENGTH];
+ char result_buf[HAL_SCRIPT_LENGTH];
+
+ for (i = 0; i < RTE_MAX_ETHPORTS; i++)
+ {
+ ret = hal_snprintf (script_cmmd, sizeof (script_cmmd),
+ "readlink ls /sys/class/uio/uio%d/device | awk -F '/' '{print $4}'",
+ i);
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("hal_snprintf fail]pci=%s,i=%d", pci_addr, i);
+ return -1;
+ }
+
+ ret_len = hal_run_script (script_cmmd, result_buf, sizeof (result_buf));
+ if (0 > ret_len)
+ {
+ NSHAL_LOGERR ("hal_run_script fail]pci=%s,i=%d", pci_addr, i);
+ return -1;
+ }
+ if (strcmp (result_buf, pci_addr) == 0)
+ return i;
+ }
+
+ return -1;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_set_uio_permission
+ Description : set uio permission
+ Input : char *pci_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_set_uio_permission (char *pci_addr)
+{
+ int ret, uio_idx;
+ char file_path[HAL_SCRIPT_LENGTH / 2] = { 0 };
+
+ /* get /dev/uio by pci addr */
+ uio_idx = dpdk_get_uio_by_pci_addr (pci_addr);
+ if (uio_idx < 0)
+ {
+ NSHAL_LOGERR ("dpdk_get_uio_by_pci_addr fail]pci_addr=%s", pci_addr);
+ return -1;
+ }
+
+ NSHAL_LOGINF ("uio_idx]pci=%s,uio%d", pci_addr, uio_idx);
+
+ /* change /dev/uio%u permission */
+ if (SNPRINTF_S
+ (file_path, sizeof (file_path), sizeof (file_path) - 1, "/dev/uio%d",
+ uio_idx) < 0)
+ {
+ NSHAL_LOGERR ("SNPRINTF_S failed]uio%d", uio_idx);
+ return -1;
+ }
+ sys_sleep_ns (0, 500000000);
+ ret =
+ chown (file_path, dpdk_non_root_user->pw_uid, dpdk_non_root_user->pw_gid);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chown fail]file_path=%s,ret=%d,errno=%d", file_path, ret,
+ errno);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chown succ]file_path=%s,ret=%d", file_path, ret);
+
+ ret = chmod (file_path, 0640);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chmod fail]file_path=%s,ret=%d,errno=%d", file_path, ret,
+ errno);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chmod succ]file_path=%s,ret=%d", file_path, ret);
+
+ /* change /sys/class/uio/uio%u/device/config permission */
+ if (SNPRINTF_S
+ (file_path, sizeof (file_path), sizeof (file_path) - 1,
+ "/sys/class/uio/uio%d/device/config", uio_idx) < 0)
+ {
+ NSHAL_LOGERR ("SNPRINTF_S failed]uio%d", uio_idx);
+ return -1;
+ }
+
+ ret =
+ chown (file_path, dpdk_non_root_user->pw_uid, dpdk_non_root_user->pw_gid);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chown fail]file_path=%s,ret=%d,errno=%d", file_path, ret,
+ errno);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chown succ]file_path=%s,ret=%d", file_path, ret);
+
+ ret = chmod (file_path, 0640);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("chmod fail]file_path=%s,ret=%d,errno=%d", file_path, ret,
+ errno);
+ return -1;
+ }
+ NSHAL_LOGWAR ("chmod succ]file_path=%s,ret=%d", file_path, ret);
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_nic_list_file
+ Description : get dpdk bind nic list file
+ Input : void
+ Output : char*
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC char *
+dpdk_get_nic_list_file (void)
+{
+ int ret;
+ static char buffer[HAL_MAX_PATH_LEN]; /* static so auto-zeroed */
+ const char *directory = "/var/run";
+ const char *home_dir = getenv ("HOME");
+
+ if (getuid () != 0 && home_dir != NULL)
+ directory = home_dir;
+
+ ret =
+ SNPRINTF_S (buffer, sizeof (buffer), sizeof (buffer) - 1,
+ DPDK_NIC_LIST_FILE, directory);
+ if (-1 == ret)
+ {
+ NSCOMM_LOGERR ("SNPRINTF_S failed]ret=%d", ret);
+ return NULL;
+ }
+
+ return buffer;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_bind_uio
+ Description : bind uio
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_bind_uio (netif_inst_t * inst)
+{
+ char script_cmmd[HAL_SCRIPT_LENGTH];
+ char result_buf[HAL_SCRIPT_LENGTH];
+ int ret, ret_len;
+
+ result_buf[0] = '\0';
+
+ if (strncmp ("mlx4_co", inst->data.dpdk_if.driver_name, (size_t) 7) == 0)
+ {
+ /*For MLX4: NIC should be set link up before rte_eth_dev_start() is called. */
+ ret = dpdk_mlx_linkup (inst->data.dpdk_if.nic_name);
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("set mlx linkup fail]nic_name=%s,ret=%d",
+ inst->data.dpdk_if.nic_name, ret);
+
+ return -1;
+ }
+ }
+ else
+ {
+ /*For other drivers: NIC should be set link down before bind uio. */
+ ret = dpdk_nonmlx_linkdown (inst->data.dpdk_if.nic_name);
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("dpdk_nonmlx_linkdown fail]nic_name=%s",
+ inst->data.dpdk_if.nic_name);
+ return -1;
+ }
+
+ /* save binded VF list to file /var/run/ip_module/.nstack_dpdk_nic_list */
+ ret = hal_snprintf (script_cmmd, sizeof (script_cmmd),
+ "sudo %s"
+ "/dpdk-devbind.py -s | grep `ethtool -i %s| grep bus-info |awk '{print $2}'` >> %s 2>&1",
+ dpdk_tool_path, inst->data.dpdk_if.nic_name,
+ dpdk_get_nic_list_file ());
+
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("hal_snprintf fail]nic_name=%s",
+ inst->data.dpdk_if.nic_name);
+ return -1;
+ }
+
+ ret_len =
+ hal_run_script (script_cmmd, result_buf, sizeof (result_buf) - 1);
+ NSHAL_LOGINF ("bind]script_cmmd=%s,ret_len=%d", script_cmmd, ret_len);
+ if (0 > ret_len)
+ {
+ NSHAL_LOGERR ("hal_run_script fail]script_cmmd=%s", script_cmmd);
+ return -1;
+ }
+
+ if (strncmp ("virtio", inst->data.dpdk_if.driver_name, (size_t) 6) == 0)
+ {
+ /* For Virtio NIC, should call "./devbind.sh ethX" to bind the VF */
+ ret = hal_snprintf (script_cmmd, sizeof (script_cmmd),
+ "sudo %s"
+ "/dpdk-devbind.py --bind=igb_uio `ethtool -i %s| grep bus-info |awk '{print $2}'`",
+ dpdk_tool_path, inst->data.dpdk_if.nic_name);
+ //"sudo %s" "/devbind.sh " "%s", dpdk_tool_path, inst->data.dpdk_if.nic_name);
+
+ }
+ else
+ {
+ ret = hal_snprintf (script_cmmd, sizeof (script_cmmd),
+ "sudo %s" "/dpdk-devbind.py --bind=igb_uio "
+ "%s", dpdk_tool_path,
+ inst->data.dpdk_if.nic_name);
+ }
+
+ if (-1 == ret)
+ {
+ NSHAL_LOGERR ("hal_snprintf failed");
+ return -1;
+ }
+
+ ret_len =
+ hal_run_script (script_cmmd, result_buf, sizeof (result_buf) - 1);
+ NSHAL_LOGINF ("bind]script_cmmd=%s,retlen=%d", script_cmmd, ret_len);
+ if (0 > ret_len)
+ {
+ NSHAL_LOGERR ("hal_run_script fail]script_cmmd=%s", script_cmmd);
+ return -1;
+ }
+
+ if (dpdk_non_root_user && getuid ())
+ {
+ ret = dpdk_set_uio_permission (inst->data.dpdk_if.pci_addr);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("set_uio_permission fail]nic_name=%s",
+ inst->data.dpdk_if.nic_name);
+ return -1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_probe_pci
+ Description : probe pci
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_probe_pci (netif_inst_t * inst)
+{
+ int ret;
+ uint16_t port_id;
+ struct rte_eth_dev *eth_dev;
+ char *pci_addr = inst->data.dpdk_if.pci_addr;
+
+ ret = rte_eal_iopl_init ();
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("rte_eal_iopl_init fail]pci_addr=%s,ret=%d", pci_addr,
+ ret);
+ return -1;
+ }
+
+ ret = rte_eth_dev_attach (pci_addr, &port_id);
+ if (0 != ret)
+ {
+ NSHAL_LOGWAR
+ ("pci attach to DPDK fail, the pci may have attached, try to get port id]pci_addr=%s,ret=%d",
+ pci_addr, ret);
+
+ eth_dev = rte_eth_dev_allocated (inst->data.dpdk_if.nic_name);
+ if (NULL != eth_dev && NULL != eth_dev->data)
+ {
+ port_id = eth_dev->data->port_id;
+ ret = 0;
+ }
+ }
+
+ if (!ret)
+ {
+ ret = dpdk_set_port (inst, port_id);
+
+ if (0 == ret)
+ {
+ NSHAL_LOGINF ("set port success]pci_addr=%s,port_id=%u", pci_addr,
+ port_id);
+ }
+ else
+ {
+ NSHAL_LOGERR ("set port fail]pci_addr=%s,port_id=%u", pci_addr,
+ port_id);
+ return -1;
+ }
+ }
+ else
+ {
+ NSHAL_LOGERR ("get port fail]pci_addr=%s,ret=%d", pci_addr, ret);
+ return -1;
+ }
+
+ /*[TA33635][2017-04-24][l00408818] Start: support bond mode */
+ ret = rte_eal_devargs_add (RTE_DEVTYPE_WHITELISTED_PCI, pci_addr);
+ if (!ret)
+ {
+ NSHAL_LOGINF ("pci attach to whitelist success]pci_addr=%s", pci_addr);
+ }
+ else
+ {
+ NSHAL_LOGERR ("pci attach to whitelist fail]pci_addr=%s", pci_addr);
+ return -1;
+ }
+ /*[TA33635][2017-04-24][l00408818] End */
+
+ return 0;
+}
+
+/*nic_name->driver_name->pci_addr->get port*/
+/*****************************************************************************
+ Prototype : dpdk_open
+ Description : open the port
+ Input : netif_inst_t* inst
+ const char* name
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_open (netif_inst_t * inst, const char *name)
+{
+ int ret;
+
+ ret = dpdk_set_nic_name (inst, name);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_set_nic_name fail]nic_name=%s, ret=%d", name, ret);
+ return -1;
+ }
+
+ ret = dpdk_get_driver_name (inst);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_get_driver_name fail]nic_name=%s, ret=%d", name,
+ ret);
+ return -1;
+ }
+
+ ret = dpdk_get_pci_addr (inst);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_get_pci_addr fail]nic_name=%s, ret=%d", name, ret);
+ return -1;
+ }
+
+ ret = dpdk_bind_uio (inst);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_bind_uio fail]nic_name=%s, ret=%d", name, ret);
+ return -1;
+ }
+
+ ret = dpdk_probe_pci (inst);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_probe_pci fail]nic_name=%s, ret=%d", name, ret);
+ return -1;
+ }
+
+ NSHAL_LOGINF ("open port succ]port_id=%u, nic_name=%s",
+ inst->data.dpdk_if.port_id, inst->data.dpdk_if.nic_name);
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_close
+ Description : close the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_close (netif_inst_t * inst)
+{
+ int i;
+
+ /* close slave NIC first */
+ for (i = 0; i < inst->data.dpdk_if.slave_num; i++)
+ {
+ rte_eth_dev_close (inst->data.dpdk_if.slave_port[i]);
+ NSHAL_LOGINF ("close slave port succ]port_id=%u, nic_name=%s",
+ inst->data.dpdk_if.slave_port[i],
+ inst->data.dpdk_if.nic_name);
+ }
+
+ rte_eth_dev_close (inst->data.dpdk_if.port_id);
+ NSHAL_LOGINF ("close port succ]port_id=%u, nic_name=%s",
+ inst->data.dpdk_if.port_id, inst->data.dpdk_if.nic_name);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_queue_conf
+ Description : get the port queue configure
+ Input : netif_inst_t* inst
+ struct rte_eth_rxconf** rx_conf
+ struct rte_eth_txconf** tx_conf
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_queue_conf (netif_inst_t * inst,
+ struct rte_eth_rxconf **rx_conf,
+ struct rte_eth_txconf **tx_conf)
+{
+ static struct rte_eth_dev_info slave_dev_info;
+
+ if (strncmp ("igb", inst->data.dpdk_if.driver_name, (size_t) 3) == 0)
+ {
+ *rx_conf = (struct rte_eth_rxconf *) &rx_conf_default_igb;
+ *tx_conf = (struct rte_eth_txconf *) &tx_conf_default_igb;
+ NSHAL_LOGINF ("igb config is enable]port_id=%u",
+ inst->data.dpdk_if.port_id);
+ }
+ else if (strncmp ("ixgbe", inst->data.dpdk_if.driver_name, (size_t) 5) == 0)
+ {
+ *rx_conf = (struct rte_eth_rxconf *) &rx_conf_default_ixgbe;
+ *tx_conf = (struct rte_eth_txconf *) &tx_conf_default_ixgbe;
+ NSHAL_LOGINF ("igxbe config is enable]port_id=%u",
+ inst->data.dpdk_if.port_id);
+ }
+ else if (strncmp ("bond", inst->data.dpdk_if.driver_name, (size_t) 4) == 0)
+ {
+ *rx_conf = NULL;
+ rte_eth_dev_info_get (inst->data.dpdk_if.slave_port[0],
+ &slave_dev_info);
+ *tx_conf = &(slave_dev_info.default_txconf);
+ NSHAL_LOGINF ("bond config is enable]port_id=%u",
+ inst->data.dpdk_if.port_id);
+ }
+ else
+ {
+ *rx_conf = NULL;
+ *tx_conf = NULL;
+ NSHAL_LOGINF ("default config is enable]port_id=%u",
+ inst->data.dpdk_if.port_id);
+ }
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_port_conf
+ Description : get the port configure
+ Input : netif_inst_t* inst
+ struct rte_eth_conf** port_conf
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC void
+dpdk_get_port_conf (netif_inst_t * inst, struct rte_eth_conf **port_conf)
+{
+ if (strncmp ("virtio", inst->data.dpdk_if.driver_name, (size_t) 6) == 0)
+ {
+ *port_conf = &port_conf_default_virtio;
+ }
+ else if (strncmp ("bond", inst->data.dpdk_if.driver_name, (size_t) 4) == 0)
+ {
+ *port_conf = &port_conf_default_bond;
+ }
+ else
+ {
+ *port_conf = &port_conf_default_normal;
+ }
+
+ (*port_conf)->rxmode.hw_vlan_filter = inst->data.dpdk_if.hw_vlan_filter;
+ (*port_conf)->rxmode.hw_vlan_strip = inst->data.dpdk_if.hw_vlan_strip;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_setup_port
+ Description : setup the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_setup_port (netif_inst_t * inst)
+{
+ int ret;
+ uint32_t i;
+ struct rte_eth_conf *port_conf;
+ struct rte_eth_rxconf *rx_conf;
+ struct rte_eth_txconf *tx_conf;
+
+ uint8_t port_id = inst->data.dpdk_if.port_id;
+ struct rte_mempool **mp = inst->data.dpdk_if.rx_pool;
+ uint32_t *rx_ring_size = inst->data.dpdk_if.rx_ring_size;
+ uint32_t *tx_ring_size = inst->data.dpdk_if.tx_ring_size;
+ uint32_t rx_queue_num = inst->data.dpdk_if.rx_queue_num;
+ uint32_t tx_queue_num = inst->data.dpdk_if.tx_queue_num;
+
+ dpdk_get_port_conf (inst, &port_conf);
+
+ ret =
+ rte_eth_dev_configure (port_id, rx_queue_num, tx_queue_num, port_conf);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("rte_eth_dev_configure]port_id=%u,ret=%d", port_id, ret);
+ return ret;
+ }
+
+ if (dpdk_get_queue_conf (inst, &rx_conf, &tx_conf) < 0)
+ {
+ NSHAL_LOGERR ("dpdk_get_queue_conf failed]inst=%p,rx_conf=%p", inst,
+ rx_conf);
+ return -1;
+ }
+ /* fix "FORTIFY.Out-of-Bounds_Read" type codedex issue CID 33436 */
+ if (rx_queue_num > HAL_ETH_MAX_QUEUE_NUM
+ || tx_queue_num > HAL_ETH_MAX_QUEUE_NUM)
+ {
+ NSHAL_LOGERR
+ ("queue num error]rx_queue_num=%u, tx_queue_num=%u, HAL_ETH_MAX_QUEUE_NUM=%d",
+ rx_queue_num, tx_queue_num, HAL_ETH_MAX_QUEUE_NUM);
+
+ return -1;
+ }
+
+ for (i = 0; i < rx_queue_num; i++)
+ {
+ ret =
+ rte_eth_rx_queue_setup (port_id, i, rx_ring_size[i], SOCKET_ID_ANY,
+ rx_conf, mp[i]);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("rx queue setup fail]index=%u,port_id=%u,ret=%d", i,
+ port_id, ret);
+ return ret;
+ }
+ }
+
+ for (i = 0; i < tx_queue_num; i++)
+ {
+ ret =
+ rte_eth_tx_queue_setup (port_id, i, tx_ring_size[i], SOCKET_ID_ANY,
+ tx_conf);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("tx queue setup fail]q=%u,ret=%d", i, ret);
+ return ret;
+ }
+ }
+
+ rte_eth_promiscuous_enable (port_id);
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_start
+ Description : start the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_start (netif_inst_t * inst)
+{
+ int ret;
+ struct ether_addr eth_addr;
+
+ ret = dpdk_setup_port (inst);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("call dpdk_setup_port fail]ret=%d", ret);
+ return ret;
+ }
+
+ ret = rte_eth_dev_start (inst->data.dpdk_if.port_id);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("rte_eth_dev_start fail]ret=%d", ret);
+ return ret;
+ }
+
+ rte_eth_macaddr_get (inst->data.dpdk_if.port_id, &eth_addr);
+ NSHAL_LOGINF ("port_id=%u,nic_name=%s,mac=%02X:%02X:%02X:%02X:%02X:%02X",
+ inst->data.dpdk_if.port_id,
+ inst->data.dpdk_if.nic_name,
+ eth_addr.addr_bytes[0],
+ eth_addr.addr_bytes[1],
+ eth_addr.addr_bytes[2],
+ eth_addr.addr_bytes[3],
+ eth_addr.addr_bytes[4], eth_addr.addr_bytes[5]);
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_stop
+ Description : stop the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_stop (netif_inst_t * inst)
+{
+ int i;
+
+ /* stop slave NIC first */
+ for (i = 0; i < inst->data.dpdk_if.slave_num; i++)
+ {
+ rte_eth_dev_stop (inst->data.dpdk_if.slave_port[i]);
+ NSHAL_LOGINF ("stop slave port succ]port_id=%u, nic_name=%s",
+ inst->data.dpdk_if.slave_port[i],
+ inst->data.dpdk_if.nic_name);
+ }
+ rte_eth_dev_stop (inst->data.dpdk_if.port_id);
+
+ NSHAL_LOGINF ("stop port succ]port_id=%u, nic_name=%s",
+ inst->data.dpdk_if.port_id, inst->data.dpdk_if.nic_name);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_mtu
+ Description : get the port mtu
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC uint32_t
+dpdk_get_mtu (netif_inst_t * inst)
+{
+ uint32_t mtu;
+
+ if (rte_eth_dev_get_mtu (inst->data.dpdk_if.port_id, (uint16_t *) & mtu))
+ {
+ return 0;
+ }
+
+ return mtu;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_macaddr
+ Description : get the port mac addr
+ Input : netif_inst_t* inst
+ void* mac_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_macaddr (netif_inst_t * inst, void *mac_addr)
+{
+ /*bond port */
+ int primary_port = rte_eth_bond_primary_get (inst->data.dpdk_if.port_id);
+ if (0 <= primary_port)
+ {
+ rte_eth_macaddr_get ((uint8_t) primary_port,
+ (struct ether_addr *) mac_addr);
+
+ NSHAL_LOGDBG
+ ("primary_port_id=%u,nic_name=%s,mac=%02X:%02X:%02X:%02X:%02X:%02X",
+ primary_port, inst->data.dpdk_if.nic_name,
+ ((struct ether_addr *) mac_addr)->addr_bytes[0],
+ ((struct ether_addr *) mac_addr)->addr_bytes[1],
+ ((struct ether_addr *) mac_addr)->addr_bytes[2],
+ ((struct ether_addr *) mac_addr)->addr_bytes[3],
+ ((struct ether_addr *) mac_addr)->addr_bytes[4],
+ ((struct ether_addr *) mac_addr)->addr_bytes[5]);
+ }
+ /*normal port */
+ else
+ {
+ rte_eth_macaddr_get (inst->data.dpdk_if.port_id,
+ (struct ether_addr *) mac_addr);
+
+ NSHAL_LOGDBG
+ ("normal_port_id=%u,nic_name=%s,mac=%02X:%02X:%02X:%02X:%02X:%02X",
+ inst->data.dpdk_if.port_id, inst->data.dpdk_if.nic_name,
+ ((struct ether_addr *) mac_addr)->addr_bytes[0],
+ ((struct ether_addr *) mac_addr)->addr_bytes[1],
+ ((struct ether_addr *) mac_addr)->addr_bytes[2],
+ ((struct ether_addr *) mac_addr)->addr_bytes[3],
+ ((struct ether_addr *) mac_addr)->addr_bytes[4],
+ ((struct ether_addr *) mac_addr)->addr_bytes[5]);
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_capa_convert
+ Description : convert format from dpdk to hal
+ Input : const struct rte_eth_dev_info* dev_info
+ hal_netif_capa_t* capa
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC inline void
+dpdk_capa_convert (const struct rte_eth_dev_info *dev_info,
+ hal_netif_capa_t * capa)
+{
+ int retVal =
+ MEMSET_S (capa, sizeof (hal_netif_capa_t), 0, sizeof (hal_netif_capa_t));
+ if (EOK != retVal)
+ {
+ NSHAL_LOGERR ("MEMSET_S fail]retVal=%d", retVal);
+ }
+
+ capa->tx_offload_capa = dev_info->tx_offload_capa;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_get_capability
+ Description : get the port capability
+ Input : netif_inst_t* inst
+ hal_netif_capa_t* capa
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_get_capability (netif_inst_t * inst, hal_netif_capa_t * capa)
+{
+ struct rte_eth_dev_info dev_info;
+
+ rte_eth_dev_info_get (inst->data.dpdk_if.port_id, &dev_info);
+ dpdk_capa_convert (&dev_info, capa);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_recv
+ Description : recv packet from the port
+ Input : netif_inst_t* inst
+ uint16_t queue_id
+ struct common_mem_mbuf** rx_pkts
+ uint16_t nb_pkts
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC uint16_t
+dpdk_recv (netif_inst_t * inst, uint16_t queue_id,
+ struct common_mem_mbuf ** rx_pkts, uint16_t nb_pkts)
+{
+ return hal_rte_eth_rx_burst (inst->data.dpdk_if.port_id, queue_id,
+ (struct rte_mbuf **) rx_pkts, nb_pkts);
+}
+
+/*****************************************************************************
+ Prototype : dpdk_send
+ Description : send packet to the port
+ Input : netif_inst_t* inst
+ uint16_t queue_id
+ struct common_mem_mbuf** tx_pkts
+ uint16_t nb_pkts
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC uint16_t
+dpdk_send (netif_inst_t * inst, uint16_t queue_id,
+ struct common_mem_mbuf **tx_pkts, uint16_t nb_pkts)
+{
+ return hal_rte_eth_tx_burst (inst->data.dpdk_if.port_id, queue_id,
+ (struct rte_mbuf **) tx_pkts, nb_pkts);
+}
+
+/*****************************************************************************
+ Prototype : dpdk_link_status
+ Description : get link status form the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC uint32_t
+dpdk_link_status (netif_inst_t * inst)
+{
+ struct rte_eth_link eth_link;
+
+ /* add log output when failed */
+ int retVal = MEMSET_S (&eth_link, sizeof (struct rte_eth_link), 0,
+ sizeof (struct rte_eth_link));
+ if (EOK != retVal)
+ {
+ NSHAL_LOGERR ("MEMSET_S fail]retVal=%d", retVal);
+ }
+
+ rte_eth_link_get (inst->data.dpdk_if.port_id, &eth_link);
+
+ return eth_link.link_status;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_stats_convert
+ Description : convert format from dpdk to hal
+ Input : const struct rte_eth_stats* rte_stats
+ hal_netif_stats_t* stats
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC inline void
+dpdk_stats_convert (const struct rte_eth_stats *rte_stats,
+ hal_netif_stats_t * stats)
+{
+ int i;
+
+ /* give fail error number when failed */
+ int retVal = MEMSET_S (stats, sizeof (hal_netif_stats_t), 0,
+ sizeof (hal_netif_stats_t));
+ if (EOK != retVal)
+ {
+ NSHAL_LOGERR ("MEMSET_S fail]retVal=%d", retVal);
+ }
+
+ stats->ipackets = rte_stats->ipackets;
+ stats->opackets = rte_stats->opackets;
+ stats->ibytes = rte_stats->ibytes;
+ stats->obytes = rte_stats->obytes;
+ stats->imissed = rte_stats->imissed;
+ stats->ierrors = rte_stats->ierrors;
+ stats->oerrors = rte_stats->oerrors;
+ stats->rx_nombuf = rte_stats->rx_nombuf;
+
+ for (i = 0; i < HAL_ETH_QUEUE_STAT_CNTRS; i++)
+ {
+ stats->q_ipackets[i] = rte_stats->q_ipackets[i];
+ stats->q_opackets[i] = rte_stats->q_opackets[i];
+ stats->q_ibytes[i] = rte_stats->q_ibytes[i];
+ stats->q_obytes[i] = rte_stats->q_obytes[i];
+ stats->q_errors[i] = rte_stats->q_errors[i];
+ }
+}
+
+/*****************************************************************************
+ Prototype : dpdk_stats
+ Description : get stats form the port
+ Input : netif_inst_t* inst
+ hal_netif_stats_t* stats
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_stats (netif_inst_t * inst, hal_netif_stats_t * stats)
+{
+ int ret;
+ struct rte_eth_stats rte_stats;
+
+ ret = rte_eth_stats_get (inst->data.dpdk_if.port_id, &rte_stats);
+ if (ret == 0)
+ {
+ dpdk_stats_convert (&rte_stats, stats);
+ return 0;
+ }
+
+ return -1;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_stats_reset
+ Description : reset stats to the port
+ Input : netif_inst_t* inst
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_stats_reset (netif_inst_t * inst)
+{
+ rte_eth_stats_reset (inst->data.dpdk_if.port_id);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_config
+ Description : config the port queue and ring
+ Input : netif_inst_t* inst
+ hal_netif_config_t* conf
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_config (netif_inst_t * inst, hal_netif_config_t * conf)
+{
+ uint32_t i;
+
+ inst->data.dpdk_if.hw_vlan_filter = conf->bit.hw_vlan_filter;
+ inst->data.dpdk_if.hw_vlan_strip = conf->bit.hw_vlan_strip;
+
+ inst->data.dpdk_if.rx_queue_num = conf->rx.queue_num;
+ /* fix Buffer Overflow type code-dex issue */
+ if (inst->data.dpdk_if.rx_queue_num > HAL_ETH_MAX_QUEUE_NUM)
+ {
+ NSHAL_LOGERR
+ ("rx queue num error]rx_queue_num=%u, HAL_ETH_MAX_QUEUE_NUM=%d",
+ inst->data.dpdk_if.rx_queue_num, HAL_ETH_MAX_QUEUE_NUM);
+
+ return -1;
+ }
+
+ for (i = 0; i < inst->data.dpdk_if.rx_queue_num; i++)
+ {
+ inst->data.dpdk_if.rx_ring_size[i] = conf->rx.ring_size[i];
+ inst->data.dpdk_if.rx_pool[i] =
+ (struct rte_mempool *) conf->rx.ring_pool[i];
+ }
+
+ inst->data.dpdk_if.tx_queue_num = conf->tx.queue_num;
+ /* fix "FORTIFY.Out-of-Bounds_Read--Off-by-One" type codedex issue */
+ if (inst->data.dpdk_if.tx_queue_num > HAL_ETH_MAX_QUEUE_NUM)
+ {
+ NSHAL_LOGERR
+ ("tx queue num error]rx_queue_num=%u, HAL_ETH_MAX_QUEUE_NUM=%d",
+ inst->data.dpdk_if.tx_queue_num, HAL_ETH_MAX_QUEUE_NUM);
+
+ return -1;
+ }
+ for (i = 0; i < inst->data.dpdk_if.tx_queue_num; i++)
+ {
+ inst->data.dpdk_if.tx_ring_size[i] = conf->tx.ring_size[i];
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_bond_config
+ Description : config the port for bond mode
+ Input : netif_inst_t* inst
+ uint8_t slave_num
+ netif_inst_t* slave_inst[]
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_bond_config (netif_inst_t * inst, uint8_t slave_num,
+ netif_inst_t * slave_inst[])
+{
+ int ret;
+ uint32_t i, queue;
+
+ inst->data.dpdk_if.slave_num = slave_num;
+
+ for (i = 0; i < slave_num; i++)
+ {
+ inst->data.dpdk_if.slave_port[i] = slave_inst[i]->data.dpdk_if.port_id;
+
+ if (0 == i)
+ {
+ inst->data.dpdk_if.hw_vlan_filter =
+ slave_inst[i]->data.dpdk_if.hw_vlan_filter;
+ inst->data.dpdk_if.hw_vlan_strip =
+ slave_inst[i]->data.dpdk_if.hw_vlan_strip;
+ inst->data.dpdk_if.rx_queue_num =
+ slave_inst[i]->data.dpdk_if.rx_queue_num;
+ inst->data.dpdk_if.tx_queue_num =
+ slave_inst[i]->data.dpdk_if.tx_queue_num;
+
+ /*will be used in function dpdk_get_queue_conf and dpdk_get_port_conf */
+ ret =
+ STRCPY_S (inst->data.dpdk_if.driver_name,
+ sizeof (inst->data.dpdk_if.driver_name), "bond");
+
+ if (EOK != ret)
+ {
+ NSHAL_LOGERR ("STRCPY_S failed]ret=%d.", ret);
+ return -1;
+ }
+
+ for (queue = 0; queue < HAL_ETH_MAX_QUEUE_NUM; queue++)
+ {
+ inst->data.dpdk_if.rx_pool[queue] =
+ slave_inst[i]->data.dpdk_if.rx_pool[queue];
+ inst->data.dpdk_if.rx_ring_size[queue] =
+ slave_inst[i]->data.dpdk_if.rx_ring_size[queue];
+ inst->data.dpdk_if.tx_ring_size[queue] =
+ slave_inst[i]->data.dpdk_if.tx_ring_size[queue];
+ }
+ }
+ }
+
+ return 0;
+
+}
+
+/*****************************************************************************
+ Prototype : dpdk_bond
+ Description : bond port
+ Input : netif_inst_t* inst
+ const char* bond_name
+ uint8_t slave_num
+ netif_inst_t* slave_inst[]
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_bond (netif_inst_t * inst, const char *bond_name, uint8_t slave_num,
+ netif_inst_t * slave_inst[])
+{
+ int i, ret;
+ int port;
+ struct ether_addr eth_addr;
+
+ /* check if all the slaves' drivers are same, not support different drivers */
+ for (i = 1; i < slave_num; i++)
+ {
+ if (strncmp
+ (slave_inst[0]->data.dpdk_if.driver_name,
+ slave_inst[i]->data.dpdk_if.driver_name,
+ strlen (slave_inst[0]->data.dpdk_if.driver_name)))
+ {
+ NSHAL_LOGERR
+ ("dpdk does not support different types of network card]slave[0]=%s, slave[%i]=%s",
+ slave_inst[0]->data.dpdk_if.driver_name, i,
+ slave_inst[i]->data.dpdk_if.driver_name);
+ return -1;
+ }
+ }
+
+ ret = dpdk_set_nic_name (inst, bond_name);
+
+ if (0 != ret)
+ {
+ NSHAL_LOGERR ("dpdk_set_nic_name fail]ret=%d", ret);
+ return -1;
+ }
+
+ port =
+ rte_eth_bond_create (bond_name, BONDING_MODE_ACTIVE_BACKUP, SOCKET_ID_0);
+ if (port < 0)
+ {
+ NSHAL_LOGERR ("rte_eth_bond_create fail]ret=%i", ret);
+ return -1;
+ }
+
+ ret = dpdk_set_port (inst, (uint8_t) port);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("dpdk_set_port fail]ret=%i", ret);
+ return ret;
+ }
+
+ ret = dpdk_bond_config (inst, slave_num, slave_inst);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("dpdk_bond_config fail]ret=%i", ret);
+ return ret;
+ }
+
+ ret = dpdk_setup_port (inst);
+
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("dpdk_setup_port fail]ret=%i", ret);
+ return ret;
+ }
+
+ for (i = 0; i < slave_num; i++)
+ {
+ NSHAL_LOGINF ("add slave port_id=%u, nic_name=%s",
+ slave_inst[i]->data.dpdk_if.port_id,
+ slave_inst[i]->data.dpdk_if.nic_name);
+
+ if (rte_eth_bond_slave_add
+ ((uint8_t) port, slave_inst[i]->data.dpdk_if.port_id) == -1)
+ {
+ NSHAL_LOGERR ("adding slave (%u) to bond (%u) failed]",
+ slave_inst[i]->data.dpdk_if.port_id, port);
+ return -1;
+ }
+ }
+
+ rte_eth_macaddr_get (slave_inst[0]->data.dpdk_if.port_id, &eth_addr);
+
+ ret = rte_eth_bond_mac_address_set ((uint8_t) port, &eth_addr);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("rte_eth_bond_mac_address_set fail]ret=%i", ret);
+ return ret;
+ }
+
+ ret = rte_eth_dev_start (inst->data.dpdk_if.port_id);
+ if (ret < 0)
+ {
+ NSHAL_LOGERR ("rte_eth_dev_start fail]ret=%i, port_id=%d", ret,
+ inst->data.dpdk_if.port_id);
+ return ret;
+ }
+
+ NSHAL_LOGINF ("port_id=%d,nic_name=%s,mac=%02X:%02X:%02X:%02X:%02X:%02X",
+ port,
+ inst->data.dpdk_if.nic_name,
+ eth_addr.addr_bytes[0],
+ eth_addr.addr_bytes[1],
+ eth_addr.addr_bytes[2],
+ eth_addr.addr_bytes[3],
+ eth_addr.addr_bytes[4], eth_addr.addr_bytes[5]);
+ return 0;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_add_mcastaddr
+ Description : add mcastaddr to the port
+ Input : netif_inst_t* inst
+ void* mc_addr_set
+ void* mc_addr
+ uint32_t nb_mc_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_set_mcastaddr (netif_inst_t * inst, void *mc_addr_set,
+ void *mc_addr, uint32_t nb_mc_addr)
+{
+ uint8_t port = inst->data.dpdk_if.port_id;
+ int iRetVal;
+
+ NSHAL_LOGINF ("mc_addr_set number=%u", nb_mc_addr);
+ iRetVal = rte_eth_dev_set_mc_addr_list (port, mc_addr_set, nb_mc_addr);
+ if (iRetVal != 0)
+ {
+ NSHAL_LOGWAR ("fail to set_mc_addr_list]port=%u,ret=%d", port, iRetVal);
+ }
+
+ return iRetVal;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_add_mac_addr
+ Description : add mcastaddr to the port
+ Input : netif_inst_t* inst
+ void* mc_addr
+ Output : None
+ Return Value : NSTACK_STATIC int
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_add_mac_addr (netif_inst_t * inst, void *mc_addr)
+{
+ uint8_t port = inst->data.dpdk_if.port_id;
+ int iRetVal;
+
+ /* for MLX: set_mc_addr_list() is not callback, so call mac_addr_add() instead */
+ iRetVal = rte_eth_dev_mac_addr_add (port, mc_addr, 0);
+ if (0 != iRetVal)
+ {
+ NSHAL_LOGWAR ("fail to add_mac_addr]port=%u,ret=%d", port, iRetVal);
+ }
+
+ return iRetVal;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_rmv_mac_addr
+ Description : remove mcastaddr to the port
+ Input : netif_inst_t* inst
+ void* mc_addr
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_rmv_mac_addr (netif_inst_t * inst, void *mc_addr)
+{
+ uint8_t port = inst->data.dpdk_if.port_id;
+ int iRetVal;
+
+ /* for MLX: set_mc_addr_list() is not callback, so call mac_addr_remove() instead */
+ iRetVal = rte_eth_dev_mac_addr_remove (port, mc_addr);
+ if (0 != iRetVal)
+ {
+ NSHAL_LOGWAR ("fail to rmv_mac_addr]port=%u,ret=%d", port, iRetVal);
+ }
+
+ return iRetVal;
+}
+
+/*****************************************************************************
+ Prototype : dpdk_allmcast
+ Description : set allmcast mode to the port
+ Input : netif_inst_t* inst
+ uint8_t enable
+ Output : None
+ Return Value : NSTACK_STATIC
+ Calls :
+ Called By :
+
+*****************************************************************************/
+NSTACK_STATIC int
+dpdk_allmcast (netif_inst_t * inst, uint8_t enable)
+{
+ if (enable)
+ {
+ rte_eth_allmulticast_enable (inst->data.dpdk_if.port_id);
+ }
+ else
+ {
+ rte_eth_allmulticast_disable (inst->data.dpdk_if.port_id);
+ }
+
+ return 0;
+}
+
+const netif_ops_t dpdk_netif_ops = {
+ .name = "dpdk",
+ .init_global = dpdk_init_global,
+ .init_local = dpdk_init_local,
+ .open = dpdk_open,
+ .close = dpdk_close,
+ .start = dpdk_start,
+ .stop = dpdk_stop,
+ .bond = dpdk_bond,
+ .mtu = dpdk_get_mtu,
+ .macaddr = dpdk_get_macaddr,
+ .capability = dpdk_get_capability,
+ .recv = dpdk_recv,
+ .send = dpdk_send,
+ .link_status = dpdk_link_status,
+ .stats = dpdk_stats,
+ .stats_reset = dpdk_stats_reset,
+ .config = dpdk_config,
+ .mcastaddr = dpdk_set_mcastaddr,
+ .add_mac = dpdk_add_mac_addr,
+ .rmv_mac = dpdk_rmv_mac_addr,
+ .allmcast = dpdk_allmcast
+};
+
+HAL_IO_REGISTER (dpdk, &dpdk_netif_ops);
diff --git a/stacks/lwip_stack/src/maintain/CMakeLists.txt b/stacks/lwip_stack/src/maintain/CMakeLists.txt
new file mode 100644
index 0000000..05c5117
--- /dev/null
+++ b/stacks/lwip_stack/src/maintain/CMakeLists.txt
@@ -0,0 +1,44 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+if(WITH_HAL_LIB)
+else()
+ SET(PAL_H_DIRECTORIES "/usr/include/dpdk/")
+ SET(PAL_BITWIDE_ADJUST ${PROJECT_SOURCE_DIR}/../../src/framework/common/base/include/common_pal_bitwide_adjust.h)
+ ADD_DEFINITIONS(-include ${PAL_BITWIDE_ADJUST})
+ INCLUDE_DIRECTORIES(
+ ${PAL_H_DIRECTORIES}
+ )
+endif()
+
+FILE(GLOB_RECURSE NSTACKMAINTAIN *.c)
+
+LINK_LIBRARIES(m dl rt dmm_api)
+if(WITH_SECUREC_LIB)
+INCLUDE_DIRECTORIES(
+ ./
+ ${JSON_C_SRC}
+ ${SECUREC_SRC}
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+)
+else()
+INCLUDE_DIRECTORIES(
+ ./
+ ${JSON_C_SRC}
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+)
+endif()
+ADD_LIBRARY(nStackMaintain STATIC ${NSTACKMAINTAIN})
diff --git a/stacks/lwip_stack/src/maintain/fw_mt_config.c b/stacks/lwip_stack/src/maintain/fw_mt_config.c
new file mode 100644
index 0000000..400eaa0
--- /dev/null
+++ b/stacks/lwip_stack/src/maintain/fw_mt_config.c
@@ -0,0 +1,843 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+/*==============================================*
+ * include header files *
+ *----------------------------------------------*/
+
+#include "types.h"
+#include "nsfw_mt_config.h"
+#include <stdlib.h>
+#include <pthread.h>
+#include "nstack_log.h"
+#include "nstack_securec.h"
+#include "json.h"
+#include "nsfw_init.h"
+#include "nsfw_mgr_com_api.h"
+
+/*==============================================*
+ * project-wide global variables *
+ *----------------------------------------------*/
+
+// can be read from config file
+u32 g_base_cfg_items[MAX_BASE_CFG] = { 0 };
+
+// calculated according to base config
+u32 g_custom_cfg_items[MAX_CUSTOM_CFG] = { 0 };
+
+// note: if seg number greater than 16, such buffer should use malloc
+// or it will be exceed 2K
+struct cfg_item_info g_cfg_item_info[CFG_SEG_MAX][MAX_CFG_ITEM];
+
+NSTACK_STATIC int g_cfg_item_count[CFG_SEG_MAX] = { 0 };
+
+NSTACK_STATIC char *g_cfg_seg_name[CFG_SEG_MAX];
+
+/*==============================================*
+ * routines' or functions' implementations *
+ *----------------------------------------------*/
+
+/* nStackCtrl cannot get the env path info, no start by shell script, need get
+ the path info ,and legal check , add a input parameter proc_type*/
+
+NSTACK_STATIC int
+get_ctrl_dir_info (char *current_path, unsigned path_len)
+{
+ char ctrl_dir[MAX_FILE_NAME_LEN] = { 0 };
+ int count = 0;
+ unsigned int dir_len = 0;
+
+ //nStackCtrl cannot get the path from the env, so need get from current pwd.
+ count = readlink ("/proc/self/exe", ctrl_dir, MAX_FILE_NAME_LEN);
+ if ((count < 0) || (count >= MAX_FILE_NAME_LEN))
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "readlink get nStackCtrl path failed, write nothing!");
+ return -1;
+ }
+ ctrl_dir[count] = '\0';
+
+ dir_len = strlen (ctrl_dir);
+ if ((dir_len > strlen ("nStackCtrl")) && (dir_len < MAX_FILE_NAME_LEN))
+ {
+ ctrl_dir[dir_len - strlen ("nStackCtrl")] = '\0';
+ }
+ else
+ {
+ save_pre_init_log (NSLOG_ERR, "path strlen is illegal, write nothing!");
+ return -1;
+ }
+
+ if (NULL == strstr (ctrl_dir, "bin"))
+ {
+ /* Exit before nstack_log_init, use printf */
+ printf
+ ("the nStackServer content change, plz keep same with nStack release, exit!\n");
+#ifdef FOR_NSTACK_UT
+ return -1;
+#else
+ exit (1);
+#endif
+ }
+ if (EOK !=
+ STRNCAT_S (ctrl_dir, sizeof (ctrl_dir), "/../configure",
+ strlen ("/../configure")))
+ {
+ save_pre_init_log (NSLOG_ERR, "STRNCAT_S failed, current_dir = %s",
+ ctrl_dir);
+ return -1;
+ }
+
+ if (-1 == SNPRINTF_S (current_path, path_len, path_len - 1, "%s", ctrl_dir))
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "SNPRINTF_S path name failed, ctrl_dir %s.",
+ ctrl_dir);
+ return -1;
+ }
+
+ return 0;
+
+}
+
+NSTACK_STATIC int
+get_cfg_buf (u32 proc_type, char *cfg_buf, unsigned buf_size)
+{
+ char current_dir[MAX_FILE_NAME_LEN] = { 0 };
+ char cfg_file_name[MAX_FILE_NAME_LEN] = { 0 };
+ char *cfg_resolved_path = NULL;
+ char *cfg_path = NULL;
+ FILE *fp = NULL;
+ int cfg_buf_len = 0;
+
+ cfg_path = getenv (CFG_PATH);
+ if ((NULL == cfg_path) && (NSFW_PROC_CTRL == proc_type))
+ {
+ if (-1 == get_ctrl_dir_info (current_dir, sizeof (current_dir)))
+ {
+ save_pre_init_log (NSLOG_ERR, "get_ctrl_dir_info failed.");
+ return -1;
+ }
+ cfg_path = current_dir;
+ }
+ else if ((NULL == cfg_path) && (NSFW_PROC_CTRL != proc_type))
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "main or master process get nstack config path failed, will use default config!");
+ return -1;
+ }
+
+ if (-1 ==
+ SPRINTF_S (cfg_file_name, sizeof (cfg_file_name), "%s/%s", cfg_path,
+ CFG_FILE_NAME))
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "format config file name failed, path %s, name %s.",
+ cfg_path, CFG_FILE_NAME);
+ return -1;
+ }
+
+ cfg_resolved_path = realpath (cfg_file_name, NULL);
+ if (NULL == cfg_resolved_path)
+ {
+ save_pre_init_log (NSLOG_ERR, "config file path invalid, cfg name %s.",
+ cfg_file_name);
+ return -1;
+ }
+
+ fp = fopen (cfg_resolved_path, "r");
+ if (NULL == fp)
+ {
+ free (cfg_resolved_path);
+ save_pre_init_log (NSLOG_ERR, "config file path invalid, cfg name %s.",
+ cfg_file_name);
+ return -1;
+ }
+
+ free (cfg_resolved_path);
+ // read config file to json buffer
+ cfg_buf_len = fread (cfg_buf, 1, buf_size, fp);
+
+ fclose (fp);
+
+ return cfg_buf_len;
+}
+
+NSTACK_STATIC inline int
+get_value_from_json_obj (struct json_object *obj, struct cfg_item_info *pitem)
+{
+ switch (pitem->type)
+ {
+ case CFG_ITEM_TYPE_INT:
+ pitem->value = json_object_get_int (obj);
+ break;
+ case CFG_ITEM_TYPE_STRING:
+ pitem->pvalue = (char *) json_object_get_string (obj);
+ break;
+ default:
+ // print log here?
+ return -1;
+ }
+ return 0;
+}
+
+NSTACK_STATIC inline void
+get_cfg_item (struct json_object *obj, int seg_index)
+{
+ struct json_object *cfg_seg_obj = NULL;
+ struct json_object *cfg_seg = NULL;
+ struct json_object *cfg_item_obj[MAX_CFG_ITEM] = { 0 };
+ int i = 0;
+ int cfg_num = 0;
+
+ (void) json_object_object_get_ex (obj, g_cfg_seg_name[seg_index],
+ &cfg_seg_obj);
+ if (NULL == cfg_seg_obj)
+ {
+ save_pre_init_log (NSLOG_ERR, "get config segment obj failed, seg:%s.",
+ g_cfg_seg_name[seg_index]);
+ return;
+ }
+
+ cfg_num = json_object_array_length (cfg_seg_obj);
+ if (cfg_num < 1)
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "config segment count invalid, config segment %s, count %d.",
+ g_cfg_seg_name[seg_index], cfg_num);
+ return;
+ }
+
+ // each config segment just has 1 array element
+ cfg_seg = (struct json_object *) json_object_array_get_idx (cfg_seg_obj, 0);
+ if (NULL == cfg_seg)
+ {
+ save_pre_init_log (NSLOG_ERR, "no config item in seg %s.",
+ g_cfg_seg_name[seg_index]);
+ return;
+ }
+
+ for (; i < g_cfg_item_count[seg_index]; i++)
+ {
+ (void) json_object_object_get_ex (cfg_seg,
+ g_cfg_item_info[seg_index][i].name,
+ &cfg_item_obj[i]);
+
+ if (NULL == cfg_item_obj[i])
+ {
+ save_pre_init_log (NSLOG_ERR,
+ "get config item failed, config item %s.",
+ g_cfg_item_info[seg_index][i].name);
+ return;
+ }
+
+ // note: should specify the config item type if not only int item exist
+ if (get_value_from_json_obj
+ (cfg_item_obj[i], &g_cfg_item_info[seg_index][i]) != 0)
+ {
+ return;
+ }
+ }
+
+ return;
+}
+
+NSTACK_STATIC inline void
+parse_cfg (char *cfg_buf)
+{
+ if (NULL == cfg_buf)
+ {
+ return;
+ }
+
+ struct json_object *obj =
+ (struct json_object *) json_tokener_parse (cfg_buf);
+ int i = 0;
+
+ for (; i < CFG_SEG_MAX; i++)
+ {
+ if (0 == g_cfg_item_count[i])
+ {
+ continue;
+ }
+
+ get_cfg_item (obj, i);
+ }
+}
+
+NSTACK_STATIC inline int
+is_valid (int value, int min_value, int max_value)
+{
+ if ((value < min_value) || (value > max_value))
+ {
+ return 0;
+ }
+
+ return 1;
+}
+
+NSTACK_STATIC inline void
+check_cfg_item_int (struct cfg_item_info *pitem)
+{
+ if (!is_valid (pitem->value, pitem->min_value, pitem->max_value))
+ {
+ pitem->value = pitem->default_value;
+ }
+}
+
+NSTACK_STATIC inline void
+check_cfg_item_string (struct cfg_item_info *pitem)
+{
+ if ((NULL == pitem->pvalue) || ((pitem->pvalue) && (0 == pitem->pvalue[0])))
+ {
+ pitem->pvalue = pitem->default_str;
+ }
+}
+
+NSTACK_STATIC inline void
+check_cfg_item (struct cfg_item_info *pitem)
+{
+ switch (pitem->type)
+ {
+ case CFG_ITEM_TYPE_INT:
+ check_cfg_item_int (pitem);
+ if (pitem->custom_check)
+ pitem->custom_check (pitem);
+ break;
+ case CFG_ITEM_TYPE_STRING:
+ check_cfg_item_string (pitem);
+ if (pitem->custom_check)
+ pitem->custom_check (pitem);
+ break;
+ default:
+ break;
+ }
+}
+
+NSTACK_STATIC inline void
+check_cfg ()
+{
+ int i = 0;
+ int j = 0;
+ for (i = 0; i < CFG_SEG_MAX; i++)
+ {
+ for (j = 0; j < g_cfg_item_count[i]; j++)
+ {
+ check_cfg_item (&g_cfg_item_info[i][j]);
+ }
+ }
+}
+
+NSTACK_STATIC inline void
+print_item_info (char *seg_name, struct cfg_item_info *pitem)
+{
+ switch (pitem->type)
+ {
+ case CFG_ITEM_TYPE_INT:
+ save_pre_init_log (NSLOG_INF, "config read seg:%s, name:%s, value:%d.",
+ seg_name, pitem->name, pitem->value);
+ break;
+ case CFG_ITEM_TYPE_STRING:
+ save_pre_init_log (NSLOG_INF, "config read seg:%s, name:%s, pvalue:%s.",
+ seg_name, pitem->name, pitem->pvalue);
+ break;
+ default:
+ break;
+ }
+}
+
+NSTACK_STATIC inline void
+print_config_item_info ()
+{
+ int i = 0;
+ int j = 0;
+ for (; i < CFG_SEG_MAX; i++)
+ {
+ for (j = 0; j < g_cfg_item_count[i]; j++)
+ {
+ print_item_info (g_cfg_seg_name[i], &g_cfg_item_info[i][j]);
+ }
+ }
+}
+
+void
+check_socket_config (void *pitem)
+{
+ struct cfg_item_info *item = (struct cfg_item_info *) pitem;
+ if (item->value > 0 && !(item->value & (item->value - 1)))
+ return;
+ save_pre_init_log (NSLOG_WAR,
+ "warning: config socket_num (%u) is not 2^n, will use the default value:%u",
+ item->value, item->default_value);
+ item->value = item->default_value;
+}
+
+/* thread schedule mode and thread priority should be matched */
+void
+check_thread_config (void *pitem)
+{
+ struct cfg_item_info *pri_cfg = (struct cfg_item_info *) pitem;
+ struct cfg_item_info *policy_cfg =
+ &g_cfg_item_info[CFG_SEG_PRI][CFG_SEG_THREAD_PRI_POLICY];
+
+ int max_pri = sched_get_priority_max (policy_cfg->value);
+ int min_pri = sched_get_priority_min (policy_cfg->value);
+ if ((pri_cfg->value > max_pri) || (pri_cfg->value < min_pri))
+ {
+ save_pre_init_log (NSLOG_INF,
+ "detect invalid thread priority configuration, use default value] policy=%d, pri=%d, def policy=%d, def pri=%d",
+ policy_cfg->value, pri_cfg->value,
+ policy_cfg->default_value, pri_cfg->default_value);
+
+ policy_cfg->value = policy_cfg->default_value;
+ pri_cfg->value = pri_cfg->default_value;
+ }
+}
+
+#define SET_CFG_ITEM(seg, item, field, value) g_cfg_item_info[seg][item].field = (value)
+#define SET_THREAD_CFG_ITEM(item, field, value) SET_CFG_ITEM(CFG_SEG_PRI, item, field, value)
+
+NSTACK_STATIC void
+init_main_def_config_items ()
+{
+ /* base config */
+ g_cfg_seg_name[CFG_SEG_BASE] = "cfg_seg_socket";
+ g_cfg_item_count[CFG_SEG_BASE] = CFG_SEG_BASE_MAX;
+ /* -- socket number */
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_SOCKET_NUM].name = "socket_num";
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_SOCKET_NUM].type =
+ CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_SOCKET_NUM].custom_check =
+ check_socket_config;
+ set_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_SOCKET_NUM, MIN_SOCKET_NUM,
+ MAX_SOCKET_NUM, DEF_SOCKET_NUM);
+ /* -- arp stale time */
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_STALE_TIME].name =
+ "arp_stale_time";
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_STALE_TIME].type =
+ CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_STALE_TIME].custom_check =
+ NULL;
+ set_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_ARP_STALE_TIME,
+ MIN_ARP_STACLE_TIME, MAX_ARP_STACLE_TIME,
+ DEF_ARP_STACLE_TIME);
+ /* -- arp braodcast retransmission times */
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_BC_RETRANS_NUM].name =
+ "arp_bc_retrans_num";
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_BC_RETRANS_NUM].type =
+ CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_BASE][CFG_SEG_BASE_ARP_BC_RETRANS_NUM].custom_check
+ = NULL;
+ set_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_ARP_BC_RETRANS_NUM,
+ MIN_ARP_BC_RETRANS_NUM, MAX_ARP_BC_RETRANS_NUM,
+ DEF_ARP_BC_RETRANS_NUM);
+
+ /* support thread priority configuration */
+ g_cfg_seg_name[CFG_SEG_PRI] = "cfg_seg_thread_pri";
+ g_cfg_item_count[CFG_SEG_PRI] = CFG_SEG_THREAD_PRI_MAX;
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_POLICY, name, "sched_policy");
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_POLICY, type, CFG_ITEM_TYPE_INT);
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_POLICY, custom_check, NULL);
+ set_cfg_info (CFG_SEG_PRI, CFG_SEG_THREAD_PRI_POLICY, 0, 2, 0);
+
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_PRI, name, "thread_pri");
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_PRI, type, CFG_ITEM_TYPE_INT);
+ SET_THREAD_CFG_ITEM (CFG_SEG_THREAD_PRI_PRI, custom_check,
+ check_thread_config);
+ set_cfg_info (CFG_SEG_PRI, CFG_SEG_THREAD_PRI_PRI, 0, 99, 0);
+
+ /* remove unsed operation config set */
+ /* log config */
+ g_cfg_seg_name[CFG_SEG_LOG] = "cfg_seg_log";
+ g_cfg_item_count[CFG_SEG_LOG] = 2;
+ g_cfg_item_info[CFG_SEG_LOG][0].name = "run_log_size";
+ g_cfg_item_info[CFG_SEG_LOG][0].type = CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_LOG][0].custom_check = NULL;
+ g_cfg_item_info[CFG_SEG_LOG][1].name = "run_log_count";
+ g_cfg_item_info[CFG_SEG_LOG][1].type = CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_LOG][1].custom_check = NULL;
+ set_cfg_info (CFG_SEG_LOG, 0, 10, 100, 50);
+ set_cfg_info (CFG_SEG_LOG, 1, 2, 20, 10);
+
+ /* path config */
+ /* set the path string and default str */
+ g_cfg_seg_name[CFG_SEG_PATH] = "cfg_seg_path";
+ g_cfg_item_count[CFG_SEG_PATH] = 1;
+ g_cfg_item_info[CFG_SEG_PATH][0].name = "stackx_log_path";
+ g_cfg_item_info[CFG_SEG_PATH][0].type = CFG_ITEM_TYPE_STRING;
+ g_cfg_item_info[CFG_SEG_PATH][0].default_str = NSTACK_LOG_NAME;
+ g_cfg_item_info[CFG_SEG_PATH][0].custom_check = NULL;
+}
+
+/* master and ctrl both use the function to reduce the redundancy,
+* as the parameter and operation all same.
+*/
+NSTACK_STATIC void
+init_master_def_config_items ()
+{
+ int i = 0;
+ for (; i < CFG_SEG_MAX; i++)
+ {
+ if (i != CFG_SEG_LOG)
+ {
+ g_cfg_item_count[i] = 0;
+ }
+ }
+
+ g_cfg_seg_name[CFG_SEG_LOG] = "cfg_seg_log";
+ g_cfg_item_count[CFG_SEG_LOG] = 2;
+ g_cfg_item_info[CFG_SEG_LOG][0].name = "mon_log_size";
+ g_cfg_item_info[CFG_SEG_LOG][0].type = CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_LOG][0].custom_check = NULL;
+ g_cfg_item_info[CFG_SEG_LOG][1].name = "mon_log_count";
+ g_cfg_item_info[CFG_SEG_LOG][1].type = CFG_ITEM_TYPE_INT;
+ g_cfg_item_info[CFG_SEG_LOG][1].custom_check = NULL;
+
+ set_cfg_info (CFG_SEG_LOG, 0, 2, 20, 10);
+ set_cfg_info (CFG_SEG_LOG, 1, 2, 20, 10);
+
+ g_cfg_seg_name[CFG_SEG_PATH] = "cfg_seg_path";
+ g_cfg_item_count[CFG_SEG_PATH] = 1;
+ g_cfg_item_info[CFG_SEG_PATH][0].name = "master_log_path";
+ g_cfg_item_info[CFG_SEG_PATH][0].type = CFG_ITEM_TYPE_STRING;
+ g_cfg_item_info[CFG_SEG_PATH][0].default_str = NSTACK_LOG_NAME;
+ g_cfg_item_info[CFG_SEG_PATH][0].custom_check = NULL;
+}
+
+NSTACK_STATIC void
+read_init_config (u32 proc_type)
+{
+ int cfg_buf_len = 0;
+ char cfg_json_buf[CFG_BUFFER_LEN] = { 0 };
+
+ cfg_buf_len = get_cfg_buf (proc_type, cfg_json_buf, sizeof (cfg_json_buf));
+ if (cfg_buf_len < 0)
+ {
+ save_pre_init_log (NSLOG_WAR,
+ "warning:file not exist, use default config.");
+ return;
+ }
+ else
+ {
+ /* parse json buffer */
+ parse_cfg (cfg_json_buf);
+ }
+ save_pre_init_log (NSLOG_INF, "read configuration finished.");
+}
+
+/* =========== set config items ========= */
+NSTACK_STATIC inline void
+set_base_config ()
+{
+ g_base_cfg_items[CFG_BASE_RING_SIZE] = DEF_RING_BASE_SIZE;
+ g_base_cfg_items[CFG_BASE_HAL_PORT_NUM] = DEF_HAL_PORT_NUM;
+
+ g_base_cfg_items[CFG_BASE_SOCKET_NUM] =
+ (u32) get_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_SOCKET_NUM);
+ g_base_cfg_items[CFG_BASE_ARP_STALE_TIME] =
+ (u32) get_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_ARP_STALE_TIME);
+ g_base_cfg_items[CFG_BASE_ARP_BC_RETRANS_NUM] =
+ (u32) get_cfg_info (CFG_SEG_BASE, CFG_SEG_BASE_ARP_BC_RETRANS_NUM);
+}
+
+NSTACK_STATIC void
+init_base_config (cfg_module_param * param)
+{
+ /* initial default config */
+ /* omc_ctrl single log file should be 10M */
+ if (param->proc_type == NSFW_PROC_MASTER
+ || param->proc_type == NSFW_PROC_CTRL)
+ {
+ init_master_def_config_items ();
+ }
+ else
+ {
+ init_main_def_config_items ();
+ }
+
+ /* read base config from file */
+ read_init_config (param->proc_type);
+ /* check config and reset value */
+ check_cfg ();
+
+ /* print config info */
+ print_config_item_info ();
+
+ set_base_config ();
+}
+
+NSTACK_STATIC void
+init_stackx_config ()
+{
+ u32 socket_num_per_thread = CUR_CFG_SOCKET_NUM;
+ u32 factor = socket_num_per_thread / SOCKET_NUM_PER_THREAD;
+
+ if (factor == 0 || socket_num_per_thread % SOCKET_NUM_PER_THREAD > 0)
+ {
+ factor += 1;
+ }
+
+ save_pre_init_log (NSLOG_INF, "socket num:%d, factor:%d",
+ CUR_CFG_SOCKET_NUM, factor);
+
+ /* MBUF config */
+ set_custom_cfg_item (CFG_MBUF_DATA_SIZE, DEF_MBUF_DATA_SIZE);
+ set_custom_cfg_item (CFG_TX_MBUF_NUM, DEF_TX_MBUF_POOL_SIZE);
+ set_custom_cfg_item (CFG_RX_MBUF_NUM, DEF_RX_MBUF_POOL_SIZE);
+ set_custom_cfg_item (CFG_MP_TCPSEG_NUM, DEF_MEMP_NUM_TCP_SEG); /* tcp segment number */
+ set_custom_cfg_item (CFG_MP_MSG_NUM, DEF_TX_MSG_POOL_SIZE); /* msg number */
+
+ /* ring config */
+ set_custom_cfg_item (CFG_HAL_RX_RING_SIZE, DEF_HAL_RX_RING_SIZE); /* netif ring size not changed */
+ set_custom_cfg_item (CFG_HAL_TX_RING_SIZE, DEF_HAL_TX_RING_SIZE); /* netif ring size not changed */
+ set_custom_cfg_item (CFG_MBOX_RING_SIZE, DEF_MBOX_RING_SIZE);
+ set_custom_cfg_item (CFG_SPL_MAX_RING_SIZE, DEF_SPL_MAX_RING_SIZE); /* stackx ring size */
+
+ /* pcb config */
+ set_custom_cfg_item (CFG_TCP_PCB_NUM, DEF_TCP_PCB_NUM * factor);
+ set_custom_cfg_item (CFG_UDP_PCB_NUM, DEF_UDP_PCB_NUM * factor);
+ set_custom_cfg_item (CFG_RAW_PCB_NUM, DEF_RAW_PCB_NUM * factor);
+ set_custom_cfg_item (CFG_ARP_QUEUE_NUM,
+ CUR_CFG_SOCKET_NUM >
+ DEF_SOCKET_NUM ? LARGE_ARP_QUEUE_NUM :
+ DEF_ARP_QUEUE_NUM);
+}
+
+void
+print_final_config_para ()
+{
+ save_pre_init_log (NSLOG_INF, "socket_num :%u",
+ get_base_cfg (CFG_BASE_SOCKET_NUM));
+ save_pre_init_log (NSLOG_INF, "base_ring_size :%u",
+ get_base_cfg (CFG_BASE_RING_SIZE));
+ save_pre_init_log (NSLOG_INF, "hal_port_num :%u",
+ get_base_cfg (CFG_BASE_HAL_PORT_NUM));
+ save_pre_init_log (NSLOG_INF, "arp_stale_num :%u",
+ get_base_cfg (CFG_BASE_ARP_STALE_TIME));
+ save_pre_init_log (NSLOG_INF, "arp_bc_retrans_num :%u",
+ get_base_cfg (CFG_BASE_ARP_BC_RETRANS_NUM));
+
+ save_pre_init_log (NSLOG_INF, "mbuf_data_size :%u",
+ get_custom_cfg (CFG_MBUF_DATA_SIZE));
+ save_pre_init_log (NSLOG_INF, "tx_mbuf_num :%u",
+ get_custom_cfg (CFG_TX_MBUF_NUM));
+ save_pre_init_log (NSLOG_INF, "rx_mbuf_num :%u",
+ get_custom_cfg (CFG_RX_MBUF_NUM));
+ save_pre_init_log (NSLOG_INF, "tcp_seg_mp_num :%u",
+ get_custom_cfg (CFG_MP_TCPSEG_NUM));
+ save_pre_init_log (NSLOG_INF, "msg_mp_num :%u",
+ get_custom_cfg (CFG_MP_MSG_NUM));
+ save_pre_init_log (NSLOG_INF, "hal_tx_ring_size :%u",
+ get_custom_cfg (CFG_HAL_TX_RING_SIZE));
+ save_pre_init_log (NSLOG_INF, "hal_rx_ring_size :%u",
+ get_custom_cfg (CFG_HAL_RX_RING_SIZE));
+ save_pre_init_log (NSLOG_INF, "mbox_ring_size :%u",
+ get_custom_cfg (CFG_MBOX_RING_SIZE));
+ save_pre_init_log (NSLOG_INF, "spl_ring_size :%u",
+ get_custom_cfg (CFG_SPL_MAX_RING_SIZE));
+ save_pre_init_log (NSLOG_INF, "tcp_pcb_num :%u",
+ get_custom_cfg (CFG_TCP_PCB_NUM));
+ save_pre_init_log (NSLOG_INF, "udp_pcb_num :%u",
+ get_custom_cfg (CFG_UDP_PCB_NUM));
+ save_pre_init_log (NSLOG_INF, "raw_pcb_num :%u",
+ get_custom_cfg (CFG_RAW_PCB_NUM));
+}
+
+NSTACK_STATIC void
+init_module_cfg_default ()
+{
+ init_stackx_config ();
+
+ print_final_config_para ();
+}
+
+NSTACK_STATIC void
+init_main_log_cfg_para ()
+{
+ struct log_init_para log_para;
+ log_para.run_log_size = g_cfg_item_info[CFG_SEG_LOG][0].value;
+ log_para.run_log_count = g_cfg_item_info[CFG_SEG_LOG][1].value;
+
+ /* log path valid check */
+ if (0 == access (g_cfg_item_info[CFG_SEG_PATH][0].pvalue, W_OK))
+ {
+ log_para.run_log_path = g_cfg_item_info[CFG_SEG_PATH][0].pvalue;
+ }
+ else
+ {
+ log_para.run_log_path = g_cfg_item_info[CFG_SEG_PATH][0].default_str;
+ }
+
+ set_log_init_para (&log_para);
+}
+
+NSTACK_STATIC void
+init_master_log_cfg_para ()
+{
+ struct log_init_para log_para;
+ log_para.mon_log_size = g_cfg_item_info[CFG_SEG_LOG][0].value;
+ log_para.mon_log_count = g_cfg_item_info[CFG_SEG_LOG][1].value;
+
+ /* log path valid check */
+ if (0 == access (g_cfg_item_info[CFG_SEG_PATH][0].pvalue, W_OK))
+ {
+ log_para.mon_log_path = g_cfg_item_info[CFG_SEG_PATH][0].pvalue;
+ }
+ else
+ {
+ log_para.mon_log_path = g_cfg_item_info[CFG_SEG_PATH][0].default_str;
+ }
+
+ set_log_init_para (&log_para);
+}
+
+/* nStackCtrl is the diff process with main, cannot use main process info,
+ need get the configure info respectively */
+/* omc_ctrl single log file should be 10M */
+NSTACK_STATIC void
+init_ctrl_log_cfg_para ()
+{
+ struct log_init_para log_para;
+ log_para.mon_log_size = g_cfg_item_info[CFG_SEG_LOG][0].value;
+ log_para.mon_log_count = g_cfg_item_info[CFG_SEG_LOG][1].value;
+
+ /* log path valid check */
+ if (0 == access (g_cfg_item_info[CFG_SEG_PATH][0].pvalue, W_OK))
+ {
+ log_para.mon_log_path = g_cfg_item_info[CFG_SEG_PATH][0].pvalue;
+ }
+ else
+ {
+ log_para.mon_log_path = g_cfg_item_info[CFG_SEG_PATH][0].default_str;
+ }
+
+ set_log_init_para (&log_para);
+}
+
+/*===========config init for nstack main=============*/
+
+NSTACK_STATIC void
+init_module_cfg_nstackmain ()
+{
+ /* init config data */
+ init_module_cfg_default ();
+
+ /* init log para */
+ init_main_log_cfg_para ();
+}
+
+/*===========config init for nstack master=============*/
+
+NSTACK_STATIC void
+init_module_cfg_nstackmaster ()
+{
+ /* init config data */
+ init_module_cfg_default ();
+
+ init_master_log_cfg_para ();
+}
+
+/*===========config init for nstack ctrl=============*/
+
+/* nStackCtrl is the diff process with main,
+ cannot use main process info, need get the configure info respectively */
+
+NSTACK_STATIC void
+init_module_cfg_nstackctrl ()
+{
+ init_ctrl_log_cfg_para ();
+}
+
+/*===========init config module=============*/
+void
+config_module_init (cfg_module_param * param)
+{
+ save_pre_init_log (NSLOG_INF, "config module init begin] proc type=%d",
+ param->proc_type);
+
+ init_base_config (param);
+
+ switch (param->proc_type)
+ {
+ case NSFW_PROC_MAIN:
+ init_module_cfg_nstackmain ();
+ break;
+
+ case NSFW_PROC_MASTER:
+ init_module_cfg_nstackmaster ();
+ break;
+
+ case NSFW_PROC_CTRL:
+ init_module_cfg_nstackctrl ();
+ break;
+
+ default:
+ init_module_cfg_default ();
+ break;
+ }
+
+ save_pre_init_log (NSLOG_INF, "config module init end.");
+}
+
+u32
+get_cfg_share_mem_size ()
+{
+ return sizeof (g_base_cfg_items) + sizeof (g_custom_cfg_items);
+}
+
+int
+get_share_cfg_from_mem (void *mem)
+{
+ if (EOK !=
+ MEMCPY_S (g_base_cfg_items, sizeof (g_base_cfg_items), mem,
+ sizeof (g_base_cfg_items)))
+ {
+ return -1;
+ }
+
+ char *custom_cfg_mem = (char *) mem + sizeof (g_base_cfg_items);
+
+ if (EOK !=
+ MEMCPY_S (g_custom_cfg_items, sizeof (g_custom_cfg_items),
+ custom_cfg_mem, sizeof (g_custom_cfg_items)))
+ {
+ return -1;
+ }
+
+ return 0;
+}
+
+int
+set_share_cfg_to_mem (void *mem)
+{
+ if (EOK !=
+ MEMCPY_S (mem, sizeof (g_base_cfg_items), g_base_cfg_items,
+ sizeof (g_base_cfg_items)))
+ {
+ return -1;
+ }
+
+ char *custom_cfg_mem = (char *) mem + sizeof (g_base_cfg_items);
+
+ if (EOK !=
+ MEMCPY_S (custom_cfg_mem, sizeof (g_custom_cfg_items),
+ g_custom_cfg_items, sizeof (g_custom_cfg_items)))
+ {
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/stacks/lwip_stack/src/maintain/nsfw_msg.c b/stacks/lwip_stack/src/maintain/nsfw_msg.c
new file mode 100644
index 0000000..338f803
--- /dev/null
+++ b/stacks/lwip_stack/src/maintain/nsfw_msg.c
@@ -0,0 +1,23 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "nsfw_msg.h"
+/* *INDENT-OFF* */
+msg_fun g_msg_module_fun_array[MAX_MODULE_TYPE] = {NULL};
+msg_fun g_msg_module_major_fun_array[MAX_MODULE_TYPE][MAX_MAJOR_TYPE] = {{NULL}};
+msg_fun g_msg_module_major_minor_fun_array[MAX_MODULE_TYPE][MAX_MAJOR_TYPE][MAX_MINOR_TYPE] = {{{NULL}}};
+msg_fun g_msg_unsupport_fun = NULL;
+/* *INDENT-ON* */
diff --git a/stacks/lwip_stack/src/maintain/nsfw_rti.c b/stacks/lwip_stack/src/maintain/nsfw_rti.c
new file mode 100644
index 0000000..e5a1d3c
--- /dev/null
+++ b/stacks/lwip_stack/src/maintain/nsfw_rti.c
@@ -0,0 +1,92 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <stdlib.h>
+#include "types.h"
+#include "nstack_securec.h"
+#include "nsfw_init.h"
+#include "nstack_log.h"
+#include "nsfw_maintain_api.h"
+#include "nsfw_mem_api.h"
+#include "nsfw_rti.h"
+#include "nsfw_msg.h"
+#ifdef HAL_LIB
+#else
+#include "common_pal_bitwide_adjust.h"
+#endif
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C"{
+/* *INDENT-ON* */
+#endif /* __cplusplus */
+
+char g_dfx_switch = 1;
+
+struct rti_queue *g_nsfw_rti_primary_stat = NULL;
+
+void
+nsfw_rti_stat (nsfw_rti_stat_type_t statType, const data_com_msg * m)
+{
+ if (!g_nsfw_rti_primary_stat || !m)
+ {
+ return;
+ }
+
+ struct rti_queue *primary_stat = ADDR_SHTOL (g_nsfw_rti_primary_stat);
+
+ switch (statType)
+ {
+ case NSFW_STAT_PRIMARY_DEQ:
+ if ((m->param.major_type >= MAX_MAJOR_TYPE)
+ || (m->param.minor_type >= MAX_MINOR_TYPE))
+ {
+ return;
+ }
+ /*call_msg_fun() is only called in nStackMain, no reentrance risk, ++ operation is ok */
+ primary_stat->tcpip_msg_deq[m->param.major_type]++;
+ if (0 == m->param.major_type) //SPL_TCPIP_NEW_MSG_API
+ {
+ primary_stat->api_msg_deq[m->param.minor_type]++;
+ }
+ break;
+ case NSFW_STAT_PRIMARY_ENQ_FAIL:
+ if ((m->param.major_type >= MAX_MAJOR_TYPE)
+ || (m->param.minor_type >= MAX_MINOR_TYPE))
+ {
+ return;
+ }
+ __sync_fetch_and_add (&primary_stat->tcpip_msg_enq_fail
+ [m->param.major_type], 1);
+ if (0 == m->param.major_type) //SPL_TCPIP_NEW_MSG_API
+ {
+ __sync_fetch_and_add (&primary_stat->api_msg_enq_fail
+ [m->param.minor_type], 1);
+ }
+ break;
+ case NSFW_STAT_PRIMARY_ENQ:
+ //not use
+ break;
+ default:
+ break;
+ }
+}
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif /* __cplusplus */
diff --git a/stacks/lwip_stack/src/nStackMain/CMakeLists.txt b/stacks/lwip_stack/src/nStackMain/CMakeLists.txt
new file mode 100644
index 0000000..24f6c9d
--- /dev/null
+++ b/stacks/lwip_stack/src/nStackMain/CMakeLists.txt
@@ -0,0 +1,60 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+FILE(GLOB_RECURSE MAIN *.c)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE -pie")
+
+ADD_DEFINITIONS(-rdynamic -D__NSTACK_MAIN__)
+ADD_EXECUTABLE(nStackMain ${MAIN})
+TARGET_LINK_LIBRARIES(
+ nStackMain
+ -Wl,--whole-archive
+ ${LIB_PATH_STATIC}/libjson-c.a
+ ${LIB_PATH_STATIC}/libglog.a
+ dmm_api
+ nStackMaintain
+ stacklwip
+ nStackHal
+ nStackAlarm
+ nTcpdump
+ -Wl,--no-whole-archive,-lstdc++ -ldl
+ -Wl,--no-as-needed
+ rte_eal
+ rte_ethdev
+ rte_mempool
+ rte_ring
+ rte_mbuf
+ rte_pmd_ixgbe
+ rte_pmd_virtio
+ rte_pmd_e1000
+ rte_pmd_vmxnet3_uio
+ rte_pmd_bond
+ rte_kvargs
+ rte_cmdline
+)
+
+if(WITH_SECUREC_LIB)
+ADD_DEPENDENCIES(nStackMain nStackHal nStackMaintain nStackAlarm stacklwip SECUREC)
+else()
+ADD_DEPENDENCIES(nStackMain nStackHal nStackMaintain nStackAlarm stacklwip)
+endif()
+
+INCLUDE_DIRECTORIES(
+ ${CMAKE_CURRENT_LIST_DIR}/../alarm/
+ ${CMAKE_CURRENT_LIST_DIR}/../maintain/
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+)
diff --git a/stacks/lwip_stack/src/nStackMain/main.c b/stacks/lwip_stack/src/nStackMain/main.c
new file mode 100644
index 0000000..ce05068
--- /dev/null
+++ b/stacks/lwip_stack/src/nStackMain/main.c
@@ -0,0 +1,427 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <signal.h>
+#include <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <sched.h>
+#include <fcntl.h>
+#include <malloc.h>
+#include "nstack_securec.h"
+#include "nstack_log.h"
+#include "types.h"
+#include "nsfw_init.h"
+#include "alarm_api.h"
+
+#include "nsfw_mgr_com_api.h"
+#include "nsfw_ps_mem_api.h"
+#include "nsfw_ps_api.h"
+#include "nsfw_recycle_api.h"
+#include "nsfw_fd_timer_api.h"
+#include "nsfw_maintain_api.h"
+#include "nstack_dmm_adpt.h"
+
+#include "nsfw_mem_api.h"
+#include "nsfw_mt_config.h"
+
+#define GLOBAL_Stack_ARG "stack"
+#define GlOBAL_HELP "--help"
+#define GLOBAL_Dpdk_ARG "dpdk"
+#define GLOBAL_STACK_PORT "-port"
+#define NSTACK_MAIN_MAX_PARA 19
+#define NSTACK_MAIN_MIN_PARA 1
+
+#define MAX_MASTER_OPEN_FD 1024
+
+extern int uStackArgIndex;
+extern void spl_tcpip_thread (void *arg);
+extern int globalArgc;
+extern char **gArgv;
+extern int g_dpdk_argc;
+extern char **g_dpdk_argv;
+extern void print_call_stack ();
+extern int adjust_mem_arg (int argc, char *argv[]);
+extern struct cfg_item_info g_cfg_item_info[CFG_SEG_MAX][MAX_CFG_ITEM];
+extern int get_network_json_data ();
+extern int get_ip_json_data ();
+
+#ifdef SYS_MEM_RES_STAT
+extern void get_resource_stat ();
+#endif
+
+extern alarm_result ms_alarm_check_func (void *para);
+int g_tcpip_thread_stat = 0; //this variable will be used at health check feature
+
+#if (DPDK_MODULE)
+extern void pal_common_usage (void);
+#endif
+
+typedef void (*pSignalFunc) (int);
+int app_init (void);
+
+void
+helpInfo ()
+{
+ NSPOL_LOGERR
+ ("-----------------------------------------------------------------"
+ "\nThe format of arg" "\nbash:./nStackMain RTE-ARGS stack STACK-ARGS"
+ "\n RTE-ARGS=-c COREMASK -n NUM [-b <domain:bus:devid.func>] [--socket-mem=MB,...] [-m MB] [-r NUM] [-v] [--file-prefix] [--proc-type <primary|secondary|auto>] [-- xen-dom0]"
+ "\n STACK-ARGS=-port PORTMASK [-c COREMASK] [-thread NUM]"
+ "\nUser examples:"
+ "\nTo make the DPDK run on core mask:0xf,Number of memory channels per processor socket in DPDK is 3 "
+ "\nTo make the stack run on eth coremask:f"
+ "\nbash: ./nStackMain -c 0xf -n 3 stack -port f"
+ "\nTo get more help info for stack:" "\n ./nStackMain --help stack"
+ "\nTo get more help info for dpdk:" "\n ./nStackMain --help dpdk"
+ "\n-----------------------------------------------------------------");
+
+#ifndef FOR_NSTACK_UT
+ exit (0);
+#endif
+
+}
+
+#define SIG_PTRACE __SIGRTMIN + 5
+
+void
+signal_handler (int s)
+{
+ NSPOL_LOGERR ("Received signal exiting.]s=%d", s);
+ if (s == SIGSEGV) /* add for gdb attach work */
+ {
+ print_call_stack ();
+ }
+
+ nstack_segment_error (s);
+ if ((SIG_PTRACE != s) && (SIG_PTRACE + 2 != s))
+ {
+#ifndef FOR_NSTACK_UT
+ exit (0);
+#endif
+ }
+
+ int i;
+ for (i = 0; i < MAX_THREAD; i++)
+ {
+ if (g_all_thread[i] != pthread_self () && 0 != g_all_thread[i])
+ {
+ NSFW_LOGERR ("send sig thread %d", g_all_thread[i]);
+ if (0 == pthread_kill (g_all_thread[i], SIG_PTRACE + 2))
+ {
+ return;
+ }
+ }
+ g_all_thread[i] = 0;
+ }
+
+ for (i = 0; i < MAX_THREAD; i++)
+ {
+ if (0 != g_all_thread[i])
+ {
+ return;
+ }
+ }
+
+#ifndef FOR_NSTACK_UT
+ exit (0);
+#endif
+
+ //dpdk_signal_handler();
+}
+
+void
+register_signal_handler ()
+{
+/* donot catch SIGHUP SIGTERM */
+ static const int s_need_handle_signals[] = {
+ SIGABRT,
+ SIGBUS,
+ SIGFPE,
+ SIGILL,
+ SIGIOT,
+ SIGQUIT,
+ SIGSEGV,
+ //SIGTRAP,
+ SIGXCPU,
+ SIGXFSZ,
+ //SIGALRM,
+ //SIGHUP,
+ SIGINT,
+ //SIGKILL,
+ SIGPIPE,
+ SIGPROF,
+ SIGSYS,
+ //SIGTERM,
+ SIGUSR1,
+ SIGUSR2,
+ //SIGVTALRM,
+ //SIGSTOP,
+ //SIGTSTP,
+ //SIGTTIN,
+ //SIGTTOU
+ };
+
+ /* here mask signal that will use in sigwait() */
+ sigset_t waitset, oset;
+
+ if (0 != sigemptyset (&waitset))
+ {
+ NSPOL_LOGERR ("sigemptyset failed.");
+ }
+ sigaddset (&waitset, SIGRTMIN); /* for timer */
+ sigaddset (&waitset, SIGRTMIN + 2);
+ pthread_sigmask (SIG_BLOCK, &waitset, &oset);
+ unsigned int i = 0;
+
+ struct sigaction s;
+ s.sa_handler = signal_handler;
+ if (0 != sigemptyset (&s.sa_mask))
+ {
+ NSPOL_LOGERR ("sigemptyset failed.");
+ }
+
+ s.sa_flags = (int) SA_RESETHAND;
+
+ /* register sig handler for more signals */
+ for (i = 0; i < sizeof (s_need_handle_signals) / sizeof (int); i++)
+ {
+ if (sigaction (s_need_handle_signals[i], &s, NULL) != 0)
+ {
+ NSPOL_LOGERR ("Could not register %d signal handler.",
+ s_need_handle_signals[i]);
+ }
+
+ }
+
+}
+
+void
+checkArgs (int argc, char **argv)
+{
+ int uStackArg = 0; //mark the status whether need helpinfo and return
+ int i;
+ const unsigned int global_para_length = 5; //GLOBAL_Stack_ARG "stack" and GLOBAL_STACK_PORT "-port" string length, both are 5
+ const unsigned int global_help_length = 6; //GlOBAL_HELP "--help" string length is 6
+ const unsigned int global_dpdk_length = 4; //GLOBAL_Dpdk_ARG "dpdk" string length is 4
+
+ for (i = 0; i < argc; i++)
+ {
+ if (argc > 1)
+ {
+ if (strncmp (argv[i], GLOBAL_Stack_ARG, global_para_length) == 0)
+ {
+ if (i < 5)
+ {
+ NSPOL_LOGERR ("Too less args");
+ helpInfo ();
+ return;
+ }
+
+ uStackArg = 1;
+ uStackArgIndex = i;
+ continue;
+ }
+
+ if (strncmp (argv[i], GLOBAL_STACK_PORT, global_para_length) == 0)
+ {
+ continue;
+ }
+
+ if (strncmp (argv[i], GlOBAL_HELP, global_help_length) == 0)
+ {
+ if (i == (argc - 1))
+ {
+ helpInfo ();
+ return;
+ }
+ else if ((++i < argc)
+ &&
+ (strncmp (argv[i], GLOBAL_Dpdk_ARG, global_dpdk_length)
+ == 0))
+ {
+#if (DPDK_MODULE != 1)
+ //eal_common_usage();
+#else
+ pal_common_usage ();
+#endif
+ return;
+ }
+ else
+ {
+ helpInfo ();
+ return;
+ }
+ }
+ }
+ else
+ {
+ NSPOL_LOGERR ("Too less args");
+ helpInfo ();
+ return;
+ }
+ }
+
+ if (!uStackArg)
+ {
+ helpInfo ();
+ return;
+ }
+}
+
+extern u64 timer_get_threadid ();
+
+#ifdef FOR_NSTACK_UT
+int
+nstack_main (void)
+{
+ int argc;
+
+ char *argv[NSTACK_MAIN_MAX_PARA];
+ argv[0] = "nStackMain";
+ argv[1] = "-c";;
+ argv[2] = "0xffffffff";
+ argv[3] = "-n";
+ argv[4] = "3";
+ argv[5] = "stack";
+ argv[6] = "-port";
+ argv[7] = "288";
+ argv[8] = "-c";
+ argv[9] = "2";
+ argc = 10;
+
+#else
+int
+main (int argc, char *argv[])
+{
+#endif
+ fw_poc_type proc_type = NSFW_PROC_MAIN;
+
+ /* although nStackMaster has set close on exec, here can't be removed.
+ * in upgrade senario, if Master is old which has not set close on exec, here,
+ * if new version Main not close, problem will reappear. Add Begin*/
+ int i;
+ for (i = 4; i < MAX_MASTER_OPEN_FD; i++)
+ {
+ close (i);
+ }
+
+ cfg_module_param config_para;
+ config_para.proc_type = proc_type;
+ config_para.argc = argc;
+ config_para.argv = (unsigned char **) argv;
+ config_module_init (&config_para);
+
+ set_log_proc_type (LOG_PRO_NSTACK);
+ (void) nstack_log_init ();
+
+// nstack_tracing_enable();
+ if (0 != nsfw_proc_start_with_lock (NSFW_PROC_MAIN))
+ {
+ NSFW_LOGERR ("another process is running!!");
+ return 0;
+ }
+
+ if (1 != mallopt (M_ARENA_MAX, 1))
+ {
+ NSPOL_LOGERR ("Error: mallopt fail, continue init");
+ }
+
+ /* Set different mem args to PAL and EAL */
+ INITPOL_LOGINF ("main_thread", "adjust_mem_arg init", NULL_STRING,
+ LOG_INVALID_VALUE, MODULE_INIT_START);
+ if (adjust_mem_arg (argc, argv))
+ {
+ INITPOL_LOGERR ("main_thread", "adjust_mem_arg init", NULL_STRING,
+ LOG_INVALID_VALUE, MODULE_INIT_FAIL);
+ return -1;
+ }
+ INITPOL_LOGINF ("main_thread", "adjust_mem_arg init", NULL_STRING,
+ LOG_INVALID_VALUE, MODULE_INIT_SUCCESS);
+
+ checkArgs (globalArgc, gArgv);
+ register_signal_handler ();
+
+ (void) signal (SIG_PTRACE, signal_handler);
+ (void) signal (SIG_PTRACE + 2, signal_handler);
+
+ if (nsfw_mgr_comm_fd_init (NSFW_PROC_MAIN) < 0)
+ {
+ NSFW_LOGERR ("nsfw_mgr_comm_fd_init failed");
+ }
+
+ (void) nsfw_reg_trace_thread (pthread_self ());
+
+ (void) nstack_framework_setModuleParam (NSFW_ALARM_MODULE,
+ (void *) ((u64) proc_type));
+ (void) nstack_framework_setModuleParam (TCPDUMP_MODULE,
+ (void *) ((u64) proc_type));
+
+ nstack_dmm_para stpara;
+ stpara.argc = uStackArgIndex;
+ stpara.argv = gArgv;
+ stpara.deploy_type = NSTACK_MODEL_TYPE3;
+ stpara.proc_type = NSFW_PROC_MAIN;
+ stpara.attr.policy = get_cfg_info (CFG_SEG_PRI, CFG_SEG_THREAD_PRI_POLICY);
+ stpara.attr.pri = get_cfg_info (CFG_SEG_PRI, CFG_SEG_THREAD_PRI_PRI);
+
+ if (nstack_adpt_init (&stpara) != 0)
+ {
+ NSFW_LOGERR ("nstack adpt init fail");
+ return -1;
+ }
+
+ ns_send_init_alarm (ALARM_EVENT_NSTACK_MAIN_ABNORMAL);
+
+ while (!timer_get_threadid ())
+ {
+ (void) nsfw_thread_chk ();
+ sys_sleep_ns (0, 500000000);
+ }
+ (void) nsfw_thread_chk_unreg ();
+ NSFW_LOGINF ("tcpip thread start!");
+ (void) sleep (2);
+
+ NSFW_LOGINF ("read configuration!");
+ if (0 != get_network_json_data ())
+ {
+ NSFW_LOGINF ("get_network_json_data error");
+ }
+
+ if (0 != get_ip_json_data ())
+ {
+ NSFW_LOGINF ("get_ip_json_data error");
+ }
+
+ int ep_thread = 0;
+ while (1)
+ {
+#ifdef SYS_MEM_RES_STAT
+ get_resource_stat ();
+#endif
+ (void) sleep (3);
+ ep_thread = nsfw_mgr_com_chk_hbt (1);
+ if (ep_thread > 0)
+ {
+ NSFW_LOGINF ("force release lock");
+ (void) nsfw_recycle_rechk_lock ();
+ }
+#ifdef FOR_NSTACK_UT
+ return 0;
+#endif
+
+ }
+}
diff --git a/stacks/lwip_stack/src/sbr/CMakeLists.txt b/stacks/lwip_stack/src/sbr/CMakeLists.txt
new file mode 100644
index 0000000..42ab4a4
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/CMakeLists.txt
@@ -0,0 +1,30 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+if(WITH_HAL_LIB)
+else()
+ SET(PAL_H_DIRECTORIES "/usr/include/dpdk/")
+endif()
+
+
+FILE(GLOB SBR *.c)
+ADD_LIBRARY(nstack SHARED ${SBR})
+TARGET_LINK_LIBRARIES(nstack -Wl,--whole-archive socket -Wl,--no-whole-archive dmm_api nStackMaintain)
+ADD_DEPENDENCIES(nstack socket DPDK)
+INCLUDE_DIRECTORIES(
+ ${CMAKE_CURRENT_LIST_DIR}/../include
+ ${PAL_H_DIRECTORIES}
+)
diff --git a/stacks/lwip_stack/src/sbr/sbr_err.h b/stacks/lwip_stack/src/sbr/sbr_err.h
new file mode 100644
index 0000000..be3bc3b
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_err.h
@@ -0,0 +1,191 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SBR_ERR_H
+#define SBR_ERR_H
+#include <errno.h>
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#ifdef SBR_PROVIDE_ERRNO
+#define EPERM 1 /* Operation not permitted */
+#define ENOENT 2 /* No such file or directory */
+#define ESRCH 3 /* No such process */
+#define EINTR 4 /* Interrupted system call */
+#define EIO 5 /* I/O error */
+#define ENXIO 6 /* No such device or address */
+#define E2BIG 7 /* Arg list too long */
+#define ENOEXEC 8 /* Exec format error */
+#define EBADF 9 /* Bad file number */
+#define ECHILD 10 /* No child processes */
+#define EAGAIN 11 /* Try again */
+#define ENOMEM 12 /* Out of memory */
+#define EACCES 13 /* Permission denied */
+#define EFAULT 14 /* Bad address */
+#define ENOTBLK 15 /* Block device required */
+#define EBUSY 16 /* Device or resource busy */
+#define EEXIST 17 /* File exists */
+#define EXDEV 18 /* Cross-device link */
+#define ENODEV 19 /* No such device */
+#define ENOTDIR 20 /* Not a directory */
+#define EISDIR 21 /* Is a directory */
+#define EINVAL 22 /* Invalid argument */
+#define ENFILE 23 /* File table overflow */
+#define EMFILE 24 /* Too many open files */
+#define ENOTTY 25 /* Not a typewriter */
+#define ETXTBSY 26 /* Text file busy */
+#define EFBIG 27 /* File too large */
+#define ENOSPC 28 /* No space left on device */
+#define ESPIPE 29 /* Illegal seek */
+#define EROFS 30 /* Read-only file system */
+#define EMLINK 31 /* Too many links */
+#define EPIPE 32 /* Broken pipe */
+#define EDOM 33 /* Math argument out of domain of func */
+#define ERANGE 34 /* Math result not representable */
+#define EDEADLK 35 /* Resource deadlock would occur */
+#define ENAMETOOLONG 36 /* File name too long */
+#define ENOLCK 37 /* No stored locks available */
+#define ENOSYS 38 /* Function not implemented */
+#define ENOTEMPTY 39 /* Directory not empty */
+#define ELOOP 40 /* Too many symbolic links encountered */
+#define EWOULDBLOCK EAGAIN /* Operation would block */
+#define ENOMSG 42 /* No message of desired type */
+#define EIDRM 43 /* Identifier removed */
+#define ECHRNG 44 /* Channel number out of range */
+#define EL2NSYNC 45 /* Level 2 not synchronized */
+#define EL3HLT 46 /* Level 3 halted */
+#define EL3RST 47 /* Level 3 reset */
+#define ELNRNG 48 /* Link number out of range */
+#define EUNATCH 49 /* Protocol driver not attached */
+#define ENOCSI 50 /* No CSI structure available */
+#define EL2HLT 51 /* Level 2 halted */
+#define EBADE 52 /* Invalid exchange */
+#define EBADR 53 /* Invalid request descriptor */
+#define EXFULL 54 /* Exchange full */
+#define ENOANO 55 /* No anode */
+#define EBADRQC 56 /* Invalid request code */
+#define EBADSLT 57 /* Invalid slot */
+
+#define EDEADLOCK EDEADLK
+
+#define EBFONT 59 /* Bad font file format */
+#define ENOSTR 60 /* Device not a stream */
+#define ENODATA 61 /* No data available */
+#define ETIME 62 /* Timer expired */
+#define ENOSR 63 /* Out of streams resources */
+#define ENONET 64 /* Machine is not on the network */
+#define ENOPKG 65 /* Package not installed */
+#define EREMOTE 66 /* Object is remote */
+#define ENOLINK 67 /* Link has been severed */
+#define EADV 68 /* Advertise error */
+#define ESRMNT 69 /* Srmount error */
+#define ECOMM 70 /* Communication error on send */
+#define EPROTO 71 /* Protocol error */
+#define EMULTIHOP 72 /* Multihop attempted */
+#define EDOTDOT 73 /* RFS specific error */
+#define EBADMSG 74 /* Not a data message */
+#define EOVERFLOW 75 /* Value too large for defined data type */
+#define ENOTUNIQ 76 /* Name not unique on network */
+#define EBADFD 77 /* File descriptor in bad state */
+#define EREMCHG 78 /* Remote address changed */
+#define ELIBACC 79 /* Can not access a needed shared library */
+#define ELIBBAD 80 /* Accessing a corrupted shared library */
+#define ELIBSCN 81 /* .lib section in a.out corrupted */
+#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
+#define ELIBEXEC 83 /* Cannot exec a shared library directly */
+#define EILSEQ 84 /* Illegal byte sequence */
+#define ERESTART 85 /* Interrupted system call should be restarted */
+#define ESTRPIPE 86 /* Streams pipe error */
+#define EUSERS 87 /* Too many users */
+#define ENOTSOCK 88 /* Socket operation on non-socket */
+#define EDESTADDRREQ 89 /* Destination address required */
+#define EMSGSIZE 90 /* Message too long */
+#define EPROTOTYPE 91 /* Protocol wrong type for socket */
+#define ENOPROTOOPT 92 /* Protocol not available */
+#define EPROTONOSUPPORT 93 /* Protocol not supported */
+#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
+#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
+#define EPFNOSUPPORT 96 /* Protocol family not supported */
+#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
+#define EADDRINUSE 98 /* Address already in use */
+#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
+#define ENETDOWN 100 /* Network is down */
+#define ENETUNREACH 101 /* Network is unreachable */
+#define ENETRESET 102 /* Network dropped connection because of reset */
+#define ECONNABORTED 103 /* Software caused connection abort */
+#define ECONNRESET 104 /* Connection reset by peer */
+#define ENOBUFS 105 /* No buffer space available */
+#define EISCONN 106 /* Transport endpoint is already connected */
+#define ENOTCONN 107 /* Transport endpoint is not connected */
+#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
+#define ETOOMANYREFS 109 /* Too many references: cannot splice */
+#define ETIMEDOUT 110 /* Connection timed out */
+#define ECONNREFUSED 111 /* Connection refused */
+#define EHOSTDOWN 112 /* Host is down */
+#define EHOSTUNREACH 113 /* No route to host */
+#define EALREADY 114 /* Operation already in progress */
+#define EINPROGRESS 115 /* Operation now in progress */
+#define ESTALE 116 /* Stale NFS file handle */
+#define EUCLEAN 117 /* Structure needs cleaning */
+#define ENOTNAM 118 /* Not a XENIX named type file */
+#define ENAVAIL 119 /* No XENIX semaphores available */
+#define EISNAM 120 /* Is a named type file */
+#define EREMOTEIO 121 /* Remote I/O error */
+#define EDQUOT 122 /* Quota exceeded */
+
+#define ENOMEDIUM 123 /* No medium found */
+#define EMEDIUMTYPE 124 /* Wrong medium type */
+
+#define ENSROK 0
+#define ENSRNODATA 160
+#define ENSRFORMERR 161
+#define ENSRSERVFAIL 162
+#define ENSRNOTFOUND 163
+#define ENSRNOTIMP 164
+#define ENSRREFUSED 165
+#define ENSRBADQUERY 166
+#define ENSRBADNAME 167
+#define ENSRBADFAMILY 168
+#define ENSRBADRESP 169
+#define ENSRCONNREFUSED 170
+#define ENSRTIMEOUT 171
+#define ENSROF 172
+#define ENSRFILE 173
+#define ENSRNOMEM 174
+#define ENSRDESTRUCTION 175
+#define ENSRQUERYDOMAINTOOLONG 176
+#define ENSRCNAMELOOP 177
+#define OPTION_DEG 200
+
+#endif
+
+static inline void
+sbr_set_errno (int err)
+{
+ errno = err;
+}
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/sbr/sbr_index_ring.c b/stacks/lwip_stack/src/sbr/sbr_index_ring.c
new file mode 100644
index 0000000..0daa465
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_index_ring.c
@@ -0,0 +1,212 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <string.h>
+#include "sbr_index_ring.h"
+#include "nstack_securec.h"
+#include "common_mem_common.h"
+#include "common_func.h"
+
+/*****************************************************************************
+* Prototype : sbr_init_index_ring
+* Description : init index ring
+* Input : sbr_index_ring* ring
+* u32 num
+* Output : None
+* Return Value : static inline void
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline void
+sbr_init_index_ring (sbr_index_ring * ring, u32 num)
+{
+ u32 loop;
+
+ ring->head = 0;
+ ring->tail = 0;
+ ring->num = num;
+ ring->mask = num - 1;
+
+ for (loop = 0; loop < num; loop++)
+ {
+ ring->nodes[loop].ver = (loop - num);
+ ring->nodes[loop].val = 0;
+ }
+}
+
+/*****************************************************************************
+* Prototype : sbr_create_index_ring
+* Description : create index ring
+* Input : u32 num
+* Output : None
+* Return Value : sbr_index_ring*
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+sbr_index_ring *
+sbr_create_index_ring (u32 num)
+{
+ num = common_mem_align32pow2 (num + 1);
+ sbr_index_ring *ring =
+ (sbr_index_ring *) malloc (sizeof (sbr_index_ring) +
+ num * sizeof (sbr_index_node));
+ if (!ring)
+ {
+ return NULL;
+ }
+
+ sbr_init_index_ring (ring, num);
+ return ring;
+}
+
+/*****************************************************************************
+* Prototype : sbr_index_ring_enqueue
+* Description : enqueue data,val != 0
+* Input : sbr_index_ring* ring
+* i32 val
+* Output : None
+* Return Value : int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+int
+sbr_index_ring_enqueue (sbr_index_ring * ring, i32 val)
+{
+ if (0 == val)
+ {
+ return -1;
+ }
+
+ sbr_index_node expect_node;
+ sbr_index_node cur_node;
+ u32 tmp_head;
+ u32 tmp_tail;
+ u32 cur_head = ring->head;
+ u32 mask = ring->mask;
+ u32 size = ring->num;
+
+ do
+ {
+ tmp_tail = ring->tail;
+ if (tmp_tail + size - cur_head == 0)
+ {
+ if (ring->nodes[tmp_tail & mask].val == 0)
+ {
+ (void) __sync_bool_compare_and_swap (&ring->tail, tmp_tail,
+ tmp_tail + 1);
+ }
+ else
+ {
+ return 0;
+ }
+ }
+
+ expect_node.ver = cur_head - size;
+ expect_node.val = 0;
+
+ cur_node.ver = cur_head;
+ cur_node.val = val;
+
+ if ((ring->nodes[cur_head & mask].ver == expect_node.ver)
+ && __sync_bool_compare_and_swap (&ring->nodes[cur_head & mask].data,
+ expect_node.data, cur_node.data))
+ {
+ tmp_head = ring->head;
+ if ((tmp_head - cur_head > 0x80000000) && (0 == (cur_head & 0x11)))
+ {
+ (void) __sync_bool_compare_and_swap (&ring->head, tmp_head,
+ cur_head);
+ }
+
+ break;
+ }
+
+ tmp_head = ring->head;
+ cur_head = cur_head - tmp_head < mask - 1 ? cur_head + 1 : tmp_head;
+ }
+ while (1);
+
+ return 1;
+}
+
+/*****************************************************************************
+* Prototype : sbr_index_ring_dequeue
+* Description : dequeue
+* Input : sbr_index_ring* ring
+* i32* val
+* Output : None
+* Return Value : int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+int
+sbr_index_ring_dequeue (sbr_index_ring * ring, i32 * val)
+{
+ u32 cur_tail;
+ u32 tmp_tail;
+ u32 tmp_head;
+ u32 mask = ring->mask;
+ sbr_index_node null_node;
+ sbr_index_node expect_node;
+
+ cur_tail = ring->tail;
+ do
+ {
+ tmp_head = ring->head;
+ if (cur_tail == tmp_head)
+ {
+ if (0 != (ring->nodes[tmp_head & mask].val))
+ {
+ (void) __sync_bool_compare_and_swap (&ring->head, tmp_head,
+ tmp_head + 1);
+ }
+ else
+ {
+ return 0;
+ }
+ }
+
+ null_node.ver = cur_tail;
+ null_node.val = 0;
+ expect_node = ring->nodes[cur_tail & mask];
+
+ if ((null_node.ver == expect_node.ver) && (expect_node.val)
+ && __sync_bool_compare_and_swap (&ring->nodes[cur_tail & mask].data,
+ expect_node.data, null_node.data))
+
+ {
+ *val = expect_node.val;
+ tmp_tail = ring->tail;
+ if ((tmp_tail - cur_tail > 0x80000000) && (0 == (cur_tail & 0x11)))
+ {
+ (void) __sync_bool_compare_and_swap (&ring->tail, tmp_tail,
+ cur_tail);
+ }
+
+ break;
+ }
+
+ tmp_tail = ring->tail;
+ cur_tail = cur_tail - tmp_tail < mask - 1 ? cur_tail + 1 : tmp_tail;
+ }
+ while (1);
+
+ return 1;
+}
diff --git a/stacks/lwip_stack/src/sbr/sbr_index_ring.h b/stacks/lwip_stack/src/sbr/sbr_index_ring.h
new file mode 100644
index 0000000..86e8345
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_index_ring.h
@@ -0,0 +1,61 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _SBR_INDEX_RING_H_
+#define _SBR_INDEX_RING_H_
+
+#include "types.h"
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+typedef struct
+{
+ union
+ {
+ struct
+ {
+ volatile u32 ver;
+ volatile u32 val;
+ };
+ u64 data;
+ };
+} sbr_index_node;
+
+typedef struct
+{
+ volatile u32 head;
+ i8 cache_space[124];
+ volatile u32 tail;
+ u32 num;
+ u32 mask;
+ sbr_index_node nodes[0];
+} sbr_index_ring;
+
+sbr_index_ring *sbr_create_index_ring (u32 num);
+int sbr_index_ring_enqueue (sbr_index_ring * ring, i32 val);
+int sbr_index_ring_dequeue (sbr_index_ring * ring, i32 * val);
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/sbr/sbr_protocol_api.h b/stacks/lwip_stack/src/sbr/sbr_protocol_api.h
new file mode 100644
index 0000000..1c0fb1e
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_protocol_api.h
@@ -0,0 +1,99 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SBR_PROTOCOL_API_H
+#define SBR_PROTOCOL_API_H
+#include <sys/uio.h>
+#include <sys/epoll.h>
+#include <netinet/in.h>
+#include "sbr_err.h"
+#include "nsfw_msg_api.h"
+#include "nsfw_mt_config.h"
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+#ifndef SBR_MAX_INTEGER
+#define SBR_MAX_INTEGER 0x7FFFFFFF
+#endif
+
+#ifndef socklen_t
+#define socklen_t u32
+#endif
+
+#define SBR_MAX_FD_NUM MAX_SOCKET_NUM
+
+typedef struct sbr_socket_s sbr_socket_t;
+typedef struct
+{
+ int (*socket) (sbr_socket_t *, int, int, int);
+ int (*bind) (sbr_socket_t *, const struct sockaddr *, socklen_t);
+ int (*listen) (sbr_socket_t *, int);
+ int (*accept) (sbr_socket_t *, sbr_socket_t *, struct sockaddr *,
+ socklen_t *);
+ int (*accept4) (sbr_socket_t *, sbr_socket_t *, struct sockaddr *,
+ socklen_t *, int);
+ int (*connect) (sbr_socket_t *, const struct sockaddr *, socklen_t);
+ int (*shutdown) (sbr_socket_t *, int);
+ int (*getsockname) (sbr_socket_t *, struct sockaddr *, socklen_t *);
+ int (*getpeername) (sbr_socket_t *, struct sockaddr *, socklen_t *);
+ int (*getsockopt) (sbr_socket_t *, int, int, void *, socklen_t *);
+ int (*setsockopt) (sbr_socket_t *, int, int, const void *, socklen_t);
+ int (*recvfrom) (sbr_socket_t *, void *, size_t, int, struct sockaddr *,
+ socklen_t *);
+ int (*readv) (sbr_socket_t *, const struct iovec *, int);
+ int (*recvmsg) (sbr_socket_t *, struct msghdr *, int);
+ int (*send) (sbr_socket_t *, const void *, size_t, int);
+ int (*sendto) (sbr_socket_t *, const void *, size_t, int,
+ const struct sockaddr *, socklen_t);
+ int (*sendmsg) (sbr_socket_t *, const struct msghdr *, int);
+ int (*writev) (sbr_socket_t *, const struct iovec *, int);
+ int (*fcntl) (sbr_socket_t *, int, long);
+ int (*ioctl) (sbr_socket_t *, unsigned long, void *);
+ int (*close) (sbr_socket_t *);
+ int (*peak) (sbr_socket_t *);
+ void (*lock_common) (sbr_socket_t *);
+ void (*unlock_common) (sbr_socket_t *);
+ unsigned int (*ep_ctl) (sbr_socket_t *, int triggle_ops,
+ struct epoll_event * event, void *pdata);
+ unsigned int (*ep_getevt) (sbr_socket_t *, unsigned int events);
+ void (*set_app_info) (sbr_socket_t *, void *appinfo);
+ void (*set_close_stat) (sbr_socket_t *, int flag);
+} sbr_fdopt;
+
+struct sbr_socket_s
+{
+ int fd;
+ sbr_fdopt *fdopt;
+ void *stack_obj;
+ void *sk_obj;
+};
+
+int sbr_init_protocol ();
+
+sbr_fdopt *sbr_get_fdopt (int domain, int type, int protocol);
+void sbr_app_touch_in (void); /*app send its version info to nStackMain */
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/sbr/sbr_res_mgr.c b/stacks/lwip_stack/src/sbr/sbr_res_mgr.c
new file mode 100644
index 0000000..f40f101
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_res_mgr.c
@@ -0,0 +1,88 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "nstack_securec.h"
+#include "sbr_res_mgr.h"
+
+sbr_res_group g_res_group = { };
+
+/*****************************************************************************
+* Prototype : sbr_init_sk
+* Description : init sock pool
+* Input : None
+* Output : None
+* Return Value : static int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+NSTACK_STATIC int
+sbr_init_sk ()
+{
+ sbr_index_ring *ring = sbr_create_index_ring (SBR_MAX_FD_NUM - 1);
+
+ if (!ring)
+ {
+ NSSBR_LOGERR ("init ring failed");
+ return -1;
+ }
+
+ int i;
+ /*the queue can't accept value=0, so i begin with 1 */
+ for (i = 1; i <= SBR_MAX_FD_NUM; ++i)
+ {
+ g_res_group.sk[i].fd = i;
+ if (sbr_index_ring_enqueue (ring, i) != 1)
+ {
+ NSSBR_LOGERR ("sbr_index_ring_enqueue failed, this can not happen");
+ free (ring);
+ return -1;
+ }
+ }
+
+ g_res_group.sk_ring = ring;
+ return 0;
+}
+
+/*****************************************************************************
+* Prototype : sbr_init_res
+* Description : init sbr res
+* Input : None
+* Output : None
+* Return Value : int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+int
+sbr_init_res ()
+{
+ if (sbr_init_sk () != 0)
+ {
+ return -1;
+ }
+
+ NSSBR_LOGDBG ("init socket ok");
+
+ if (sbr_init_protocol () != 0)
+ {
+ return -1;
+ }
+
+ NSSBR_LOGDBG ("init protocol ok");
+
+ return 0;
+}
diff --git a/stacks/lwip_stack/src/sbr/sbr_res_mgr.h b/stacks/lwip_stack/src/sbr/sbr_res_mgr.h
new file mode 100644
index 0000000..54729d4
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_res_mgr.h
@@ -0,0 +1,128 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SBR_RES_MGR_H
+#define SBR_RES_MGR_H
+#include "sbr_protocol_api.h"
+#include "sbr_index_ring.h"
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+extern "C" {
+/* *INDENT-ON* */
+#endif
+
+typedef struct
+{
+ sbr_index_ring *sk_ring;
+ sbr_socket_t sk[SBR_MAX_FD_NUM + 1]; /* unuse index 0 */
+} sbr_res_group;
+
+extern sbr_res_group g_res_group;
+
+/*****************************************************************************
+* Prototype : sbr_malloc_sk
+* Description : malloc sock
+* Input : None
+* Output : None
+* Return Value : static inline sbr_socket_t *
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline sbr_socket_t *
+sbr_malloc_sk ()
+{
+ int fd;
+
+ if (sbr_index_ring_dequeue (g_res_group.sk_ring, &fd) != 1)
+ {
+ NSSBR_LOGERR ("malloc sk failed]");
+ sbr_set_errno (EMFILE);
+ return NULL;
+ }
+
+ NSSBR_LOGDBG ("malloc sk ok]fd=%d", fd);
+ return &g_res_group.sk[fd];
+}
+
+/*****************************************************************************
+* Prototype : sbr_free_sk
+* Description : free sock
+* Input : sbr_socket_t * sk
+* Output : None
+* Return Value : static inline void
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline void
+sbr_free_sk (sbr_socket_t * sk)
+{
+ sk->fdopt = NULL;
+ sk->sk_obj = NULL;
+ sk->stack_obj = NULL;
+
+ if (sbr_index_ring_enqueue (g_res_group.sk_ring, sk->fd) != 1)
+ {
+ NSSBR_LOGERR ("sbr_index_ring_enqueue failed, this can not happen");
+ }
+
+ NSSBR_LOGDBG ("free sk ok]fd=%d", sk->fd);
+}
+
+/*****************************************************************************
+* Prototype : sbr_lookup_sk
+* Description : lookup socket
+* Input : int fd
+* Output : None
+* Return Value : static inline sbr_socket_t *
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline sbr_socket_t *
+sbr_lookup_sk (int fd)
+{
+ if ((fd < 1) || (fd > SBR_MAX_FD_NUM))
+ {
+ NSSBR_LOGERR ("fd is not ok]fd=%d", fd);
+ sbr_set_errno (EBADF);
+ return NULL;
+ }
+
+ sbr_socket_t *sk = &g_res_group.sk[fd];
+ if (!sk->sk_obj || !sk->stack_obj)
+ {
+ NSSBR_LOGERR
+ ("data in sk is error, this can not happen]fd=%d,sk_obj=%p,stack_obj=%p",
+ fd, sk->sk_obj, sk->stack_obj);
+ sbr_set_errno (EBADF);
+ return NULL;
+ }
+
+ return sk;
+}
+
+int sbr_init_res ();
+
+#ifdef __cplusplus
+/* *INDENT-OFF* */
+}
+/* *INDENT-ON* */
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/src/sbr/sbr_socket.c b/stacks/lwip_stack/src/sbr/sbr_socket.c
new file mode 100644
index 0000000..47aefda
--- /dev/null
+++ b/stacks/lwip_stack/src/sbr/sbr_socket.c
@@ -0,0 +1,1231 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <dlfcn.h>
+#include "sbr_protocol_api.h"
+#include "sbr_res_mgr.h"
+#include "nstack_log.h"
+#include "nstack_dmm_api.h"
+
+#define SBR_INTERCEPT(ret, name, args) ret sbr_ ## name args
+#define CALL_SBR_INTERCEPT(name, args) sbr_ ## name args
+#define GET_SBR_INTERCEPT(name) sbr_ ## name
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : create socket
+* Input : int
+* socket
+* (int domain
+* int type
+* int protocol)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, socket, (int domain, int type, int protocol))
+{
+ NSSBR_LOGDBG ("socket]domain=%d,type=%d,protocol=%d", domain, type,
+ protocol);
+ sbr_fdopt *fdopt = sbr_get_fdopt (domain, type, protocol);
+
+ if (!fdopt)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_malloc_sk ();
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt = fdopt;
+
+ int ret = sk->fdopt->socket (sk, domain, type, protocol);
+
+ if (ret != 0)
+ {
+ sbr_free_sk (sk);
+ return ret;
+ }
+
+ return sk->fd;
+}
+
+/*****************************************************************************
+* Prototype : sbr_check_addr
+* Description : check addr
+* Input : int s
+* struct sockaddr * addr
+* socklen_t * addrlen
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline int
+sbr_check_addr (int s, struct sockaddr *addr, socklen_t * addrlen)
+{
+ if (addr)
+ {
+ if (!addrlen)
+ {
+ NSSBR_LOGERR ("addrlen is null]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ if (0 > (int) (*addrlen))
+ {
+ NSSBR_LOGERR ("addrlen is negative]fd=%d,addrlen=%d", s, *addrlen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : accept4
+* Input : int
+* accept4
+* (int s
+* struct sockaddr * addr
+* socklen_t * addrlen
+* int flags)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, accept4,
+ (int s, struct sockaddr * addr, socklen_t * addrlen,
+ int flags))
+{
+ NSSBR_LOGDBG ("accept4]fd=%d,addr=%p,addrlen=%p,flags=%d", s, addr, addrlen,
+ flags);
+ int ret = sbr_check_addr (s, addr, addrlen);
+
+ if (ret != 0)
+ {
+ return ret;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *new_sk = sbr_malloc_sk ();
+ if (!new_sk)
+ {
+ return -1;
+ }
+
+ new_sk->fdopt = sk->fdopt;
+
+ ret = sk->fdopt->accept4 (sk, new_sk, addr, addrlen, flags);
+ if (-1 == ret)
+ {
+ sbr_free_sk (new_sk);
+ }
+
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : accept
+* Input : int
+* accept
+* (int s
+* struct sockaddr * addr
+* socklen_t * addrlen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, accept,
+ (int s, struct sockaddr * addr, socklen_t * addrlen))
+{
+ NSSBR_LOGDBG ("accept]fd=%d,addr=%p,addrlen=%p", s, addr, addrlen);
+ int ret = sbr_check_addr (s, addr, addrlen);
+
+ if (ret != 0)
+ {
+ return ret;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *new_sk = sbr_malloc_sk ();
+ if (!new_sk)
+ {
+ return -1;
+ }
+
+ new_sk->fdopt = sk->fdopt;
+
+ ret = sk->fdopt->accept (sk, new_sk, addr, addrlen);
+ if (-1 == ret)
+ {
+ sbr_free_sk (new_sk);
+ }
+
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : bind
+* Input : int
+* bind
+* (int s
+* const struct sockaddr * name
+* socklen_t namelen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, bind,
+ (int s, const struct sockaddr * name, socklen_t namelen))
+{
+ NSSBR_LOGDBG ("bind]fd=%d,name=%p,namelen=%d", s, name, namelen);
+ if (!name)
+ {
+ NSSBR_LOGERR ("name is not ok]fd=%d,name=%p", s, name);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ if ((name->sa_family) != AF_INET)
+ {
+ NSSBR_LOGERR ("domain is not AF_INET]fd=%d,name->sa_family=%u", s,
+ name->sa_family);
+ sbr_set_errno (EAFNOSUPPORT);
+ return -1;
+ }
+
+ if (namelen != sizeof (struct sockaddr_in))
+ {
+ NSSBR_LOGERR ("namelen is invalid]fd=%d,namelen=%d", s, namelen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->bind (sk, name, namelen);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : listen
+* Input : int
+* listen
+* (int s
+* int backlog)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, listen, (int s, int backlog))
+{
+ NSSBR_LOGDBG ("listen]fd=%d,backlog=%d", s, backlog);
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ /* limit the "backlog" parameter to fit in an u8_t */
+ if (backlog < 0)
+ {
+ backlog = 0;
+ }
+
+ if (backlog > 0xff)
+ {
+ backlog = 0xff;
+ }
+
+ return sk->fdopt->listen (sk, backlog);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : connect
+* Input : int
+* connect
+* (int s
+* const struct sockaddr * name
+* socklen_t namelen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, connect,
+ (int s, const struct sockaddr * name, socklen_t namelen))
+{
+ NSSBR_LOGDBG ("connect]fd=%d,name=%p,namelen=%d", s, name, namelen);
+ if (!name)
+ {
+ NSSBR_LOGERR ("name is null]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ if (!
+ (namelen == sizeof (struct sockaddr_in)
+ && (name->sa_family == AF_INET)))
+ {
+ NSSBR_LOGERR ("parameter invalid]fd=%d,domain=%u,namelen=%d", s,
+ name->sa_family, namelen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ NSSBR_LOGERR ("get socket failed]fd=%d", s);
+ return -1;
+ }
+
+ return sk->fdopt->connect (sk, name, namelen);
+}
+
+/*****************************************************************************
+* Prototype : sbr_check_sock_name
+* Description : check name
+* Input : int s
+* struct sockaddr * name
+* socklen_t * namelen
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline int
+sbr_check_sock_name (int s, struct sockaddr *name, socklen_t * namelen)
+{
+ if (!name || !namelen)
+ {
+ NSSBR_LOGERR ("name or namelen is null]fd=%d", s);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ if (*namelen & 0x80000000)
+ {
+ NSSBR_LOGERR ("namelen is not ok]fd=%d,namelen=%d", s, *namelen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : getpeername
+* Input : int
+* getpeername
+* (int s
+* struct sockaddr * name
+* socklen_t * namelen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, getpeername,
+ (int s, struct sockaddr * name, socklen_t * namelen))
+{
+ NSSBR_LOGDBG ("getpeername]fd=%d", s);
+ int ret = sbr_check_sock_name (s, name, namelen);
+
+ if (ret != 0)
+ {
+ return ret;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ ret = sk->fdopt->getpeername (sk, name, namelen);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : getsockname
+* Input : int
+* getsockname
+* (int s
+* struct sockaddr * name
+* socklen_t * namelen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, getsockname,
+ (int s, struct sockaddr * name, socklen_t * namelen))
+{
+ NSSBR_LOGDBG ("getsockname]fd=%d", s);
+ int ret = sbr_check_sock_name (s, name, namelen);
+
+ if (ret != 0)
+ {
+ return ret;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ ret = sk->fdopt->getsockname (sk, name, namelen);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : setsockopt
+* Input : int
+* setsockopt
+* (int s
+* int level
+* int optname
+* const void * optval
+* socklen_t optlen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, setsockopt,
+ (int s, int level, int optname, const void *optval,
+ socklen_t optlen))
+{
+ NSSBR_LOGDBG ("setsockopt]fd=%d,level=%d,optname=%d,optval=%p,optlen=%d", s,
+ level, optname, optval, optlen);
+ if (!optval)
+ {
+ NSSBR_LOGERR ("optval is null]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ int ret = sk->fdopt->setsockopt (sk, level, optname, optval, optlen);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : getsockopt
+* Input : int
+* getsockopt
+* (int s
+* int level
+* int optname
+* void * optval
+* socklen_t * optlen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, getsockopt,
+ (int s, int level, int optname, void *optval,
+ socklen_t * optlen))
+{
+ NSSBR_LOGDBG ("getsockopt]fd=%d,level=%d,optname=%d,optval=%p,optlen=%p", s,
+ level, optname, optval, optlen);
+ if (!optval || !optlen)
+ {
+ NSSBR_LOGERR ("optval or optlen is NULL]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ int ret = sk->fdopt->getsockopt (sk, level, optname, optval, optlen);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : ioctl
+* Input : int
+* ioctl
+* (int s
+* unsigned long cmd
+* ...)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, ioctl, (int s, unsigned long cmd, ...))
+{
+ NSSBR_LOGDBG ("ioctl]fd=%d,cmd=%lu", s, cmd);
+ va_list va;
+ va_start (va, cmd);
+ void *arg = va_arg (va, void *);
+ va_end (va);
+
+ if (!arg)
+ {
+ NSSBR_LOGERR ("parameter is not ok]fd=%d", s);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ int ret = sk->fdopt->ioctl (sk, cmd, arg);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : fcntl
+* Input : int
+* fcntl
+* (int s
+* int cmd
+* ...)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, fcntl, (int s, int cmd, ...))
+{
+ NSSBR_LOGDBG ("fcntl]fd=%d,cmd=%d", s, cmd);
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ va_list va;
+ va_start (va, cmd);
+ long arg = va_arg (va, long);
+ va_end (va);
+
+ sk->fdopt->lock_common (sk);
+ int ret = sk->fdopt->fcntl (sk, cmd, arg);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : recvfrom
+* Input : int
+* recvfrom
+* (int s
+* void * mem
+* size_t len
+* int flags
+* struct sockaddr * from
+* socklen_t * fromlen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, recvfrom,
+ (int s, void *mem, size_t len, int flags,
+ struct sockaddr * from, socklen_t * fromlen))
+{
+ NSSBR_LOGDBG ("recvfrom]fd=%d,mem=%p,len=%d,flags=%d,from=%p,fromlen=%p", s,
+ mem, len, flags, from, fromlen);
+
+ if (0 == len)
+ {
+ NSSBR_LOGDBG ("len is zero]fd=%d,len=%u", s, (u32) len);
+ return 0; //return directly, don't change the last errno.
+ }
+
+ if (!mem)
+ {
+ NSSBR_LOGERR ("mem is NULL]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ if (fromlen && (*((int *) fromlen) < 0))
+ {
+ NSSBR_LOGERR ("fromlen is not ok]fd=%d,fromlen=%d", s, *fromlen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->recvfrom (sk, mem, len, flags, from, fromlen);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : read
+* Input : int
+* read
+* (int s
+* void * mem
+* size_t len)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, read, (int s, void *mem, size_t len))
+{
+ NSSBR_LOGDBG ("read]fd=%d,mem=%p,len=%d", s, mem, len);
+ return CALL_SBR_INTERCEPT (recvfrom, (s, mem, len, 0, NULL, NULL));
+}
+
+/*****************************************************************************
+* Prototype : sbr_check_iov
+* Description : check iov
+* Input : int s
+* const struct iovec * iov
+* int iovcnt
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline int
+sbr_check_iov (int s, const struct iovec *iov, int iovcnt)
+{
+ if ((!iov) || (iovcnt <= 0))
+ {
+ NSSBR_LOGERR ("iov is NULL or iovcn <=0]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ int i;
+ for (i = 0; i < iovcnt; ++i)
+ {
+ if (!iov[i].iov_base && (iov[i].iov_len != 0))
+ {
+ NSSBR_LOGERR ("iov is not ok]fd=%d,iov_base=%p,iov_len=%d", s,
+ iov[i].iov_base, iov[i].iov_len);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : readv
+* Input : int
+* readv
+* (int s
+* const struct iovec * iov
+* int iovcnt)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, readv, (int s, const struct iovec * iov, int iovcnt))
+{
+ NSSBR_LOGDBG ("readv]fd=%d,iov=%p,iovcnt=%d", s, iov, iovcnt);
+
+ if (sbr_check_iov (s, iov, iovcnt) != 0)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->readv (sk, iov, iovcnt);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : recv
+* Input : int
+* recv
+* (int s
+* void * mem
+* size_t len
+* int flags)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, recv, (int s, void *mem, size_t len, int flags))
+{
+ NSSBR_LOGDBG ("recv]fd=%d,mem=%p,len=%d,flags=%d", s, mem, len, flags);
+ return CALL_SBR_INTERCEPT (recvfrom, (s, mem, len, flags, NULL, NULL));
+}
+
+/*****************************************************************************
+* Prototype : sbr_check_msg
+* Description : check msg
+* Input : int s
+* const struct msghdr * msg
+* Output : None
+* Return Value : static inline int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+static inline int
+sbr_check_msg (int s, const struct msghdr *msg)
+{
+ if (!msg)
+ {
+ NSSBR_LOGERR ("msg is NULL]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ if (msg->msg_name && ((int) msg->msg_namelen < 0))
+ {
+ NSSBR_LOGERR ("msg_namelen is not ok]fd=%d,msg_namelen=%d", s,
+ msg->msg_namelen);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ return sbr_check_iov (s, msg->msg_iov, msg->msg_iovlen);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : recvmsg
+* Input : int
+* recvmsg
+* (int s
+* struct msghdr * msg
+* int flags)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, recvmsg, (int s, struct msghdr * msg, int flags))
+{
+ NSSBR_LOGDBG ("recvmsg]fd=%d,msg=%p,flags=%d", s, msg, flags);
+
+ if (sbr_check_msg (s, msg) != 0)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->recvmsg (sk, msg, flags);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : send
+* Input : int
+* send
+* (int s
+* const void * data
+* size_t size
+* int flags)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, send, (int s, const void *data, size_t size, int flags))
+{
+ NSSBR_LOGDBG ("send]fd=%d,data=%p,size=%zu,flags=%d", s, data, size, flags);
+ if (!data)
+ {
+ NSSBR_LOGERR ("data is NULL]fd=%d", s);
+ sbr_set_errno (EFAULT);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->send (sk, data, size, flags);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : sendmsg
+* Input : int
+* sendmsg
+* (int s
+* const struct msghdr * msg
+* int flags)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, sendmsg, (int s, const struct msghdr * msg, int flags))
+{
+ NSSBR_LOGDBG ("sendmsg]fd=%d,msg=%p,flags=%d", s, msg, flags);
+
+ if (sbr_check_msg (s, msg) != 0)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->sendmsg (sk, msg, flags);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : sendto
+* Input : int
+* sendto
+* (int s
+* const void * data
+* size_t size
+* int flags
+* const struct sockaddr * to
+* socklen_t tolen)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, sendto,
+ (int s, const void *data, size_t size, int flags,
+ const struct sockaddr * to, socklen_t tolen))
+{
+ NSSBR_LOGDBG ("sendto]fd=%d,data=%p,size=%zu,flags=%d,to=%p,tolen=%d", s,
+ data, size, flags, to, tolen);
+ if ((data == NULL) || (flags < 0))
+ {
+ NSSBR_LOGERR ("parameter is not ok]fd=%d,data=%p,size=%zu,flags=%d", s,
+ data, size, flags);
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->sendto (sk, data, size, flags, to, tolen);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : write
+* Input : int
+* write
+* (int s
+* const void * data
+* size_t size)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, write, (int s, const void *data, size_t size))
+{
+ NSSBR_LOGDBG ("write]fd=%d,data=%p,size=%zu", s, data, size);
+ return CALL_SBR_INTERCEPT (send, (s, data, size, 0));
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : writev
+* Input : int
+* writev
+* (int s
+* const struct iovec * iov
+* int iovcnt)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, writev, (int s, const struct iovec * iov, int iovcnt))
+{
+ NSSBR_LOGDBG ("writev]fd=%d,iov=%p,iovcnt=%d", s, iov, iovcnt);
+
+ if (sbr_check_iov (s, iov, iovcnt) != 0)
+ {
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->writev (sk, iov, iovcnt);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : shutdown
+* Input : int
+* shutdown
+* (int s
+* int how)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, shutdown, (int s, int how))
+{
+ NSSBR_LOGDBG ("shutdown]fd=%d,how=%d", s, how);
+ if ((how != SHUT_RD) && (how != SHUT_WR) && (how != SHUT_RDWR))
+ {
+ sbr_set_errno (EINVAL);
+ return -1;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ sk->fdopt->lock_common (sk);
+ int ret = sk->fdopt->shutdown (sk, how);
+ sk->fdopt->unlock_common (sk);
+ return ret;
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : close
+* Input : int
+* close
+* (int s)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (int, close, (int s))
+{
+ NSSBR_LOGDBG ("close]fd=%d", s);
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ int ret = sk->fdopt->close (sk);
+ sbr_free_sk (sk);
+ return ret;
+}
+
+SBR_INTERCEPT (int, select,
+ (int nfds, fd_set * readfd, fd_set * writefd,
+ fd_set * exceptfd, struct timeval * timeout))
+{
+ return -1;
+}
+
+SBR_INTERCEPT (unsigned int, ep_getevt,
+ (int epfd, int profd, unsigned int events))
+{
+ NSSBR_LOGDBG ("epfd= %d, proFD=%d,epi=0x%x", epfd, profd, events);
+ sbr_socket_t *sk = sbr_lookup_sk (profd);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->ep_getevt (sk, events);
+}
+
+SBR_INTERCEPT (unsigned int, ep_ctl,
+ (int epfd, int profd, int triggle_ops,
+ struct epoll_event * event, void *pdata))
+{
+ NSSBR_LOGDBG ("epfd = %d, proFD=%d,triggle_ops=%d,pdata=%p", epfd, profd,
+ triggle_ops, pdata);
+ sbr_socket_t *sk = sbr_lookup_sk (profd);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->ep_ctl (sk, triggle_ops, event, pdata);
+}
+
+SBR_INTERCEPT (int, peak, (int s))
+{
+ NSSBR_LOGDBG ("]fd=%d", s);
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return -1;
+ }
+
+ return sk->fdopt->peak (sk);
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : set_app_info
+* Input : int
+* set_app_info
+* (int s
+* void* app_info)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (void, set_app_info, (int s, void *app_info))
+{
+ NSSBR_LOGDBG ("set_app_info]fd=%d", s);
+
+ if (!app_info)
+ {
+ NSSBR_LOGERR ("invalid param, app_info is NULL]");
+ return;
+ }
+
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+ if (!sk)
+ {
+ return;
+ }
+
+ sk->fdopt->set_app_info (sk, app_info);
+}
+
+/* app send its version info to nStackMain */
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : sbr_app_touch
+* Input : int
+* sbr_app_touch
+* ()
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (void, app_touch, (void))
+{
+ NSSBR_LOGDBG ("sbr_app_touch() is called]");
+
+ sbr_app_touch_in ();
+}
+
+/*****************************************************************************
+* Prototype : SBR_INTERCEPT
+* Description : set_close_status
+* Input : void
+* set_close_stat
+* (int s
+* int flag)
+* Output : None
+* Return Value :
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+SBR_INTERCEPT (void, set_close_stat, (int s, int flag))
+{
+ NSSBR_LOGDBG ("]fd=%d", s);
+ sbr_socket_t *sk = sbr_lookup_sk (s);
+
+ if (!sk)
+ {
+ return;
+ }
+ if (sk->fdopt->set_close_stat)
+ {
+ sk->fdopt->set_close_stat (sk, flag);
+ }
+
+}
+
+SBR_INTERCEPT (int, fd_alloc, ())
+{
+ return sbr_socket (AF_INET, SOCK_STREAM, 0);
+}
+
+/*****************************************************************************
+* Prototype : nstack_stack_register
+* Description : reg api to nsocket
+* Input : nstack_socket_ops* ops
+* nstack_event_ops *val
+* nstack_proc_ops *deal
+* Output : None
+* Return Value : int
+* Calls :
+* Called By :
+*
+*****************************************************************************/
+int
+nstack_stack_register (nstack_proc_cb * ops, nstack_event_cb * val)
+{
+ if (!ops || !val || !val->handle)
+ {
+ return -1;
+ }
+
+#undef NSTACK_MK_DECL
+#define NSTACK_MK_DECL(ret, fn, args) \
+ (ops->socket_ops).pf ## fn = (typeof(((nstack_socket_ops*)0)->pf ## fn))dlsym(val->handle, "sbr_" # fn);
+#include "declare_syscalls.h"
+
+ (ops->extern_ops).module_init = sbr_init_res;
+ (ops->extern_ops).ep_getevt = GET_SBR_INTERCEPT (ep_getevt);
+ (ops->extern_ops).ep_ctl = GET_SBR_INTERCEPT (ep_ctl);
+ (ops->extern_ops).peak = GET_SBR_INTERCEPT (peak);
+ (ops->extern_ops).stack_alloc_fd = GET_SBR_INTERCEPT (fd_alloc); /*alloc a fd id for epoll */
+ return 0;
+}
diff --git a/stacks/lwip_stack/src/tools/CMakeLists.txt b/stacks/lwip_stack/src/tools/CMakeLists.txt
new file mode 100644
index 0000000..bd485b8
--- /dev/null
+++ b/stacks/lwip_stack/src/tools/CMakeLists.txt
@@ -0,0 +1,22 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+FILE(GLOB_RECURSE Tcpdump *.c)
+ADD_LIBRARY(nTcpdump STATIC ${Tcpdump})
+INCLUDE_DIRECTORIES(
+ ${CMAKE_CURRENT_LIST_DIR}/../include
+)
+TARGET_LINK_LIBRARIES(nTcpdump dmm_api) \ No newline at end of file
diff --git a/stacks/lwip_stack/src/tools/dump_tool.c b/stacks/lwip_stack/src/tools/dump_tool.c
new file mode 100644
index 0000000..53f0e44
--- /dev/null
+++ b/stacks/lwip_stack/src/tools/dump_tool.c
@@ -0,0 +1,622 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <arpa/inet.h>
+
+#include "nsfw_init.h"
+#include "nsfw_maintain_api.h"
+#include "nsfw_mem_api.h"
+#include "nsfw_fd_timer_api.h"
+#include "nstack_log.h"
+#include "nstack_securec.h"
+
+#include "dump_tool.h"
+#include "nstack_dmm_adpt.h"
+
+NSTACK_STATIC u32 g_dump_task_mask = 0;
+NSTACK_STATIC dump_task_info g_dump_task[MAX_DUMP_TASK];
+static dump_timer_info g_dump_timer;
+
+static nsfw_mem_name g_dump_mem_ring_info =
+ { NSFW_SHMEM, NSFW_PROC_MAIN, DUMP_SHMEM_RIGN_NAME };
+static nsfw_mem_name g_dump_mem_pool_info =
+ { NSFW_SHMEM, NSFW_PROC_MAIN, DUMP_SHMEM_POOL_NAME };
+
+NSTACK_STATIC inline void
+dump_task_init (dump_task_info * task)
+{
+ task->task_state = 0;
+ task->task_id = -1;
+ task->task_keep_time = 0;
+ task->task_pool = NULL;
+ task->task_queue = NULL;
+}
+
+NSTACK_STATIC inline void
+clear_dump_task ()
+{
+ int i = 0;
+ for (; i < MAX_DUMP_TASK; i++)
+ {
+ dump_task_init (&g_dump_task[i]);
+ }
+}
+
+NSTACK_STATIC i16
+get_dump_task (nsfw_tool_dump_msg * req)
+{
+ // base version just support 1 dump task
+ if (req->task_keep_time > MAX_DUMP_TIME
+ || req->task_keep_time < MIN_DUMP_TIME)
+ {
+ NSPOL_DUMP_LOGERR ("task keep time invalid] time=%u.",
+ req->task_keep_time);
+ return -1;
+ }
+
+ if (1 == g_dump_task[0].task_state)
+ {
+ NSPOL_DUMP_LOGERR
+ ("start tcpdump task failed, task still in work state] task id=%d.",
+ 0);
+ return -1;
+ }
+
+ struct timespec cur_time;
+ GET_CUR_TIME (&cur_time); /*do not need return value */
+ g_dump_task[0].task_start_sec = cur_time.tv_sec;
+ g_dump_task[0].last_hbt_sec = cur_time.tv_sec;
+
+ g_dump_task[0].task_state = 1;
+ g_dump_task[0].task_id = 0;
+ g_dump_task[0].task_keep_time = req->task_keep_time;
+
+ g_dump_task_mask |= (1 << g_dump_task[0].task_id);
+ NSPOL_DUMP_LOGINF ("start tcpdump task success] task id=%d.", 0);
+ return 0;
+}
+
+NSTACK_STATIC i16
+close_dump_task (i16 task_id)
+{
+ if (task_id < 0 || task_id >= MAX_DUMP_TASK)
+ {
+ NSPOL_DUMP_LOGERR
+ ("receive invalid task id in close dump task req] task id=%d.",
+ task_id);
+ return -1;
+ }
+
+ g_dump_task[task_id].task_state = 0;
+
+ g_dump_task_mask &= ~(1 << task_id);
+
+ NSPOL_DUMP_LOGINF ("stop tcpdump task success] task id=%d.", 0);
+
+ return task_id;
+}
+
+NSTACK_STATIC void
+stop_expired_task (int idx, u32 now_sec)
+{
+ dump_task_info *ptask = &g_dump_task[idx];
+ if (0 == ptask->task_state)
+ {
+ return;
+ }
+
+ if (now_sec - ptask->task_start_sec > ptask->task_keep_time)
+ {
+ NSPOL_DUMP_LOGERR
+ ("stop dump task because task time expired] task id=%d, now_sec=%u, task start time=%u, dump time=%u.",
+ ptask->task_id, now_sec, ptask->task_start_sec,
+ ptask->task_keep_time);
+ close_dump_task (ptask->task_id);
+ return;
+ }
+
+ if (now_sec - ptask->last_hbt_sec > DUMP_TASK_HBT_TIME_OUT)
+ {
+ NSPOL_DUMP_LOGERR
+ ("stop dump task because heart beat time out] task id=%d, now_sec=%u, last hbt time=%u, hbt timeout=%u.",
+ ptask->task_id, now_sec, ptask->last_hbt_sec,
+ DUMP_TASK_HBT_TIME_OUT);
+ close_dump_task (ptask->task_id);
+ }
+
+ return;
+}
+
+NSTACK_STATIC inline bool
+check_dump_alive (u32 timer_type, void *data)
+{
+ dump_timer_info *ptimer_info = (dump_timer_info *) data;
+
+ struct timespec cur_time;
+ GET_CUR_TIME (&cur_time); /*do not need return value */
+
+ int i = 0;
+ for (; i < MAX_DUMP_TASK; i++)
+ {
+ stop_expired_task (i, cur_time.tv_sec);
+ }
+
+ ptimer_info->ptimer =
+ nsfw_timer_reg_timer (1, ptimer_info, check_dump_alive,
+ *(struct timespec *) (ptimer_info->interval));
+
+ return true;
+}
+
+NSTACK_STATIC bool
+dump_init_timer (dump_timer_info * ptimer_info)
+{
+ struct timespec *trigger_time =
+ (struct timespec *) malloc (sizeof (struct timespec));
+ if (NULL == trigger_time)
+ {
+ NSPOL_DUMP_LOGERR ("alloc memory for timer failed.");
+ return false;
+ }
+
+ trigger_time->tv_sec = DUMP_HBT_CHK_INTERVAL;
+ trigger_time->tv_nsec = 0;
+
+ ptimer_info->interval = trigger_time;
+ ptimer_info->ptimer =
+ nsfw_timer_reg_timer (1, ptimer_info, check_dump_alive, *trigger_time);
+ return true;
+}
+
+NSTACK_STATIC inline u32
+copy_limit_buf (char *dst_buf, int dst_buf_len, char *src_buf,
+ u32 src_buf_len, u32 limit_len)
+{
+ if (src_buf_len < limit_len)
+ {
+ NSPOL_DUMP_LOGERR ("message too short] len=%d", src_buf_len);
+ return 0;
+ }
+
+ if (EOK != MEMCPY_S (dst_buf, dst_buf_len, src_buf, limit_len))
+ {
+ NSPOL_DUMP_LOGERR ("MEMCPY_S failed");
+ return 0;
+ }
+
+ return limit_len;
+}
+
+NSTACK_STATIC inline u32
+get_packet_buf (char *dst_buf, int dst_buf_len, char *src_buf,
+ u32 src_buf_len, u32 eth_head_len)
+{
+#define TCP_BUF_LEN (eth_head_len + IP_HEAD_LEN + TCP_HEAD_LEN)
+#define UDP_BUF_LEN (eth_head_len + IP_HEAD_LEN + UDP_HEAD_LEN)
+#define ICMP_BUF_LEN (eth_head_len + IP_HEAD_LEN + ICMP_HEAD_LEN)
+
+ if (NULL == dst_buf || NULL == src_buf)
+ {
+ return 0;
+ }
+
+ struct ip_hdr *ip_head = (struct ip_hdr *) (src_buf + eth_head_len);
+ if (ip_head->_proto == IP_PROTO_TCP)
+ {
+ return copy_limit_buf (dst_buf, dst_buf_len, src_buf, src_buf_len,
+ TCP_BUF_LEN);
+ }
+
+ if (ip_head->_proto == IP_PROTO_UDP)
+ {
+ return copy_limit_buf (dst_buf, dst_buf_len, src_buf, src_buf_len,
+ UDP_BUF_LEN);
+ }
+
+ if (ip_head->_proto == IP_PROTO_ICMP)
+ {
+ return copy_limit_buf (dst_buf, dst_buf_len, src_buf, src_buf_len,
+ ICMP_BUF_LEN);
+ }
+
+ if (EOK != MEMCPY_S (dst_buf, dst_buf_len, src_buf, src_buf_len))
+ {
+ NSPOL_DUMP_LOGERR ("MEMCPY_S failed");
+ return 0;
+ }
+
+ return src_buf_len;
+}
+
+NSTACK_STATIC int
+pack_msg_inout (void *dump_buf, char *msg_buf, u32 len, u16 direction,
+ void *para)
+{
+ (void) para;
+ dump_msg_info *pmsg = (dump_msg_info *) dump_buf;
+ if (!pmsg)
+ {
+ return 0;
+ }
+
+ pmsg->direction = direction;
+ struct timeval cur_time;
+ gettimeofday (&cur_time, NULL);
+ pmsg->dump_sec = cur_time.tv_sec;
+ pmsg->dump_usec = cur_time.tv_usec;
+
+ /* msg content can not be captured */
+ u32 real_len =
+ get_packet_buf (pmsg->buf, DUMP_MSG_SIZE, msg_buf, len, ETH_HEAD_LEN);
+ if (0 == real_len)
+ {
+ return 0;
+ }
+
+ pmsg->len = real_len;
+
+ return 1;
+}
+
+NSTACK_STATIC int
+pack_msg_loop (void *dump_buf, char *msg_buf, u32 len, u16 direction,
+ void *para)
+{
+ dump_msg_info *pmsg = (dump_msg_info *) dump_buf;
+ if (!pmsg)
+ {
+ return 0;
+ }
+ pmsg->direction = direction;
+ struct timeval cur_time;
+ gettimeofday (&cur_time, NULL);
+ pmsg->dump_sec = cur_time.tv_sec;
+ pmsg->dump_usec = cur_time.tv_usec;
+
+ eth_head pack_eth_head;
+ int retVal =
+ MEMCPY_S (pack_eth_head.dest_mac, MAC_ADDR_LEN, para, MAC_ADDR_LEN);
+ if (EOK != retVal)
+ {
+ NSPOL_DUMP_LOGERR ("MEMCPY_S failed]retVal=%d", retVal);
+ return 0;
+ }
+ retVal = MEMCPY_S (pack_eth_head.src_mac, MAC_ADDR_LEN, para, MAC_ADDR_LEN);
+ if (EOK != retVal)
+ {
+ NSPOL_DUMP_LOGERR ("MEMCPY_S failed]retVal=%d", retVal);
+ return 0;
+ }
+ pack_eth_head.eth_type = htons (PROTOCOL_IP);
+
+ retVal =
+ MEMCPY_S (pmsg->buf, DUMP_MSG_SIZE, &pack_eth_head, sizeof (eth_head));
+ if (EOK != retVal)
+ {
+ NSPOL_DUMP_LOGERR ("MEMCPY_S failed]retVal=%d", retVal);
+ return 0;
+ }
+
+ u32 buf_len = DUMP_MSG_SIZE - ETH_HEAD_LEN;
+
+ /* msg content can not be captured- Begin */
+ u32 real_len =
+ get_packet_buf (pmsg->buf + ETH_HEAD_LEN, buf_len, msg_buf, len, 0);
+ if (0 == real_len)
+ {
+ return 0;
+ }
+
+ pmsg->len = real_len + ETH_HEAD_LEN;
+
+ return 1;
+}
+
+NSTACK_STATIC void
+dump_enqueue (int task_idx, void *buf, u32 len, u16 direction,
+ pack_msg_fun pack_msg, void *para)
+{
+ mring_handle queue = (mring_handle *) g_dump_task[task_idx].task_queue;
+ mring_handle pool = (mring_handle *) g_dump_task[task_idx].task_pool;
+
+ void *msg = NULL;
+
+ if (nsfw_mem_ring_dequeue (pool, &msg) <= 0)
+ {
+ // such log may be too much if queue is empty
+ NSPOL_DUMP_LOGDBG ("get msg node from mem pool failed] pool=%p.", pool);
+ return;
+ }
+
+ if (NULL == msg)
+ {
+ NSPOL_DUMP_LOGWAR ("get NULL msg node from mem pool] pool=%p.", pool);
+ return;
+ }
+
+ if (!pack_msg (msg, buf, len, direction, para))
+ {
+ NSPOL_DUMP_LOGWAR ("get dump msg failed");
+ return;
+ }
+
+ if (nsfw_mem_ring_enqueue (queue, msg) < 0)
+ {
+ NSPOL_DUMP_LOGWAR ("dump mem ring enqueue failed] ring=%p.", queue);
+ }
+
+ return;
+}
+
+NSTACK_STATIC inline bool
+dump_enabled ()
+{
+ return (0 != g_dump_task_mask);
+}
+
+void
+ntcpdump (void *buf, u32 buf_len, u16 direction)
+{
+ u32 i;
+ if (!dump_enabled ())
+ {
+ return;
+ }
+
+ /* fix Dead-code type Codedex issue here */
+ for (i = 0; i < MAX_DUMP_TASK; i++)
+ {
+ if (g_dump_task[i].task_state)
+ {
+ dump_enqueue (i, buf, buf_len, direction, pack_msg_inout, NULL);
+ }
+ }
+}
+
+void
+ntcpdump_loop (void *buf, u32 buf_len, u16 direction, void *eth_addr)
+{
+ u32 i;
+
+ if (!dump_enabled ())
+ {
+ return;
+ }
+
+ /* fix Dead-code type Codedex issue here */
+ for (i = 0; i < MAX_DUMP_TASK; i++)
+ {
+ if (g_dump_task[i].task_state)
+ {
+ dump_enqueue (i, buf, buf_len, direction, pack_msg_loop, eth_addr);
+ }
+ }
+}
+
+// called by nStackMain
+bool
+dump_create_pool ()
+{
+ nsfw_mem_sppool pool_info;
+ if (EOK !=
+ MEMCPY_S (&pool_info.stname, sizeof (nsfw_mem_name),
+ &g_dump_mem_pool_info, sizeof (nsfw_mem_name)))
+ {
+ NSPOL_DUMP_LOGERR ("create dump mem pool failed, MEMCPY_S failed.");
+ return false;
+ }
+
+ pool_info.usnum = DUMP_MSG_NUM;
+ pool_info.useltsize = DUMP_MSG_SIZE + sizeof (dump_msg_info);
+ pool_info.isocket_id = NSFW_SOCKET_ANY;
+ pool_info.enmptype = NSFW_MRING_MPSC;
+
+ mring_handle pool = nsfw_mem_sp_create (&pool_info);
+ if (NULL == pool)
+ {
+ NSPOL_DUMP_LOGERR ("create dump mem pool failed, pool create failed.");
+ return false;
+ }
+
+ g_dump_task[0].task_pool = pool;
+
+ NSPOL_DUMP_LOGINF ("dump pool create success] pool=%p.", pool);
+
+ return true;
+}
+
+bool
+dump_create_ring ()
+{
+ nsfw_mem_mring ring_info;
+ if (EOK !=
+ MEMCPY_S (&ring_info.stname, sizeof (nsfw_mem_name),
+ &g_dump_mem_ring_info, sizeof (nsfw_mem_name)))
+ {
+ NSPOL_DUMP_LOGERR ("create dump mem ring failed, MEMCPY_S failed.");
+ return false;
+ }
+
+ ring_info.usnum = DUMP_MSG_NUM;
+ ring_info.isocket_id = NSFW_SOCKET_ANY;
+ ring_info.enmptype = NSFW_MRING_MPSC;
+
+ mring_handle ring = nsfw_mem_ring_create (&ring_info);
+ if (NULL == ring)
+ {
+ NSPOL_DUMP_LOGERR ("create dump mem ring failed, ring create failed.");
+ return false;
+ }
+
+ g_dump_task[0].task_queue = ring;
+
+ NSPOL_DUMP_LOGINF ("dump ring create success] ring=%p.", ring);
+
+ return true;
+}
+
+NSTACK_STATIC int
+on_dump_tool_req (nsfw_mgr_msg * req)
+{
+ i16 task_id = 0;
+ if (!req)
+ {
+ return -1;
+ }
+ if (req->src_proc_type != NSFW_PROC_TOOLS)
+ {
+ NSPOL_DUMP_LOGDBG
+ ("dump module receive invaild message] module type=%u.",
+ req->src_proc_type);
+ return -1;
+ }
+
+ if (req->msg_type != MGR_MSG_TOOL_TCPDUMP_REQ)
+ {
+ NSPOL_DUMP_LOGDBG ("dump module receive invaild message] msg type=%u.",
+ req->msg_type);
+ return -1;
+ }
+
+ nsfw_tool_dump_msg *dump_msg_req = GET_USER_MSG (nsfw_tool_dump_msg, req);
+
+ switch (dump_msg_req->op_type)
+ {
+ case START_DUMP_REQ:
+ task_id = get_dump_task (dump_msg_req);
+ break;
+
+ case STOP_DUMP_REQ:
+ task_id = close_dump_task (dump_msg_req->task_id);
+ break;
+
+ default:
+ task_id = -1;
+ }
+
+ nsfw_mgr_msg *rsp = nsfw_mgr_rsp_msg_alloc (req);
+ if (NULL == rsp)
+ {
+ NSPOL_DUMP_LOGDBG ("alloc response for dump request failed.");
+ return -1;
+ }
+
+ nsfw_tool_dump_msg *dump_msg_rsp = GET_USER_MSG (nsfw_tool_dump_msg, rsp);
+ dump_msg_rsp->op_type = dump_msg_req->op_type + DUMP_MSG_TYPE_RSP;
+ dump_msg_rsp->task_id = task_id;
+
+ nsfw_mgr_send_msg (rsp);
+ nsfw_mgr_msg_free (rsp);
+ return 0;
+
+}
+
+NSTACK_STATIC int
+on_dump_hbt_req (nsfw_mgr_msg * req)
+{
+ if (!req)
+ {
+ return -1;
+ }
+ if (req->src_proc_type != NSFW_PROC_TOOLS)
+ {
+ NSPOL_DUMP_LOGDBG
+ ("dump module receive invaild message] module type=%u.",
+ req->src_proc_type);
+ return -1;
+ }
+
+ if (req->msg_type != MGR_MSG_TOOL_HEART_BEAT)
+ {
+ NSPOL_DUMP_LOGDBG ("dump module receive invaild message] msg type=%u.",
+ req->msg_type);
+ return -1;
+ }
+
+ nsfw_tool_hbt *dump_hbt_req = GET_USER_MSG (nsfw_tool_hbt, req);
+
+ i16 task_id = dump_hbt_req->task_id;
+ if (task_id < 0 || task_id >= MAX_DUMP_TASK)
+ {
+ NSPOL_DUMP_LOGERR ("dump heart beat with invalid task id] task id=%d.",
+ task_id);
+ return -1;
+ }
+
+ if (0 == g_dump_task[task_id].task_state)
+ {
+ NSPOL_DUMP_LOGDBG
+ ("dump module receive heart beat but task not enabled] task id=%d.",
+ task_id);
+ return 0;
+ }
+
+ struct timespec cur_time;
+ GET_CUR_TIME (&cur_time); /*no need return value */
+
+ // update task alive time
+ g_dump_task[task_id].last_hbt_seq = dump_hbt_req->seq;
+ g_dump_task[task_id].last_hbt_sec = cur_time.tv_sec;
+
+ return 0;
+}
+
+NSTACK_STATIC int dump_tool_init (void *param);
+NSTACK_STATIC int
+dump_tool_init (void *param)
+{
+ u32 proc_type = (u32) ((long long) param);
+ NSPOL_DUMP_LOGINF ("dump module init] proc type=%d", proc_type);
+
+ switch (proc_type)
+ {
+ case NSFW_PROC_MAIN:
+ nsfw_mgr_reg_msg_fun (MGR_MSG_TOOL_TCPDUMP_REQ, on_dump_tool_req);
+ nsfw_mgr_reg_msg_fun (MGR_MSG_TOOL_HEART_BEAT, on_dump_hbt_req);
+ break;
+ default:
+ NSPOL_DUMP_LOGERR ("dump init with unknow module] proc type=%d",
+ proc_type);
+ return -1;
+ }
+
+ clear_dump_task ();
+
+ if (!dump_create_ring ())
+ {
+ return -1;
+ }
+
+ if (!dump_create_pool ())
+ {
+ return -1;
+ }
+
+ if (!dump_init_timer (&g_dump_timer))
+ {
+ return -1;
+ }
+
+ NSPOL_DUMP_LOGINF ("dump module init success.");
+ return 0;
+}
+
+/* *INDENT-OFF* */
+NSFW_MODULE_NAME (TCPDUMP_MODULE)
+NSFW_MODULE_PRIORITY (10)
+NSFW_MODULE_DEPENDS (NSTACK_DMM_MODULE)
+NSFW_MODULE_INIT (dump_tool_init)
+/* *INDENT-ON* */
diff --git a/stacks/lwip_stack/src/tools/dump_tool.h b/stacks/lwip_stack/src/tools/dump_tool.h
new file mode 100644
index 0000000..8c32523
--- /dev/null
+++ b/stacks/lwip_stack/src/tools/dump_tool.h
@@ -0,0 +1,81 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _DUMP_TOOL_H_
+#define _DUMP_TOOL_H_
+
+#define IP_PROTO_ICMP 1
+#define IP_PROTO_IGMP 2
+#define IP_PROTO_UDP 17
+#define IP_PROTO_UDPLITE 136
+#define IP_PROTO_TCP 6
+
+#ifndef MAC_ADDR_LEN
+#define MAC_ADDR_LEN 6
+#endif
+
+#ifndef IP_HEAD_LEN
+#define IP_HEAD_LEN 20
+#endif
+#ifndef TCP_HEAD_LEN
+#define TCP_HEAD_LEN 20
+#endif
+#ifndef UDP_HEAD_LEN
+#define UDP_HEAD_LEN 8
+#endif
+
+#ifndef ICMP_HEAD_LEN
+#define ICMP_HEAD_LEN 8
+#endif
+
+typedef struct _dump_task_info
+{
+ u16 task_state; // 0:off, 1:on
+ i16 task_id;
+ u32 task_keep_time;
+ u32 task_start_sec;
+ u32 last_hbt_seq;
+ u32 last_hbt_sec;
+ void *task_queue;
+ void *task_pool;
+} dump_task_info;
+
+typedef struct _dump_eth_head
+{
+ u8 dest_mac[MAC_ADDR_LEN];
+ u8 src_mac[MAC_ADDR_LEN];
+ u16 eth_type;
+} eth_head;
+
+#define ETH_HEAD_LEN sizeof(eth_head)
+
+struct ip_hdr
+{
+ u16 _v_hl_tos;
+ u16 _len;
+ u16 _id;
+ u16 _offset;
+ u8 _ttl;
+ u8 _proto;
+ u16 _chksum;
+ u32 src;
+ u32 dest;
+};
+
+typedef int (*pack_msg_fun) (void *dump_buf, char *msg_buf, u32 len,
+ u16 direction, void *para);
+
+#endif
diff --git a/stacks/lwip_stack/tools/CMakeLists.txt b/stacks/lwip_stack/tools/CMakeLists.txt
new file mode 100644
index 0000000..cfb5615
--- /dev/null
+++ b/stacks/lwip_stack/tools/CMakeLists.txt
@@ -0,0 +1,91 @@
+#########################################################################
+#
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+
+if(WITH_HAL_LIB)
+else()
+endif()
+SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${NSTACKTOOLS_PATH})
+LINK_DIRECTORIES(${LIB_PATH_SHARED} ${LIB_PATH_STATIC})
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/platform/SecureC/include/)
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g -fPIC -fPIE -pie -m64 -mssse3 -std=gnu89")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wshadow -Wfloat-equal -Wformat=2")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector -fstack-protector-all")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-z,relro,-z,now -Wl,--disable-new-dtags,--rpath,.")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-z,noexecstack -mcmodel=medium")
+
+INCLUDE_DIRECTORIES(
+ ../src/include/
+ ../../../thirdparty/glog/glog-0.3.4/src/
+ ../../SecureC/include/
+)
+
+#ADD_EXECUTABLE(narp narp.c)
+#ADD_EXECUTABLE(nnetstat nnetstat.c)
+
+ADD_EXECUTABLE(ntcpdump ntcpdump.c)
+if(WITH_SECUREC_LIB)
+TARGET_LINK_LIBRARIES(
+ ntcpdump
+ pthread
+ rt
+ securec
+ -Wl,--whole-archive
+ libjson-c.a
+ libglog.a
+ dmm_api
+ -Wl,--no-whole-archive,-lstdc++ -ldl
+ rte_eal
+ rte_mempool
+ rte_mbuf
+ rte_ring
+)
+else()
+TARGET_LINK_LIBRARIES(
+ ntcpdump
+ pthread
+ rt
+ -Wl,--whole-archive
+ libjson-c.a
+ libglog.a
+ dmm_api
+ -Wl,--no-whole-archive,-lstdc++ -ldl
+ rte_eal
+ rte_mempool
+ rte_mbuf
+ rte_ring
+)
+endif()
+
+if(WITH_SECUREC_LIB)
+ADD_DEPENDENCIES(ntcpdump JSON GLOG SECUREC DPDK)
+else()
+ADD_DEPENDENCIES(ntcpdump JSON GLOG DPDK)
+endif()
+
+
+ADD_EXECUTABLE(nping nping.c)
+
+if(WITH_SECUREC_LIB)
+ADD_DEPENDENCIES(nping SECUREC DPDK)
+else()
+ADD_DEPENDENCIES(nping DPDK)
+endif()
+
+if(WITH_SECUREC_LIB)
+TARGET_LINK_LIBRARIES(nping libnStackAPI.so securec -Wl,-rpath=. -lpthread -lrt -ldl)
+else()
+TARGET_LINK_LIBRARIES(nping libnStackAPI.so -Wl,-rpath=. -lpthread -lrt -ldl)
+endif()
diff --git a/stacks/lwip_stack/tools/nping.c b/stacks/lwip_stack/tools/nping.c
new file mode 100644
index 0000000..09e604f
--- /dev/null
+++ b/stacks/lwip_stack/tools/nping.c
@@ -0,0 +1,627 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <arpa/inet.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <errno.h>
+#include <time.h>
+#include <fcntl.h>
+#include <memory.h>
+#include <strings.h>
+#include <limits.h>
+#include <getopt.h>
+#include "nstack_securec.h"
+#include "tool_common.h"
+
+/*======== for global variables =======*/
+
+NSTACK_STATIC input_info g_input_info = { 0 };
+static stat_info g_stat_info = { 0 };
+
+static char *g_nping_short_options = "c:r:I:";
+
+int g_exit = 0;
+void
+user_exit (int sig)
+{
+ g_exit = 1;
+}
+
+NSTACK_STATIC inline double
+get_cost_time (struct timespec *pstart, struct timespec *pend)
+{
+ double sec = (double) (pend->tv_sec - pstart->tv_sec);
+ double nsec = (double) (pend->tv_nsec - pstart->tv_nsec);
+
+ return (sec * 1000 + (nsec / 1000000));
+}
+
+NSTACK_STATIC inline double
+get_lost_rate (unsigned int lost_count, unsigned int send_count)
+{
+ if (0 == send_count)
+ {
+ return 0;
+ }
+
+ return ((double) lost_count / send_count);
+}
+
+void
+print_stat (stat_info * info, const char *remote_ip)
+{
+ unsigned int send_count = info->send_seq;
+ unsigned int recv_count = info->recv_ok;
+ unsigned int lost_count = send_count - recv_count;
+ double lost_rate = 100 * get_lost_rate (lost_count, send_count);
+ double cost_time = get_cost_time (&info->start_time, &info->end_time);
+
+ printf ("\n------ %s ping statistics ------\n", remote_ip);
+
+ printf
+ ("%u packets transmitted, %u received, %.2f%% packet loss, time %.2fms\n",
+ send_count, recv_count, lost_rate, cost_time);
+
+ if (0 != recv_count)
+ {
+ double min_interval = info->min_interval;
+ double max_interval = info->max_interval;
+ double avg_interval = info->all_interval / recv_count;
+ printf ("rtt min/avg/max = %.3f/%.3f/%.3f ms\n", min_interval,
+ avg_interval, max_interval);
+ }
+}
+
+NSTACK_STATIC inline u16
+get_chksum (icmp_head * pmsg)
+{
+ int len = sizeof (icmp_head);
+ u32 sum = 0;
+ u16 *msg_stream = (u16 *) pmsg;
+ u16 check_sum = 0;
+
+ while (len > 1)
+ {
+ sum += *msg_stream;
+ len -= 2;
+ msg_stream++;
+ }
+
+ sum = (sum >> 16) + (sum & 0xFFFF);
+ sum += (sum >> 16);
+ check_sum = ~sum;
+
+ return check_sum;
+}
+
+#ifndef MAX_SHORT
+#define MAX_SHORT 0xFFFF
+#endif
+
+NSTACK_STATIC inline void
+code_icmp_req (icmp_head * pmsg, u32 send_seq, pid_t my_pid)
+{
+ struct timespec cur_time;
+
+ pmsg->icmp_type = ICMP_ECHO;
+ pmsg->icmp_code = 0;
+ pmsg->icmp_cksum = 0;
+ pmsg->icmp_seq = send_seq % (MAX_SHORT + 1);
+ pmsg->icmp_id = my_pid;
+ pmsg->timestamp = 0;
+
+ if (0 != clock_gettime (CLOCK_MONOTONIC, &cur_time))
+ {
+ printf ("Failed to get time, errno = %d\n", errno);
+ }
+
+ pmsg->icmp_sec = cur_time.tv_sec;
+ pmsg->icmp_nsec = cur_time.tv_nsec;
+
+ pmsg->icmp_cksum = get_chksum (pmsg);
+ return;
+}
+
+NSTACK_STATIC int
+send_icmp_req (int socket, pid_t my_pid, stat_info * stat,
+ struct sockaddr_in *remote_addr)
+{
+ int send_ret;
+ icmp_head icmp_req;
+
+ stat->send_seq++;
+ code_icmp_req (&icmp_req, stat->send_seq, my_pid);
+
+ send_ret = sendto (socket, &icmp_req, sizeof (icmp_head), 0,
+ (struct sockaddr *) remote_addr,
+ sizeof (struct sockaddr_in));
+
+ if (send_ret < 0)
+ {
+ printf ("send icmp request failed.\n");
+ return -1;
+ }
+
+ return send_ret;
+}
+
+NSTACK_STATIC inline double
+cal_interval (struct timespec *psend, struct timespec *precv,
+ stat_info * stat)
+{
+ double interval = get_cost_time (psend, precv);
+
+ stat->all_interval += interval;
+
+ if (interval < stat->min_interval)
+ {
+ stat->min_interval = interval;
+ }
+
+ if (interval > stat->max_interval)
+ {
+ stat->max_interval = interval;
+ }
+
+ return interval;
+}
+
+NSTACK_STATIC inline void
+print_info_on_reply (long send_sec, long send_usec, u32 send_seq,
+ stat_info * stat, struct sockaddr_in *dst_addr)
+{
+ struct timespec send_time;
+ struct timespec recv_time;
+ if (0 != clock_gettime (CLOCK_MONOTONIC, &recv_time))
+ {
+ printf ("Failed to get time, errno = %d\n", errno);
+ }
+
+ send_time.tv_sec = send_sec;
+ send_time.tv_nsec = send_usec;
+
+ double interval = cal_interval (&send_time, &recv_time, stat);
+ const char *remote_ip = inet_ntoa (dst_addr->sin_addr);
+ printf ("%lu bytes from %s: icmp_seq=%u, time=%.3f ms\n",
+ sizeof (icmp_head), remote_ip, send_seq % (MAX_SHORT + 1),
+ interval);
+}
+
+NSTACK_STATIC inline void
+print_info_on_no_reply (u32 send_seq, const char *remote_ip)
+{
+ printf ("No data from %s, icmp_seq=%u, Destination Host Unreachable\n",
+ remote_ip, send_seq);
+}
+
+static inline int
+expect_addr (int expect, int addr)
+{
+ return (expect == addr);
+}
+
+NSTACK_STATIC inline int
+parse_icmp_reply (char *buf, unsigned int buf_len, u32 my_pid, u32 send_seq,
+ stat_info * stat, struct sockaddr_in *dst_addr)
+{
+ unsigned int ip_head_len;
+ ip_head *recv_ip_head;
+ icmp_head *recv_icmp_head;
+
+ // parse all received ip package
+ while (buf_len > sizeof (ip_head))
+ {
+ recv_ip_head = (ip_head *) buf;
+
+ ip_head_len = recv_ip_head->ihl << 2;
+ recv_icmp_head = (icmp_head *) (buf + ip_head_len);
+ buf_len -= htons (recv_ip_head->tot_len);
+
+ if (!expect_addr (dst_addr->sin_addr.s_addr, recv_ip_head->local_ip))
+ {
+ return 0;
+ }
+
+ if ((recv_icmp_head->icmp_type == ICMP_REPLY)
+ && (recv_icmp_head->icmp_id == my_pid)
+ && (recv_icmp_head->icmp_seq == send_seq % (MAX_SHORT + 1)))
+ {
+ print_info_on_reply (recv_icmp_head->icmp_sec,
+ recv_icmp_head->icmp_nsec, send_seq, stat,
+ dst_addr);
+
+ return 1;
+ }
+
+ buf += ip_head_len;
+ }
+
+ return 0;
+}
+
+NSTACK_STATIC inline int
+recv_icmp_reply_ok (int socket, int my_pid, u32 send_seq, stat_info * stat,
+ struct sockaddr_in *dst_addr)
+{
+#define MAX_RECV_BUFF_SIZE (200 * sizeof(icmp_head))
+
+ struct sockaddr_in remote_addr;
+ unsigned int addr_len = sizeof (remote_addr);
+ char recv_buf[MAX_RECV_BUFF_SIZE];
+
+ int recv_ret = recvfrom (socket, recv_buf, MAX_RECV_BUFF_SIZE, 0,
+ (struct sockaddr *) &remote_addr, &addr_len);
+
+ if (recv_ret < 0)
+ {
+ return 0;
+ }
+
+ if (!parse_icmp_reply
+ (recv_buf, (unsigned int) recv_ret, my_pid, send_seq, stat, dst_addr))
+ {
+ return 0;
+ }
+
+ return 1;
+}
+
+// check recv msg in 2 us
+/* BEGIN: Added for PN:CODEDEX by l00351127, 2017/11/14 CID:50811*/
+NSTACK_STATIC void
+recv_icmp_reply (int socket, pid_t my_pid, input_info * input,
+ stat_info * stat, struct sockaddr_in *dst_addr)
+/* END: Added for PN:CODEDEX by l00351127, 2017/11/14 */
+{
+#define MAX_SLEEP_TIME (2 * US_TO_NS)
+#define MAX_WAIT_TIME (1000 * MS_TO_NS)
+
+ int recv_ok = 0;
+ int retry = 0;
+ long sleep_all = 0;
+ long sleep_time = 0;
+
+ u32 expect_seq = stat->send_seq;
+
+ while (retry < input->retry_count)
+ {
+ if (recv_icmp_reply_ok (socket, my_pid, expect_seq, stat, dst_addr))
+ {
+ recv_ok = 1;
+ stat->recv_ok++;
+ break;
+ }
+
+ sleep_all += MAX_SLEEP_TIME;
+ sys_sleep_ns (0, MAX_SLEEP_TIME);
+ retry++;
+ }
+
+ if (!recv_ok)
+ {
+ print_info_on_no_reply (expect_seq, input->dst_ip);
+ }
+
+ if (sleep_all < MAX_WAIT_TIME)
+ {
+ sleep_time = MAX_WAIT_TIME - sleep_all;
+ sys_sleep_ns (0, sleep_time);
+ }
+}
+
+NSTACK_STATIC inline int
+is_digit_nping (char *str)
+{
+ if (NULL == str || '\0' == str[0])
+ {
+ return 0;
+ }
+
+ while (*str)
+ {
+ if (*str > '9' || *str < '0')
+ {
+ return 0;
+ }
+
+ str++;
+ }
+
+ return 1;
+}
+
+#define MIN_IP_LEN_NPING 7 //the length of string ip addr x.x.x.x is 7, 4 numbers + 3 dots = 7
+#define MAX_IP_LEN_NPING 15 //the length of string ip addr xxx.xxx.xxx.xxx is 15, 12 numbers + 3 dots = 15
+
+NSTACK_STATIC inline int
+is_ip_addr_nping (char *param_addr)
+{
+ int ipseg1;
+ int ipseg2;
+ int ipseg3;
+ int ipseg4;
+
+ if (NULL == param_addr)
+ {
+ return 0;
+ }
+
+ size_t len = strlen (param_addr);
+ if (len < MIN_IP_LEN_NPING || len > MAX_IP_LEN_NPING) // valid ip MIN_IP_LEN=7, MAX_IP_LEN=15
+ {
+ printf ("Input IP format error.\n");
+ return 0;
+ }
+
+ if (SSCANF_S (param_addr, "%d.%d.%d.%d", &ipseg1, &ipseg2, &ipseg3, &ipseg4)
+ != 4)
+ {
+ return 0;
+ }
+
+ if ((ipseg1 & 0xffffff00)
+ || (ipseg2 & 0xffffff00)
+ || (ipseg3 & 0xffffff00) || (ipseg4 & 0xffffff00))
+ {
+ return 0;
+ }
+
+ return 1;
+}
+
+NSTACK_STATIC inline bool
+check_nping_input_para (input_info * input)
+{
+ if (input->send_count < 1)
+ {
+ return false;
+ }
+
+ if (input->retry_count < NPING_RETRY_COUNT
+ || input->retry_count > MAX_NPING_RETRY_COUNT)
+ {
+ return false;
+ }
+
+ if (0 == input->src_ip[0] || 0 == input->dst_ip[0])
+ {
+ return false;
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_nping_input_para (int argc, char **argv, input_info * input)
+{
+ int opt = 0;
+ bool arg_invalid = false;
+
+ if (argc < 2)
+ {
+ return false;
+ }
+
+ if (!is_ip_addr_nping (argv[1]))
+ {
+ return false;
+ }
+
+ /* CID 36687 (#1 of 2): Unchecked return value (CHECKED_RETURN) */
+ if (EOK != STRCPY_S (input->dst_ip, sizeof (input->dst_ip), argv[1]))
+ {
+ printf ("STRCPY_S failed.\n");
+ return false;
+ }
+
+ while (1)
+ {
+ opt = getopt (argc - 1, &argv[1], g_nping_short_options);
+ if (-1 == opt)
+ {
+ break;
+ }
+
+ switch (opt)
+ {
+ // for short options
+ case 'c':
+ input->send_count = atoi (optarg);
+ break;
+ case 'r':
+ input->retry_count = atoi (optarg);
+ break;
+ case 'I':
+ /* CID 36687 (#2 of 2): Unchecked return value (CHECKED_RETURN) */
+ if (!is_ip_addr_nping (optarg))
+ {
+ return false;
+ }
+ if (EOK != STRCPY_S (input->src_ip, sizeof (input->src_ip), optarg))
+ {
+ printf ("STRCPY_S failed.\n");
+ return false;
+ }
+ break;
+ default:
+ arg_invalid = true;
+ break;
+ }
+
+ if (arg_invalid)
+ {
+ return false;
+ }
+ }
+
+ if (!check_nping_input_para (input))
+ {
+ return false;
+ }
+
+ return true;
+}
+
+void
+print_help_nping ()
+{
+ printf
+ ("usage:nping destination [-c send_count -I src_addr -r retry_count]\n");
+ printf ("send count range:1-2147483647\n");
+ printf ("retry count range:1000-20000\n");
+}
+
+NSTACK_STATIC inline void
+init_input_info (input_info * input)
+{
+ if (EOK != MEMSET_S (input, sizeof (input_info), 0, sizeof (input_info)))
+ {
+ printf ("MEMSET_S failed.\n");
+ return;
+ }
+
+ input->send_count = 100000;
+ input->retry_count = NPING_RETRY_COUNT;
+}
+
+NSTACK_STATIC inline void
+init_stat_info (stat_info * stat)
+{
+ stat->max_interval = 0;
+ stat->min_interval = 0xFFFFFFFF;
+}
+
+#ifndef NSTACK_STATIC_CHECK
+int
+main (int argc, char *argv[])
+#else
+int
+nping_main (int argc, char *argv[])
+#endif
+{
+ struct sockaddr_in local_addr;
+ struct sockaddr_in remote_addr;
+ int send_ret;
+ int ret = -1;
+ int icmp_sock;
+
+ pid_t my_pid;
+
+ if (EOK !=
+ MEMSET_S (&local_addr, sizeof (local_addr), 0, sizeof (local_addr)))
+ {
+ printf ("MEMSET_S failed.\n");
+ return 0;
+ }
+ local_addr.sin_family = AF_INET;
+
+ init_input_info (&g_input_info);
+ init_stat_info (&g_stat_info);
+
+ if (!get_nping_input_para (argc, argv, &g_input_info))
+ {
+ print_help_nping ();
+ return 0;
+ }
+
+ if ((icmp_sock = socket (AF_INET, CUSTOM_SOCK_TYPE, IPPROTO_ICMP)) < 0)
+ {
+ printf ("create socket failed.\n");
+ return 0;
+ }
+
+ local_addr.sin_addr.s_addr = inet_addr (g_input_info.src_ip);
+
+ if (0 !=
+ bind (icmp_sock, (struct sockaddr *) &local_addr,
+ sizeof (struct sockaddr)))
+ {
+ printf ("bind failed, src ip %s\n", g_input_info.src_ip);
+ close (icmp_sock);
+ return 0;
+ }
+
+ int opt = 1;
+ ret = ioctl (icmp_sock, FIONBIO, &opt);
+ if (-1 == ret)
+ {
+ printf ("fcntl O_NONBLOCK fail\n");
+ close (icmp_sock);
+ return 0;
+ }
+
+ if (EOK !=
+ MEMSET_S (&remote_addr, sizeof (remote_addr), 0, sizeof (remote_addr)))
+ {
+ printf ("MEMSET_S failed.\n");
+ close (icmp_sock);
+ return 0;
+ }
+
+ remote_addr.sin_family = AF_INET;
+ remote_addr.sin_addr.s_addr = inet_addr (g_input_info.dst_ip);
+
+ my_pid = getpid ();
+ printf ("nping %s %lu bytes of data, pid:%d.\n", g_input_info.dst_ip,
+ sizeof (icmp_head), my_pid);
+
+ signal (SIGINT, user_exit);
+
+ int loop_count = 0;
+ if (0 != clock_gettime (CLOCK_MONOTONIC, &g_stat_info.start_time))
+ {
+ printf ("Failed to get time, errno = %d\n", errno);
+ }
+
+/* BEGIN: Added for PN:CODEDEX by l00351127, 2017/11/14 CID:50811*/
+ i32 send_count = g_input_info.send_count;
+/* END: Added for PN:CODEDEX by l00351127, 2017/11/14 */
+
+ while (!g_exit && (loop_count < send_count))
+ {
+ send_ret =
+ send_icmp_req (icmp_sock, my_pid, &g_stat_info, &remote_addr);
+ if (send_ret < 0)
+ {
+ break;
+ }
+
+ recv_icmp_reply (icmp_sock, my_pid, &g_input_info, &g_stat_info,
+ &remote_addr);
+
+ loop_count++;
+ }
+
+ close (icmp_sock);
+
+ if (0 != clock_gettime (CLOCK_MONOTONIC, &g_stat_info.end_time))
+ {
+ printf ("Failed to get time, errno = %d\n", errno);
+ }
+
+ print_stat (&g_stat_info, g_input_info.dst_ip);
+
+ return 0;
+}
diff --git a/stacks/lwip_stack/tools/ntcpdump.c b/stacks/lwip_stack/tools/ntcpdump.c
new file mode 100644
index 0000000..31a96bc
--- /dev/null
+++ b/stacks/lwip_stack/tools/ntcpdump.c
@@ -0,0 +1,1368 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <signal.h>
+#include <time.h>
+#include <malloc.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <unistd.h>
+#include "types.h"
+#include "nsfw_init.h"
+#include "nsfw_mem_api.h"
+#include "nsfw_fd_timer_api.h"
+#include "nsfw_maintain_api.h"
+#include "nstack_securec.h"
+
+#include "tool_common.h"
+
+NSTACK_STATIC struct option g_dump_long_options[] = {
+ {"host", 1, NULL, OPT_ARG_HOST},
+ {"lhost", 1, NULL, OPT_ARG_LOCAL_HOST},
+ {"rhost", 1, NULL, OPT_ARG_REMOTE_HOST},
+ {"port", 1, NULL, OPT_ARG_PORT},
+ {"lport", 1, NULL, OPT_ARG_LOCAL_PORT},
+ {"rport", 1, NULL, OPT_ARG_REMOTE_PORT},
+ {"mac", 1, NULL, OPT_ARG_MAC},
+ {"lmac", 1, NULL, OPT_ARG_LOCAL_MAC},
+ {"rmac", 1, NULL, OPT_ARG_REMOTE_MAC},
+ {0, 0, 0, 0}
+};
+
+static char *g_dump_short_options = "c:s:w:y:G:P:T:";
+
+NSTACK_STATIC FILE *g_dump_fp = NULL;
+static u32 g_dumped_packet = 0;
+NSTACK_STATIC u32 g_captured_packet = 0;
+static u32 g_filtered_packet = 0;
+
+NSTACK_STATIC bool g_dump_exit = 0;
+
+static dump_timer_info g_dump_hbt_timer;
+NSTACK_STATIC dump_condition g_dump_condition;
+static nsfw_mem_name g_dump_mem_ring_info =
+ { NSFW_SHMEM, NSFW_PROC_MAIN, DUMP_SHMEM_RIGN_NAME };
+static nsfw_mem_name g_dump_mem_pool_info =
+ { NSFW_SHMEM, NSFW_PROC_MAIN, DUMP_SHMEM_POOL_NAME };
+
+void
+dump_exit ()
+{
+ g_dump_exit = 1;
+}
+
+void
+print_help_ntcpdump ()
+{
+ printf ("usage:ntcpdump \n\
+ -c count \n\
+ -s len \n\
+ -w file \n\
+ -y l2_protocol \n\
+ -T l3_protocol \n\
+ -G dump_seconds \n\
+ -P in/out/inout \n\
+ --host/rhost/lhost ip_addr \n\
+ --port/rport/lport port \n\
+ --mac/rmac/lmac mac_addr\n");
+}
+
+bool
+is_digit_ntcpdump (char *str, size_t src_len)
+{
+ size_t count = 0;
+
+ if (NULL == str || 0 == *str)
+ {
+ return FALSE;
+ }
+
+ while (*str)
+ {
+ if (*str > '9' || *str < '0')
+ {
+ return false;
+ }
+
+ str++;
+ count++;
+ }
+
+ if (count > src_len)
+ {
+ return false;
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+is_ip_addr (const char *addr, ip_addr_bits * addr_info)
+{
+ u32 ip1;
+ u32 ip2;
+ u32 ip3;
+ u32 ip4;
+
+ if (SSCANF_S (addr, "%d.%d.%d.%d", &ip1, &ip2, &ip3, &ip4) != 4)
+ {
+ return false;
+ }
+
+ if ((ip1 & 0xffffff00) || (ip2 & 0xffffff00) || (ip3 & 0xffffff00)
+ || (ip4 & 0xffffff00))
+ {
+ return false;
+ }
+
+ addr_info->addr_bits1 = ip1;
+ addr_info->addr_bits2 = ip2;
+ addr_info->addr_bits3 = ip3;
+ addr_info->addr_bits4 = ip4;
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_ip_addr (const char *addr, u32 * ip_addr)
+{
+ ip_addr_bits addr_info;
+ if (!is_ip_addr (addr, &addr_info))
+ {
+ return false;
+ }
+
+ *ip_addr = ((addr_info.addr_bits1 & 0xFF)
+ | (addr_info.addr_bits2 & 0xFF) << 8
+ | (addr_info.addr_bits3 & 0xFF) << 16
+ | (addr_info.addr_bits4 & 0xFF) << 24);
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_dump_port (const char *pport, u16 * port)
+{
+ int user_port;
+
+ if (!is_digit_ntcpdump ((char *) pport, MAX_PORT_STR_LEN))
+ {
+ return false;
+ }
+
+ user_port = atoi (pport);
+ if (user_port < 1024 || user_port > 65535)
+ {
+ return false;
+ }
+
+ *port = (unsigned short) user_port;
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_dump_len (char *plen, u32 * limit_len)
+{
+ if (!is_digit_ntcpdump (plen, MAX_INTEGER_STR_LEN))
+ {
+ return false;
+ }
+
+ *limit_len = atoi (plen);
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_mac_addr (const char *opt_value, char *mac_addr)
+{
+ /* avoid coredump when opt_value is NULL */
+ if (NULL == opt_value)
+ {
+ return false;
+ }
+
+ size_t org_len = strlen (opt_value);
+ if (org_len != MAC_ADDR_STR_LEN)
+ {
+ return false;
+ }
+
+ u32 tmp_mac[MAC_ADDR_LEN];
+
+ if (6 != SSCANF_S (opt_value, "%x:%x:%x:%x:%x:%x",
+ &tmp_mac[0],
+ &tmp_mac[1],
+ &tmp_mac[2], &tmp_mac[3], &tmp_mac[4], &tmp_mac[5]))
+ {
+ return false;
+ }
+
+ int i = 0;
+ for (; i < MAC_ADDR_LEN; i++)
+ {
+ if (tmp_mac[i] > 0xFF)
+ {
+ // 01:02:03:04:5:1FF
+ return false;
+ }
+
+ mac_addr[i] = tmp_mac[i];
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+check_file_name (const char *file_name)
+{
+ if (0 == access (file_name, F_OK))
+ {
+ printf ("dump file exist, file name=%s.\n", file_name);
+ return false;
+ }
+ return true;
+}
+
+NSTACK_STATIC inline u16
+get_para_direction (const char *para)
+{
+ if (0 == strcasecmp (para, "out"))
+ {
+ return DUMP_SEND;
+ }
+
+ if (0 == strcasecmp (para, "in"))
+ {
+ return DUMP_RECV;
+ }
+
+ if (0 == strcasecmp (para, "inout"))
+ {
+ return DUMP_SEND_RECV;
+ }
+
+ return INVALID_DIRECTION;
+}
+
+NSTACK_STATIC inline u16
+get_para_l2_protocol (const char *para)
+{
+ if (0 == strcasecmp (para, "arp"))
+ {
+ return PROTOCOL_ARP;
+ }
+
+ if (0 == strcasecmp (para, "rarp"))
+ {
+ return PROTOCOL_RARP;
+ }
+
+ if (0 == strcasecmp (para, "ip"))
+ {
+ return PROTOCOL_IP;
+ }
+
+ if (0 == strcasecmp (para, "oam"))
+ {
+ return PROTOCOL_OAM_LACP;
+ }
+
+ if (0 == strcasecmp (para, "lacp"))
+ {
+ return PROTOCOL_OAM_LACP;
+ }
+
+ return INVALID_L2_PROTOCOL;
+}
+
+NSTACK_STATIC inline u16
+get_para_l3_protocol (const char *para)
+{
+ if (0 == strcasecmp (para, "tcp"))
+ {
+ return PROTOCOL_TCP;
+ }
+
+ if (0 == strcasecmp (para, "udp"))
+ {
+ return PROTOCOL_UDP;
+ }
+
+ if (0 == strcasecmp (para, "icmp"))
+ {
+ return PROTOCOL_ICMP;
+ }
+
+ return INVALID_L3_PROTOCOL;
+}
+
+NSTACK_STATIC bool
+parse_long_options (int opt, const char *long_opt_arg, int optindex,
+ dump_condition * filter_info)
+{
+ switch (opt)
+ {
+ case OPT_ARG_HOST:
+ if (!get_ip_addr (long_opt_arg, &filter_info->ip_addr))
+ {
+ printf ("invalid ip addr, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->ip_set_flag |= COND_OR_SET;
+ break;
+ case OPT_ARG_LOCAL_HOST:
+ if (!get_ip_addr (long_opt_arg, &filter_info->local_ip))
+ {
+ printf ("invalid ip addr, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->ip_set_flag |= COND_LOCAL_SET;
+ break;
+ case OPT_ARG_REMOTE_HOST:
+ if (!get_ip_addr (long_opt_arg, &filter_info->remote_ip))
+ {
+ printf ("invalid ip addr, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->ip_set_flag |= COND_REMOTE_SET;
+ break;
+ case OPT_ARG_PORT:
+ if (!get_dump_port (long_opt_arg, &filter_info->port))
+ {
+ printf ("invalid port, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->port_set_flag |= COND_OR_SET;
+ break;
+ case OPT_ARG_LOCAL_PORT:
+ if (!get_dump_port (long_opt_arg, &filter_info->local_port))
+ {
+ printf ("invalid port, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->port_set_flag |= COND_LOCAL_SET;
+ break;
+ case OPT_ARG_REMOTE_PORT:
+ if (!get_dump_port (long_opt_arg, &filter_info->remote_port))
+ {
+ printf ("invalid port, optindex=%d, port=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->port_set_flag |= COND_REMOTE_SET;
+ break;
+ case OPT_ARG_MAC:
+ if (!get_mac_addr (long_opt_arg, filter_info->mac_addr))
+ {
+ printf ("invalid mac addr, optindex=%d, mac=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->mac_set_flag |= COND_OR_SET;
+ break;
+ case OPT_ARG_LOCAL_MAC:
+ if (!get_mac_addr (long_opt_arg, filter_info->local_mac))
+ {
+ printf ("invalid mac addr, optindex=%d, mac=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->mac_set_flag |= COND_LOCAL_SET;
+ break;
+ case OPT_ARG_REMOTE_MAC:
+ if (!get_mac_addr (long_opt_arg, filter_info->remote_mac))
+ {
+ printf ("invalid mac addr, optindex=%d, mac=%s.\n", optindex,
+ long_opt_arg);
+ return false;
+ }
+ filter_info->mac_set_flag |= COND_REMOTE_SET;
+ break;
+ default:
+ printf ("unknow arg, optindex=%d, arg=%s.\n", optindex, long_opt_arg);
+ return false;
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+condition_valid (dump_condition * condition)
+{
+ // check direction
+ if (INVALID_DIRECTION == condition->direction)
+ {
+ printf ("direction invalid.\n");
+ return false;
+ }
+
+ // check l2 protocol
+ if (INVALID_L2_PROTOCOL == condition->l2_protocol)
+ {
+ printf ("L2 protocol invalid.\n");
+ return false;
+ }
+
+ // check l3 protocol
+ if (INVALID_L3_PROTOCOL == condition->l3_protocol)
+ {
+ printf ("L3 protocol invalid.\n");
+ return false;
+ }
+
+ // check ip
+ if (condition->ip_set_flag > 0x4)
+ {
+ printf ("IP options invalid.\n");
+ return false;
+ }
+
+ // check port
+ if (condition->port_set_flag > 0x4)
+ {
+ printf ("Port options invalid.\n");
+ return false;
+ }
+
+ // check mac
+ if (condition->mac_set_flag > 0x4)
+ {
+ printf ("MAC options invalid.\n");
+ return false;
+ }
+
+ if (condition->dump_time > MAX_DUMP_TIME
+ || condition->dump_time < MIN_DUMP_TIME)
+ {
+ printf ("dump time invalid.\n");
+ return false;
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline bool
+get_dump_condition (int argc, char **argv, dump_condition * filter_info)
+{
+ int opt = 0;
+ int opt_index = 0;
+ bool arg_invalid = false;
+ filter_info->has_condition = 0;
+
+ if (argc < 2)
+ {
+ // dump all package
+ return true;
+ }
+
+ while (1)
+ {
+ opt =
+ getopt_long (argc, argv, g_dump_short_options, g_dump_long_options,
+ &opt_index);
+ if (-1 == opt)
+ {
+ break;
+ }
+
+ switch (opt)
+ {
+ // for short options
+ case 'c':
+ filter_info->dump_count = atoi (optarg);
+ break;
+ case 's':
+ if (!get_dump_len (optarg, &filter_info->limit_len))
+ {
+ printf ("length invalid, optindex=%d, arg=%s.\n", opt_index,
+ optarg);
+ arg_invalid = true;
+ }
+ break;
+ case 'w':
+ if (!check_file_name (optarg))
+ {
+ printf ("invalid file name, optindex=%d, arg=%s.\n", opt_index,
+ optarg);
+ arg_invalid = true;
+ }
+ else
+ {
+ filter_info->dump_file_name = optarg;
+ }
+ break;
+ case 'y':
+ filter_info->l2_protocol = get_para_l2_protocol (optarg);
+ break;
+ case 'G':
+ filter_info->dump_time = atoi (optarg);
+ break;
+ case 'P':
+ filter_info->direction = get_para_direction (optarg);
+ break;
+ case 'T':
+ filter_info->l3_protocol = get_para_l3_protocol (optarg);
+ break;
+ case '?':
+ arg_invalid = true;
+ break;
+ // for long options
+ default:
+ if (!parse_long_options (opt, optarg, opt_index, filter_info))
+ {
+ arg_invalid = true;
+ }
+ break;
+ }
+
+ if (arg_invalid)
+ {
+ print_help_ntcpdump ();
+ return false;
+ }
+
+ filter_info->has_condition = 1;
+ }
+
+ if (!condition_valid (filter_info))
+ {
+ filter_info->has_condition = 0;
+ return false;
+ }
+
+ return true;
+}
+
+NSTACK_STATIC inline void
+open_file ()
+{
+ if (NULL == g_dump_condition.dump_file_name)
+ {
+ return;
+ }
+
+ g_dump_fp = fopen (g_dump_condition.dump_file_name, "w+");
+ if (NULL == g_dump_fp)
+ {
+ printf ("open file %s failed\n", g_dump_condition.dump_file_name);
+ }
+}
+
+NSTACK_STATIC inline void
+close_file ()
+{
+ if (NULL != g_dump_fp)
+ {
+ fclose (g_dump_fp);
+ g_dump_fp = NULL;
+ }
+}
+
+NSTACK_STATIC inline void
+write_file_head (FILE * fp)
+{
+ dump_file_head file_head;
+ file_head.magic = 0xA1B2C3D4;
+ file_head.major_ver = 2; // 0x0200;
+ file_head.minor_ver = 4; // 0x0400;
+ file_head.area = 0;
+ file_head.time_stamp = 0;
+ file_head.max_pack_size = 0x0000FFFF; // 0xFFFF0000;
+ file_head.link_type = 1; //0x01000000;
+
+ if (fwrite (&file_head, sizeof (dump_file_head), 1, fp) != 1)
+ {
+ return;
+ }
+
+ fflush (fp);
+}
+
+NSTACK_STATIC inline void
+write_packet (parse_msg_info * pmsg, FILE * fp)
+{
+ packet_head pack_head;
+ dump_msg_info *org_msg = (dump_msg_info *) pmsg->org_msg;
+ pack_head.sec = org_msg->dump_sec;
+ pack_head.usec = org_msg->dump_usec;
+ pack_head.save_len =
+ (u32) nstack_min (org_msg->len, g_dump_condition.limit_len);
+ pack_head.org_len = org_msg->len;
+
+ if (fwrite (&pack_head, sizeof (packet_head), 1, fp) != 1)
+ {
+ // log error
+ return;
+ }
+
+ if (fwrite (org_msg->buf, pack_head.save_len, 1, fp) != 1)
+ {
+ // log error
+ return;
+ }
+
+ fflush (fp);
+ return;
+}
+
+#define EMPTY(x) (0 == (x))
+#define EQUAL(x, y) ((x) == (y))
+
+#define STR_EMPTY(str) (0 == str[0])
+#define STR_EQUAL(str1, str2, len) (0 == memcmp(str1, str2, len))
+
+#define MATCH(cond, info, field) \
+ (EQUAL(cond->field, info->field))
+
+#define MATCH_MORE(cond, field, info, field1, field2) \
+ (EQUAL(cond->field, info->field1) || EQUAL(cond->field, info->field2))
+
+#define MATCH_STR(cond, info, field, len) \
+ (STR_EQUAL(cond->field, info->field, len))
+
+#define MATCH_STR_MORE(cond, field, info, field1, field2, len) \
+ (STR_EQUAL(cond->field, info->field1, len) || STR_EQUAL(cond->field, info->field2, len))
+
+NSTACK_STATIC inline bool
+ip_match (dump_condition * condition, parse_msg_info * msg_info)
+{
+ bool ret = false;
+ switch (condition->ip_set_flag)
+ {
+ case COND_NOT_SET:
+ ret = true;
+ break;
+ case COND_LOCAL_SET:
+ if (MATCH (condition, msg_info, local_ip))
+ {
+ ret = true;
+ }
+ break;
+ case COND_REMOTE_SET:
+ if (MATCH (condition, msg_info, remote_ip))
+ {
+ ret = true;
+ }
+ break;
+ case COND_AND_SET:
+ if (MATCH_MORE (condition, local_ip, msg_info, local_ip, remote_ip)
+ && MATCH_MORE (condition, remote_ip, msg_info, local_ip, remote_ip))
+ {
+ ret = true;
+ }
+ break;
+ case COND_OR_SET:
+ if (MATCH_MORE (condition, ip_addr, msg_info, local_ip, remote_ip))
+ {
+ ret = true;
+ }
+ break;
+ default:
+ break;
+ }
+
+ return ret;
+}
+
+NSTACK_STATIC inline bool
+port_match (dump_condition * condition, parse_msg_info * msg_info)
+{
+ bool ret = false;
+ switch (condition->port_set_flag)
+ {
+ case COND_NOT_SET:
+ ret = true;
+ break;
+ case COND_LOCAL_SET:
+ if (MATCH (condition, msg_info, local_port))
+ {
+ ret = true;
+ }
+ break;
+ case COND_REMOTE_SET:
+ if (MATCH (condition, msg_info, remote_port))
+ {
+ ret = true;
+ }
+ break;
+ case COND_AND_SET:
+ if (MATCH (condition, msg_info, local_port)
+ && MATCH (condition, msg_info, remote_port))
+ {
+ ret = true;
+ }
+ break;
+ case COND_OR_SET:
+ if (MATCH_MORE (condition, port, msg_info, local_port, remote_port))
+ {
+ ret = true;
+ }
+ break;
+ default:
+ break;
+ }
+
+ return ret;
+}
+
+NSTACK_STATIC inline bool
+mac_match (dump_condition * condition, parse_msg_info * msg_info)
+{
+ bool ret = false;
+ switch (condition->mac_set_flag)
+ {
+ case COND_NOT_SET:
+ ret = true;
+ break;
+ case COND_LOCAL_SET:
+ if (MATCH_STR (condition, msg_info, local_mac, MAC_ADDR_LEN))
+ {
+ ret = true;
+ }
+ break;
+ case COND_REMOTE_SET:
+ if (MATCH_STR (condition, msg_info, remote_mac, MAC_ADDR_LEN))
+ {
+ ret = true;
+ }
+ break;
+ case COND_AND_SET:
+ if ((MATCH_STR_MORE
+ (condition, local_mac, msg_info, local_mac, remote_mac,
+ MAC_ADDR_LEN)
+ && MATCH_STR_MORE (condition, remote_mac, msg_info, local_mac,
+ remote_mac, MAC_ADDR_LEN)))
+ {
+ ret = true;
+ }
+ break;
+ case COND_OR_SET:
+ if (MATCH_STR_MORE
+ (condition, mac_addr, msg_info, local_mac, remote_mac,
+ MAC_ADDR_LEN))
+ {
+ ret = true;
+ }
+ break;
+ default:
+ break;
+ }
+
+ return ret;
+}
+
+NSTACK_STATIC inline bool
+filter_by_condition (dump_condition * condition, parse_msg_info * msg_info)
+{
+ dump_msg_info *org_msg = (dump_msg_info *) msg_info->org_msg;
+ if (0 == condition->has_condition)
+ {
+ return false;
+ }
+
+ // direction
+ if (!(condition->direction & org_msg->direction))
+ {
+ return true;
+ }
+
+ // l2_protocol
+ if ((0 != condition->l2_protocol)
+ && !MATCH (condition, msg_info, l2_protocol))
+ {
+ return true;
+ }
+
+ // l3_protocol
+ if ((0 != condition->l3_protocol)
+ && !MATCH (condition, msg_info, l3_protocol))
+ {
+ return true;
+ }
+
+ // ip
+ if (!ip_match (condition, msg_info))
+ {
+ return true;
+ }
+
+ // port
+ if (!port_match (condition, msg_info))
+ {
+ return true;
+ }
+
+ // mac
+ if (!mac_match (condition, msg_info))
+ {
+ return true;
+ }
+
+ return false;
+}
+
+NSTACK_STATIC inline char *
+get_l2_protocol_desc (u16 l2_protocol)
+{
+ switch (l2_protocol)
+ {
+ case PROTOCOL_IP:
+ return "IP";
+ case PROTOCOL_ARP:
+ return "ARP";
+ case PROTOCOL_RARP:
+ return "RARP";
+ case PROTOCOL_OAM_LACP:
+ return "OAM/LACP";
+ default:
+ return "unknown";
+ }
+}
+
+NSTACK_STATIC inline char *
+get_l3_protocol_desc (u16 l3_protocol)
+{
+ switch (l3_protocol)
+ {
+ case PROTOCOL_ICMP:
+ return "ICMP";
+ case PROTOCOL_TCP:
+ return "TCP";
+ case PROTOCOL_UDP:
+ return "UDP";
+ default:
+ return "unknown";
+ }
+}
+
+NSTACK_STATIC inline void
+get_ip_str (char *pip_addr, u32 ip_addr_len, u32 ip)
+{
+ int retVal;
+ retVal = SPRINTF_S (pip_addr, ip_addr_len, "%d.%d.%d.%d",
+ ip & 0x000000FF,
+ (ip & 0x0000FF00) >> 8,
+ (ip & 0x00FF0000) >> 16, (ip & 0xFF000000) >> 24);
+ if (-1 == retVal)
+ {
+ printf ("get_ip_str:SPRINTF_S failed %d.\n", retVal);
+ }
+}
+
+NSTACK_STATIC inline void
+print_packet (parse_msg_info * msg_info, u32 seq)
+{
+ char str_local_ip[IP_ADDR_LEN];
+ char str_remote_ip[IP_ADDR_LEN];
+ get_ip_str (str_local_ip, sizeof (str_local_ip), msg_info->local_ip);
+ get_ip_str (str_remote_ip, sizeof (str_remote_ip), msg_info->remote_ip);
+
+ dump_msg_info *org_msg = (dump_msg_info *) msg_info->org_msg;
+
+ printf ("%-6d %-6d:%6d %-8s %-8s %-16s %-16s %-10d %-10d %-8d\n",
+ seq,
+ org_msg->dump_sec, org_msg->dump_usec,
+ get_l2_protocol_desc (msg_info->l2_protocol),
+ get_l3_protocol_desc (msg_info->l3_protocol),
+ str_local_ip,
+ str_remote_ip,
+ msg_info->local_port, msg_info->remote_port, org_msg->len);
+}
+
+void
+print_head ()
+{
+ if (NULL != g_dump_fp)
+ {
+ write_file_head (g_dump_fp);
+ }
+ else
+ {
+ printf ("ntcpdump start listening:\n");
+ printf ("%-6s %-18s %-8s %-8s %-16s %-16s %-10s %-10s %-8s\n",
+ "Frame", "sec:usec", "L2", "L3", "Src IP", "Dest IP",
+ "Src Port", "Dest Port", "Length");
+ }
+}
+
+void
+register_dump_signal ()
+{
+ signal (SIGINT, dump_exit);
+}
+
+NSTACK_STATIC inline void
+init_parse_msg_info (parse_msg_info * info)
+{
+ int retVal =
+ MEMSET_S (info, sizeof (parse_msg_info), 0, sizeof (parse_msg_info));
+ if (EOK != retVal)
+ {
+ printf ("MEMSET_S failed.\n");
+ }
+}
+
+NSTACK_STATIC inline void
+parse_msg (dump_msg_info * msg, parse_msg_info * info)
+{
+ init_parse_msg_info (info);
+
+ info->org_msg = msg;
+
+ char *pmsg = msg->buf;
+ u32 len = msg->len;
+ /* BEGIN: Added for PN:CODEDEX by l00351127, 2017/11/14 CID:50886 */
+ if (len < MAC_ADDR_LEN + MAC_ADDR_LEN + sizeof (u16))
+ {
+ return;
+ }
+ /* END: Added for PN:CODEDEX by l00351127, 2017/11/14 */
+
+ // get mac addr
+ if (EOK !=
+ MEMCPY_S (info->remote_mac, sizeof (info->remote_mac), pmsg,
+ MAC_ADDR_LEN))
+ {
+ return;
+ }
+
+ pmsg += MAC_ADDR_LEN;
+ len -= MAC_ADDR_LEN;
+
+ if (EOK !=
+ MEMCPY_S (info->local_mac, sizeof (info->local_mac), pmsg,
+ MAC_ADDR_LEN))
+ {
+ return;
+ }
+
+ pmsg += MAC_ADDR_LEN;
+ len -= MAC_ADDR_LEN;
+
+ info->l2_protocol = htons (*(u16 *) pmsg);
+ pmsg += sizeof (u16);
+ len -= sizeof (u16);
+
+ if (PROTOCOL_IP != info->l2_protocol)
+ {
+ return;
+ }
+
+ ip_head *p_ip_head = (ip_head *) pmsg;
+ if (len < p_ip_head->ihl)
+ {
+ return;
+ }
+
+ info->local_ip = p_ip_head->local_ip;
+ info->remote_ip = p_ip_head->remote_ip;
+ info->l3_protocol = p_ip_head->protocol;
+
+ pmsg += p_ip_head->ihl * sizeof (u32);
+
+ if (PROTOCOL_TCP == info->l3_protocol)
+ {
+ tcp_head *p_tcp_head = (tcp_head *) pmsg;
+ info->local_port = htons (p_tcp_head->src_port);
+ info->remote_port = htons (p_tcp_head->dst_port);
+ return;
+ }
+
+ if (PROTOCOL_UDP == info->l3_protocol)
+ {
+ udp_head *p_udp_head = (udp_head *) pmsg;
+ info->local_port = htons (p_udp_head->src_port);
+ info->remote_port = htons (p_udp_head->dst_port);
+ return;
+ }
+
+ return;
+}
+
+NSTACK_STATIC inline bool
+time_expired (struct timespec * start_time, u32 work_sec)
+{
+#define TIME_EXPIRE_CHECK_COUNT 1000
+
+ static u32 loop_count = 0;
+ loop_count++;
+
+ if (0 != loop_count % TIME_EXPIRE_CHECK_COUNT)
+ {
+ return false;
+ }
+
+ struct timespec cur_time;
+ GET_CUR_TIME (&cur_time);
+
+ if (cur_time.tv_sec - start_time->tv_sec > work_sec)
+ {
+ return true;
+ }
+
+ return false;
+}
+
+NSTACK_STATIC void
+dump_packet (parse_msg_info * msg)
+{
+ g_dumped_packet++;
+ if (!g_dump_fp)
+ {
+ print_packet (msg, g_dumped_packet);
+ return;
+ }
+
+ write_packet (msg, g_dump_fp);
+}
+
+NSTACK_STATIC void
+dump_msg (mring_handle dump_ring, mring_handle dump_pool,
+ dump_condition * condition, struct timespec *start_time)
+{
+ u32 dump_count = 0;
+ open_file ();
+
+ print_head ();
+
+ void *msg = NULL;
+ while (!g_dump_exit
+ && (dump_count < condition->dump_count)
+ && !time_expired (start_time, condition->dump_time))
+ {
+ if (nsfw_mem_ring_dequeue (dump_ring, &msg) <= 0)
+ {
+ sys_sleep_ns (0, 10000);
+ continue;
+ }
+
+ if (NULL == msg)
+ {
+ continue;
+ }
+
+ parse_msg_info msg_info;
+ parse_msg (msg, &msg_info);
+
+ g_captured_packet++;
+ if (!condition->has_condition)
+ {
+ dump_packet (&msg_info);
+ dump_count++;
+ nsfw_mem_ring_enqueue (dump_pool, msg);
+ continue;
+ }
+
+ if (filter_by_condition (condition, &msg_info))
+ {
+ g_filtered_packet++;
+ nsfw_mem_ring_enqueue (dump_pool, msg);
+ continue;
+ }
+
+ dump_packet (&msg_info);
+ dump_count++;
+ nsfw_mem_ring_enqueue (dump_pool, msg);
+ }
+
+ close_file ();
+}
+
+mring_handle
+dump_get_mem_ring ()
+{
+ return nsfw_mem_ring_lookup (&g_dump_mem_ring_info);
+}
+
+mring_handle
+dump_get_mem_pool ()
+{
+ return nsfw_mem_sp_lookup (&g_dump_mem_pool_info);
+}
+
+NSTACK_STATIC void
+dump_clear_mem (mring_handle ring, mring_handle pool)
+{
+ void *msg = NULL;
+ while (nsfw_mem_ring_dequeue (ring, &msg) > 0)
+ {
+ nsfw_mem_ring_enqueue (pool, msg);
+ sys_sleep_ns (0, 1000);
+ }
+}
+
+/* BEGIN: Added for PN:CODEDEX by l00351127, 2017/11/14 CID:50859*/
+i16
+dump_send_req (u16 op_type, i16 task_id, u32 task_keep_time)
+/* END: Added for PN:CODEDEX by l00351127, 2017/11/14 */
+{
+ nsfw_mgr_msg *req =
+ (nsfw_mgr_msg *) nsfw_mgr_msg_alloc (MGR_MSG_TOOL_TCPDUMP_REQ,
+ NSFW_PROC_MAIN);
+ if (NULL == req)
+ {
+ printf ("all message for getting instance id failed.\n");
+ return -1;
+ }
+
+ nsfw_tool_dump_msg *req_body = GET_USER_MSG (nsfw_tool_dump_msg, req);
+ req_body->op_type = op_type;
+ req_body->task_id = task_id;
+ req_body->task_keep_time = task_keep_time;
+
+ nsfw_mgr_msg *rsp = nsfw_mgr_null_rspmsg_alloc ();
+ if (NULL == rsp)
+ {
+ printf ("alloc rsp message for getting memory failed.\n");
+ nsfw_mgr_msg_free (req);
+ return -1;
+ }
+
+ if (!nsfw_mgr_send_req_wait_rsp (req, rsp))
+ {
+ printf ("request memory can not get response.\n");
+ nsfw_mgr_msg_free (req);
+ nsfw_mgr_msg_free (rsp);
+ return -1;
+ }
+
+ if (rsp->src_proc_type != NSFW_PROC_MAIN
+ || rsp->dst_proc_type != NSFW_PROC_TOOLS)
+ {
+ printf
+ ("dump get wrong response, src or dst proc type error,src proc type=%u, dst proc type=%u.\n",
+ rsp->src_proc_type, rsp->dst_proc_type);
+ nsfw_mgr_msg_free (req);
+ nsfw_mgr_msg_free (rsp);
+ return -1;
+ }
+
+ if (rsp->msg_type != MGR_MSG_TOOL_TCPDUMP_RSP)
+ {
+ printf ("dump get wrong response, msg type error, msg type=%d.\n",
+ rsp->msg_type);
+ nsfw_mgr_msg_free (req);
+ nsfw_mgr_msg_free (rsp);
+ return -1;
+ }
+
+ nsfw_tool_dump_msg *rsp_body = GET_USER_MSG (nsfw_tool_dump_msg, rsp);
+
+/* BEGIN: Added for PN:CODEDEX by l00351127, 2017/11/14 CID:50859*/
+ i16 new_task_id = rsp_body->task_id;
+/* END: Added for PN:CODEDEX by l00351127, 2017/11/14 */
+
+ nsfw_mgr_msg_free (req);
+ nsfw_mgr_msg_free (rsp);
+
+ return new_task_id;
+}
+
+i16
+start_dump_task (u32 task_keep_time)
+{
+ return dump_send_req (START_DUMP_REQ, -1, task_keep_time);
+}
+
+i16
+stop_dump_task (i16 task_id)
+{
+ return dump_send_req (STOP_DUMP_REQ, task_id, 0);
+}
+
+NSTACK_STATIC void
+init_dump_condition (dump_condition * condition)
+{
+ if (EOK !=
+ MEMSET_S (condition, sizeof (dump_condition), 0,
+ sizeof (dump_condition)))
+ {
+ printf ("MEMSET_S failed.\n");
+ }
+ condition->limit_len = DUMP_MSG_SIZE;
+ condition->dump_time = DEFAULT_DUMP_TIME;
+ condition->direction = 3;
+ condition->dump_count = DEFAULT_DUMP_COUNT;
+}
+
+NSTACK_STATIC inline bool
+send_hbt_req (u32 seq, i16 task_id)
+{
+ nsfw_mgr_msg *req =
+ (nsfw_mgr_msg *) nsfw_mgr_msg_alloc (MGR_MSG_TOOL_HEART_BEAT,
+ NSFW_PROC_MAIN);
+ if (NULL == req)
+ {
+ printf ("all message for getting instance id failed.\n");
+ return false;
+ }
+
+ nsfw_tool_hbt *req_body = GET_USER_MSG (nsfw_tool_hbt, req);
+ req_body->seq = seq;
+ req_body->task_id = task_id;
+
+ if (!nsfw_mgr_send_msg (req))
+ {
+ printf ("request memory can not get response.\n");
+ }
+
+ nsfw_mgr_msg_free (req);
+
+ return true;
+}
+
+NSTACK_STATIC bool
+on_send_hbt_req (u32 timer_type, void *data)
+{
+ dump_timer_info *ptimer_info = (dump_timer_info *) data;
+ // send heartbeat
+
+ send_hbt_req (ptimer_info->seq, ptimer_info->task_id);
+ ptimer_info->seq++;
+
+ ptimer_info->ptimer =
+ nsfw_timer_reg_timer (DUMP_HBT_TIMER, ptimer_info, on_send_hbt_req,
+ *(struct timespec *) (ptimer_info->interval));
+ return true;
+}
+
+NSTACK_STATIC bool
+start_dump_hbt (dump_timer_info * ptimer_info, i16 task_id)
+{
+ struct timespec *time_interval =
+ (struct timespec *) malloc (sizeof (struct timespec));
+ if (NULL == time_interval)
+ {
+ return false;
+ }
+
+ time_interval->tv_sec = DUMP_HBT_INTERVAL;
+ time_interval->tv_nsec = 0;
+
+ ptimer_info->interval = time_interval;
+ ptimer_info->seq = 1;
+ ptimer_info->task_id = task_id;
+
+ ptimer_info->ptimer =
+ nsfw_timer_reg_timer (DUMP_HBT_TIMER, ptimer_info, on_send_hbt_req,
+ *time_interval);
+
+ return true;
+}
+
+NSTACK_STATIC bool
+stop_dump_hbt (dump_timer_info * ptimer_info)
+{
+ free (ptimer_info->interval);
+ /* fix "SET_NULL_AFTER_FREE" type codedex issue */
+ ptimer_info->interval = NULL;
+ nsfw_timer_rmv_timer (ptimer_info->ptimer);
+ return true;
+}
+
+#ifndef NSTACK_STATIC_CHECK
+int
+main (int argc, char *argv[])
+#else
+int
+ntcpdump_main (int argc, char *argv[])
+#endif
+{
+ register_dump_signal ();
+
+ init_dump_condition (&g_dump_condition);
+ if (!get_dump_condition (argc, argv, &g_dump_condition))
+ {
+ printf ("dump exit because of input invalid.\n");
+ return INPUT_INVALID;
+ }
+
+ printf ("parse filter condition ok.\n");
+
+ fw_poc_type proc_type = NSFW_PROC_TOOLS;
+ nsfw_mem_para stinfo = { 0 };
+ stinfo.iargsnum = 0;
+ stinfo.pargs = NULL;
+ stinfo.enflag = proc_type;
+ nstack_framework_setModuleParam (NSFW_MEM_MGR_MODULE, &stinfo);
+ nstack_framework_setModuleParam (NSFW_MGR_COM_MODULE,
+ (void *) ((u64) proc_type));
+ nstack_framework_setModuleParam (NSFW_TIMER_MODULE,
+ (void *) ((u64) proc_type));
+
+ if (0 != nstack_framework_init ())
+ {
+ printf ("dump init failed.\n");
+ return FRAMEWORK_INIT_FAILED;
+ }
+
+ mring_handle dump_mem_pool = dump_get_mem_pool ();
+ if (NULL == dump_mem_pool)
+ {
+ printf ("dump init mem pool failed.\n");
+ return MEMPOOL_INIT_FAILED;
+ }
+
+ mring_handle dump_mem_ring = dump_get_mem_ring ();
+ if (NULL == dump_mem_ring)
+ {
+ printf ("dump init mem ring failed.\n");
+ return MEMRING_INIT_FAILED;
+ }
+
+ // initialize queue first
+ dump_clear_mem (dump_mem_ring, dump_mem_pool);
+
+ i16 task_id = start_dump_task (g_dump_condition.dump_time);
+ if (task_id < 0 || task_id > MAX_DUMP_TASK)
+ {
+ printf ("start dump task failed.\n");
+ return START_TASK_FAILED;
+ }
+
+ if (!start_dump_hbt (&g_dump_hbt_timer, task_id))
+ {
+ printf ("start dump heart beat timer failed.\n");
+ return START_TIMER_FAILED;
+ }
+
+ struct timespec dump_start_time;
+ GET_CUR_TIME (&dump_start_time);
+ dump_msg (dump_mem_ring, dump_mem_pool, &g_dump_condition,
+ &dump_start_time);
+
+ i16 new_task_id = stop_dump_task (task_id);
+ if (new_task_id != task_id)
+ {
+ printf ("stop dump task failed.\n");
+ }
+ /* modify deadcode type codedex issue */
+ (void) stop_dump_hbt (&g_dump_hbt_timer);
+
+ printf ("dump complete.\n");
+ printf ("captured packets=%u.\n", g_captured_packet);
+ printf ("dumped packets=%u.\n", g_dumped_packet);
+ printf ("filtered packets=%u.\n", g_filtered_packet);
+
+ return 0;
+}
diff --git a/stacks/lwip_stack/tools/tool_common.h b/stacks/lwip_stack/tools/tool_common.h
new file mode 100644
index 0000000..6d3526b
--- /dev/null
+++ b/stacks/lwip_stack/tools/tool_common.h
@@ -0,0 +1,243 @@
+/*
+*
+* Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at:
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef _TOOL_COMMON_H_
+#define _TOOL_COMMON_H_
+
+#include <time.h>
+#include "types.h"
+
+#ifndef NSTACK_STATIC
+#ifndef NSTACK_STATIC_CHECK
+#define NSTACK_STATIC static
+#else
+#define NSTACK_STATIC
+#endif
+#endif
+
+#ifndef IP_ADDR_LEN
+#define IP_ADDR_LEN 16
+#endif
+
+#ifndef MAC_ADDR_LEN
+#define MAC_ADDR_LEN 6
+#endif
+
+#ifndef MAC_ADDR_STR_LEN
+#define MAC_ADDR_STR_LEN 17
+#endif
+
+#define ICMP_ECHO 8
+#define ICMP_REPLY 0
+#define MS_TO_NS 1000000
+#define US_TO_NS 1000
+#define NPING_RETRY_COUNT 1000
+#define MAX_NPING_RETRY_COUNT 20000
+
+#define MAX_PORT_STR_LEN 5
+#define MAX_IP_STR_LEN 15
+#define MAX_INTEGER_STR_LEN 10
+
+#define DUMP_HBT_TIMER 1
+
+#define INVALID_DIRECTION 0xFFFF
+#define DEFAULT_DUMP_COUNT 1000
+
+#ifndef CUSTOM_SOCK_TYPE
+#define CUSTOM_SOCK_TYPE 0xF001
+#endif
+
+enum DUMP_ERR_CODE
+{
+ RET_OK = 0,
+ INPUT_INVALID = 1,
+ FRAMEWORK_INIT_FAILED = 2,
+ MEMPOOL_INIT_FAILED = 3,
+ MEMRING_INIT_FAILED = 4,
+ START_TASK_FAILED = 5,
+ START_TIMER_FAILED = 6,
+ UNKNOW_ERR
+};
+
+enum COND_LOCAL_REMOTE_SET
+{
+ COND_NOT_SET = 0,
+ COND_REMOTE_SET = 0x1,
+ COND_LOCAL_SET = 0x2,
+ COND_AND_SET = 0x3,
+ COND_OR_SET = 0x4
+};
+
+enum DUMP_OPT_ARG
+{
+ OPT_ARG_HOST = 256,
+ OPT_ARG_LOCAL_HOST,
+ OPT_ARG_REMOTE_HOST,
+ OPT_ARG_PORT,
+ OPT_ARG_LOCAL_PORT,
+ OPT_ARG_REMOTE_PORT,
+ OPT_ARG_MAC,
+ OPT_ARG_LOCAL_MAC,
+ OPT_ARG_REMOTE_MAC,
+ OPT_ARG_INVALID
+};
+
+typedef struct _ip_head
+{
+ u8 ihl:4;
+ u8 version:4;
+ u8 tos;
+ u16 tot_len;
+ u16 id;
+ u16 frag_off;
+ u8 ttl;
+ u8 protocol;
+ u16 chk_sum;
+ u32 local_ip;
+ u32 remote_ip;
+} ip_head;
+
+typedef struct _tcp_head
+{
+ u16 src_port;
+ u16 dst_port;
+ u32 seq_no;
+ u32 ack_no;
+} tcp_head;
+
+typedef struct _udp_head
+{
+ u16 src_port;
+ u16 dst_port;
+ u16 uhl;
+ u16 chk_sum;
+} udp_head;
+
+typedef struct _dump_file_head
+{
+ u32 magic;
+ u16 major_ver;
+ u16 minor_ver;
+ u32 area;
+ u32 time_stamp;
+ u32 max_pack_size;
+ u32 link_type;
+} dump_file_head;
+
+typedef struct _packet_head
+{
+ u32 sec;
+ u32 usec;
+ u32 save_len;
+ u32 org_len;
+} packet_head;
+
+typedef struct _ip_addr_bits
+{
+ u32 addr_bits1;
+ u32 addr_bits2;
+ u32 addr_bits3;
+ u32 addr_bits4;
+} ip_addr_bits;
+
+typedef struct _parse_msg_info
+{
+ u16 l2_protocol; // ARP/IP/OAM/LACP
+ u16 l3_protocol; // TCP/UDP/ICMP
+ u16 local_port;
+ u16 remote_port;
+ u32 local_ip;
+ u32 remote_ip;
+ char local_mac[MAC_ADDR_LEN + 1];
+ char remote_mac[MAC_ADDR_LEN + 1];
+
+ void *org_msg;
+} parse_msg_info;
+
+typedef struct _dump_condition
+{
+ bool has_condition;
+ u32 dump_count;
+ u32 dump_time;
+ u32 limit_len;
+ u16 direction; //1:send 2:recv 3:send-recv
+ u16 l2_protocol; // ARP/IP/OAM/LACP
+ u16 l3_protocol; // TCP/UDP/ICMP
+ u16 port_set_flag;
+ u16 port;
+ u16 local_port;
+ u16 remote_port;
+ u16 ip_set_flag;
+ u32 ip_addr;
+ u32 local_ip;
+ u32 remote_ip;
+ u16 mac_set_flag;
+ char mac_addr[MAC_ADDR_LEN + 1];
+ char local_mac[MAC_ADDR_LEN + 1];
+ char remote_mac[MAC_ADDR_LEN + 1];
+
+ char *dump_file_name;
+} dump_condition;
+
+typedef struct _icmp_head
+{
+ u8 icmp_type;
+ u8 icmp_code;
+ u16 icmp_cksum;
+ u16 icmp_id;
+ u16 icmp_seq;
+ u32 timestamp;
+
+ long icmp_sec;
+ long icmp_nsec;
+} icmp_head;
+
+typedef struct _ning_input_info
+{
+ i32 send_count; // total send req
+ i32 retry_count; // retry count for 1 req
+ char src_ip[IP_ADDR_LEN];
+ char dst_ip[IP_ADDR_LEN];
+} input_info;
+
+typedef struct _nping_stat_info
+{
+ u32 send_seq;
+ u32 recv_ok;
+ double all_interval;
+ double min_interval;
+ double max_interval;
+ struct timespec start_time;
+ struct timespec end_time;
+} stat_info;
+
+#ifndef sys_sleep_ns
+#define sys_sleep_ns(_s, _ns)\
+{ \
+ if (_s >= 0 && _ns >= 0) \
+ { \
+ struct timespec delay, remain; \
+ delay.tv_sec = _s; \
+ delay.tv_nsec = _ns; \
+ while (nanosleep(&delay, &remain) < 0) \
+ { \
+ delay = remain; \
+ } \
+ } \
+}
+#endif
+
+#endif
diff --git a/stacks/lwip_stack/vagrant/Vagrantfile b/stacks/lwip_stack/vagrant/Vagrantfile
new file mode 100644
index 0000000..3cfb883
--- /dev/null
+++ b/stacks/lwip_stack/vagrant/Vagrantfile
@@ -0,0 +1,63 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+Vagrant.configure(2) do |config|
+
+ # Pick the right distro and bootstrap, default is ubuntu1604
+ distro = ( ENV['DMM_VAGRANT_DISTRO'] || "ubuntu")
+ if distro == 'centos7'
+ config.vm.box = "puppetlabs/centos-7.2-64-nocm"
+ else
+ config.vm.box = "fdio-csit/ubuntu-14.04.4_2016-05-25_1.0"
+ end
+ config.vm.box_check_update = false
+
+ # Create DMM client and server VM's
+ config.vm.define "dmm-stackx-server" do |server|
+ server.vm.provision :shell, :path => File.join(File.dirname(__FILE__),"install_prereq.sh")
+ server.vm.provision :shell, :path => File.join(File.dirname(__FILE__),"build.sh"), :args => "/DMM vagrant"
+ end
+# config.vm.define "dmm-stackx-client" do |client|
+# client.vm.provision :shell, :path => File.join(File.dirname(__FILE__),"install_prereq.sh")
+# client.vm.provision :shell, :path => File.join(File.dirname(__FILE__),"build.sh"), :args => "/dmm vagrant"
+# end
+
+
+ # vagrant-cachier caches apt/yum etc to speed subsequent
+ # vagrant up
+ # to enable, run
+ # vagrant plugin install vagrant-cachier
+ #
+ if Vagrant.has_plugin?("vagrant-cachier")
+ config.cache.scope = :box
+ end
+
+ # Define some physical ports for your VMs to be used by DPDK
+ nics = (ENV['DMM_VAGRANT_NICS'] || "2").to_i(10)
+ for i in 1..nics
+ config.vm.network "private_network", type: "dhcp"
+ # config.vm.network "private_network", ip: "172.28.128.200"
+ # config.vm.network "private_network", ip: "172.28.128.201"
+ end
+
+ # use http proxy if avaiable
+ if ENV['http_proxy'] && Vagrant.has_plugin?("vagrant-proxyconf")
+ config.proxy.http = ENV['http_proxy']
+ config.proxy.https = ENV['https_proxy']
+ config.proxy.no_proxy = "localhost,127.0.0.1"
+ end
+
+ vmcpu=(ENV['DMM_VAGRANT_VMCPU'] || 4)
+ vmram=(ENV['DMM_VAGRANT_VMRAM'] || 4096)
+
+ config.ssh.forward_agent = true
+ config.ssh.forward_x11 = true
+
+ config.vm.provider "virtualbox" do |vb|
+ vb.customize ["modifyvm", :id, "--ioapic", "on"]
+ vb.memory = "#{vmram}"
+ vb.cpus = "#{vmcpu}"
+
+ config.vm.synced_folder "../../../", "/DMM", type: "rsync"
+ end
+end
diff --git a/stacks/lwip_stack/vagrant/build.sh b/stacks/lwip_stack/vagrant/build.sh
new file mode 100644
index 0000000..f189474
--- /dev/null
+++ b/stacks/lwip_stack/vagrant/build.sh
@@ -0,0 +1,267 @@
+#########################################################################
+# Copyright (c) 2018 Huawei Technologies Co.,Ltd.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#########################################################################
+#!/bin/bash -x
+
+set -x
+
+TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
+log_file="/tmp/build_log.txt-$TIMESTAMP"
+exec 1> >(tee -a "$log_file") 2>&1
+
+# Get Command Line arguements if present
+TEMP_DIR=$1
+if [ "x$1" != "x" ]; then
+ TEMP_DIR=$1
+ DMM_BUILD_DIR=${TEMP_DIR}/build
+ DPDK_BUILD_SCRIPT_DIR=${DMM_BUILD_DIR}/../scripts
+ LWIP_BUILD_DIR=${TEMP_DIR}/stacks/lwip_stack/build/
+else
+ TEMP_DIR=`dirname $(readlink -f $0)`/..
+ DMM_BUILD_DIR=${TEMP_DIR}/../../build
+ DPDK_BUILD_SCRIPT_DIR=${DMM_BUILD_DIR}/../scripts
+ LWIP_BUILD_DIR=${TEMP_DIR}/build/
+fi
+
+echo 0:$0
+echo 1:$1
+echo 2:$2
+echo TEMP_DIR: $TEMP_DIR
+echo DMM_BUILD_DIR: $DMM_BUILD_DIR
+echo DPDK_BUILD_SCRIPT_DIR: $DPDK_BUILD_SCRIPT_DIR
+echo LWIP_BUILD_DIR: $LWIP_BUILD_DIR
+
+OS_ID=$(grep '^ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+OS_VERSION_ID=$(grep '^VERSION_ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+KERNEL_OS=`uname -o`
+KERNEL_MACHINE=`uname -m`
+KERNEL_RELEASE=`uname -r`
+KERNEL_VERSION=`uname -v`
+
+echo KERNEL_OS: $KERNEL_OS
+echo KERNEL_MACHINE: $KERNEL_MACHINE
+echo KERNEL_RELEASE: $KERNEL_RELEASE
+echo KERNEL_VERSION: $KERNEL_VERSION
+echo OS_ID: $OS_ID
+echo OS_VERSION_ID: $OS_ID
+
+#DPDK download path
+DPDK_DOWNLOAD_PATH=/tmp/dpdk
+
+#dpdk installation path
+DPDK_INSTALL_PATH=/usr
+
+#set and check the environment for Linux
+if [ "$OS_ID" == "ubuntu" ]; then
+ export DEBIAN_FRONTEND=noninteractive
+ export DEBCONF_NONINTERACTIVE_SEEN=true
+
+ APT_OPTS="--assume-yes --no-install-suggests --no-install-recommends -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\""
+ sudo apt-get update ${APT_OPTS}
+ sudo DEBIAN_FRONTEND=noninteractive apt-get install -yq git cmake gcc g++ automake libtool wget lsof lshw pciutils net-tools tcpdump libpcre3 libpcre3-dev zlibc zlib1g zlib1g-dev vim ethtool
+elif [ "$OS_ID" == "debian" ]; then
+ echo "not tested for debian and exit"
+ exit 1
+ export DEBIAN_FRONTEND=noninteractive
+ export DEBCONF_NONINTERACTIVE_SEEN=true
+
+ APT_OPTS="--assume-yes --no-install-suggests --no-install-recommends -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\""
+ sudo apt-get update ${APT_OPTS}
+ sudo DEBIAN_FRONTEND=noninteractive apt-get install -yq git cmake gcc g++ automake libtool wget lsof lshw pciutils net-tools tcpdump libpcre3 libpcre3-dev zlibc zlib1g zlib1g-dev vim
+elif [ "$OS_ID" == "centos" ]; then
+ sudo yum install -y git cmake gcc g++ automake libtool wget lsof lshw pciutils net-tools tcpdump vim sudo yum-utils pcre-devel zlib-devel
+elif [ "$OS_ID" == "opensuse" ]; then
+ echo "not tested for opensuse and exit"
+ exit 1
+ sudo yum install -y git cmake gcc g++ automake libtool wget lsof lshw pciutils net-tools tcpdump vim sudo yum-utils pcre-devel zlib-devel
+fi
+
+#DPDK will be having dependancy on linux headers
+if [ "$OS_ID" == "ubuntu" ]; then
+ sudo apt-get -y install git build-essential linux-headers-`uname -r`
+ sudo apt-get -y install libnuma-dev
+elif [ "$OS_ID" == "debian" ]; then
+ sudo apt-get -y install git build-essential linux-headers-`uname -r`
+elif [ "$OS_ID" == "centos" ]; then
+ sudo yum groupinstall -y "Development Tools"
+ sudo yum install -y kernel-headers
+ sudo yum install -y numactl-devel
+elif [ "$OS_ID" == "opensuse" ]; then
+ sudo yum groupinstall -y "Development Tools"
+ sudo yum install -y kernel-headers
+fi
+#===========build DPDK================
+
+if [ ! -d /usr/include/dpdk ] || [ ! -d /usr/share/dpdk ] || [ ! -d /usr/lib/modules/4.4.0-31-generic/extra/dpdk ]; then
+ mkdir -p $DPDK_DOWNLOAD_PATH
+
+ cd $DPDK_DOWNLOAD_PATH
+ wget -N https://fast.dpdk.org/rel/dpdk-18.02.tar.xz --no-check-certificate
+ tar xvf dpdk-18.02.tar.xz
+ cd dpdk-18.02/
+
+
+ sed -i 's!CONFIG_RTE_EXEC_ENV=.*!CONFIG_RTE_EXEC_ENV=y!1' config/common_base
+ sed -i 's!CONFIG_RTE_BUILD_SHARED_LIB=.*!CONFIG_RTE_BUILD_SHARED_LIB=y!1' config/common_base
+ sed -i 's!CONFIG_RTE_LIBRTE_EAL=.*!CONFIG_RTE_LIBRTE_EAL=y!1' config/common_base
+ sed -i 's!CONFIG_RTE_EAL_PMD_PATH=.*!CONFIG_RTE_EAL_PMD_PATH="/tmp/dpdk/drivers/"!1' config/common_base
+
+ sudo make install T=x86_64-native-linuxapp-gcc DESTDIR=${DPDK_INSTALL_PATH} -j 4
+
+ mkdir -p /tmp/dpdk/drivers/
+ cp -f /usr/lib/librte_mempool_ring.so /tmp/dpdk/drivers/
+fi
+#===========build DMM=================
+echo "DMM build started....."
+
+cd $DMM_BUILD_DIR
+ldconfig
+rm -rf *
+cmake ..
+make -j 8
+if [ $? -eq 0 ]; then
+ echo "DMM build is SUCCESS"
+else
+ echo "DMM build has FAILED"
+ exit 1
+fi
+echo "DMM build finished....."
+
+#===========build Stackpool===========
+echo "Stackpool build started....."
+cd $LWIP_BUILD_DIR
+cmake ..
+make -j 8
+if [ $? -eq 0 ]; then
+ echo "Stackpool build is SUCCESS"
+else
+ echo "Stackpool build has FAILED"
+ exit 1
+fi
+echo "Stackpool build finished....."
+
+#===========check running env =================
+hugepagesize=$(cat /proc/meminfo | grep Hugepagesize | awk -F " " {'print$2'})
+if [ "$hugepagesize" == "2048" ]; then
+ pages=1536
+elif [ "$hugepagesize" == "1048576" ]; then
+ pages=3
+fi
+sudo sysctl -w vm.nr_hugepages=$pages
+HUGEPAGES=`sysctl -n vm.nr_hugepages`
+if [ $HUGEPAGES != $pages ]; then
+ echo "ERROR: Unable to get $pages hugepages, only got $HUGEPAGES. Cannot finish."
+ exit
+fi
+
+
+hugepageTotal=$(cat /proc/meminfo | grep -c "HugePages_Total: 0")
+if [ $hugepageTotal -ne 0 ]; then
+ echo "HugePages_Total is zero"
+ exit
+fi
+
+hugepageFree=$(cat /proc/meminfo | grep -c "HugePages_Free: 0")
+if [ $hugepageFree -ne 0 ]; then
+ echo "HugePages_Free is zero"
+ exit
+fi
+
+hugepageSize=$(cat /proc/meminfo | grep -c "Hugepagesize: 0 kB")
+if [ $hugepageSize -ne 0 ]; then
+ echo "Hugepagesize is zero"
+ exit
+fi
+
+
+sudo mkdir /mnt/nstackhuge -p
+if [ "$hugepagesize" == "2048" ]; then
+sudo mount -t hugetlbfs -o pagesize=2M none /mnt/nstackhuge/
+elif [ "$hugepagesize" == "1048576" ]; then
+ sudo mount -t hugetlbfs -o pagesize=1G none /mnt/nstackhuge/
+fi
+sudo mkdir -p /var/run/ip_module/
+
+export LD_LIBRARY_PATH=$LIB_PATH
+export NSTACK_LOG_ON=DBG
+
+
+
+#===========set environment===========
+if [ "$OS_ID" == "centos" ]; then
+ ifaddress1=$(ifconfig enp0s8 | grep 'inet' | cut -d: -f2 | awk '{print $2}')
+ echo $ifaddress1
+ ifaddresscut=$(ifconfig enp0s8 | grep 'inet' | head -n 1 | awk -F " " '{print $2}' | awk -F "." '{print $1"."$2"."$3}')
+ echo $ifaddresscut
+ ifmac=$(ifconfig enp0s8 | grep 'ether' | awk -F " " '{print $2}')
+ echo $ifmac
+elif [ "$OS_ID" == "ubuntu" ]; then
+ ifaddress1=$(ifconfig eth1 | grep 'inet' | head -n 1 | cut -d: -f2 | awk '{print $1}')
+ echo $ifaddress1
+ ifaddresscut=$(ifconfig eth1 | grep 'inet' | head -n 1 | cut -d: -f2 | awk '{print $1}' | awk -F "." '{print $1"."$2"."$3}')
+ echo $ifaddresscut
+ ifmac=$(ifconfig eth1 | grep 'HWaddr' | awk -F " " '{print $5}')
+ echo $ifmac
+fi
+
+cd $LWIP_BUILD_DIR/../
+bash ./release_tar.sh
+cd nStackServer/script
+sed -i 's!/root/dpdk/dpdk-18.02!'$DPDK_DOWNLOAD_PATH'/dpdk-18.02!1' nstack_var.sh
+
+cd ../
+cp ./configure/*.json bin/
+cd bin
+
+if [ "$OS_ID" == "centos" ]; then
+ sed -i 's!eth7!enp0s8!1' ip_data.json
+elif [ "$OS_ID" == "ubuntu" ]; then
+ sed -i 's!eth7!eth1!1' ip_data.json
+fi
+
+sed -i 's!00:54:32:19:3d:19!'$ifmac'!1' ip_data.json
+sed -i 's!192.168.1.207!'$ifaddress1'!1' ip_data.json
+
+sed -i 's!192.168.1.1!'$ifaddresscut'.0!1' network_data_tonStack.json
+sed -i 's!192.168.1.254!'$ifaddresscut'.1!1' network_data_tonStack.json
+sed -i 's!192.168.1.098!'$ifaddresscut'.5!1' network_data_tonStack.json
+sed -i 's!192.168.1.209!'$ifaddresscut'.254!1' network_data_tonStack.json
+sed -i 's!192.168.1.0!'$ifaddresscut'.0!1' network_data_tonStack.json
+sed -i 's!192.168.1.254!'$ifaddresscut'.1!1' network_data_tonStack.json
+
+if [ "$OS_ID" == "centos" ]; then
+ sed -i 's!eth7!enp0s8!1' network_data_tonStack.json
+elif [ "$OS_ID" == "ubuntu" ]; then
+ sed -i 's!eth7!eth1!1' network_data_tonStack.json
+fi
+sed -i 's!eth7!enp0s8!1' network_data_tonStack.json
+
+cd $DMM_BUILD_DIR/../release/bin
+cp -r . ../../stacks/lwip_stack/app_test
+cd $DMM_BUILD_DIR/../stacks/lwip_stack/app_test
+cp -r ../app_conf/*.json .
+
+sed -i 's!192.168.1.1!'$ifaddresscut'.0!1' rd_config.json
+
+cd $LWIP_BUILD_DIR/../nStackServer
+bash -x ./stop_nstack.sh
+bash -x ./start_nstack.sh
+check_result=$(pgrep nStackMain)
+if [ -z "$check_result" ]; then
+ echo "nStackMain execute failed"
+ exit 1
+else
+ echo "nStackMain execute successful"
+ exit 0
+fi
diff --git a/stacks/lwip_stack/vagrant/env.sh b/stacks/lwip_stack/vagrant/env.sh
new file mode 100644
index 0000000..96ad346
--- /dev/null
+++ b/stacks/lwip_stack/vagrant/env.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+
+#export DMM_VAGRANT_DISTRO="ubuntu1604"
+export DMM_VAGRANT_DISTRO="centos7"
+export DMM_VAGRANT_NICS=2
+export DMM_VAGRANT_VMCPU=4
+export DMM_VAGRANT_VMRAM=8192
diff --git a/stacks/lwip_stack/vagrant/install_prereq.sh b/stacks/lwip_stack/vagrant/install_prereq.sh
new file mode 100644
index 0000000..ae8d442
--- /dev/null
+++ b/stacks/lwip_stack/vagrant/install_prereq.sh
@@ -0,0 +1,39 @@
+#!/bin/bash -x
+log_file="/DMM/thirdpary/stackpool/vagrant/pre_install_log.txt-`date +'%Y-%m-%d_%H-%M-%S'`"
+exec 1> >(tee -a "$log_file") 2>&1
+
+if [ "$(uname)" <> "Darwin" ]; then
+ OS_ID=$(grep '^ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+ OS_VERSION_ID=$(grep '^VERSION_ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+fi
+
+if [ "$OS_ID" == "ubuntu" ]; then
+ # Standard update + upgrade dance
+ cat << EOF >> /etc/apt/sources.list
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty main restricted
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty main restricted
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty-updates main restricted
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty-updates main restricted
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty universe
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty universe
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty-updates universe
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty-updates universe
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty multiverse
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty multiverse
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty-updates multiverse
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty-updates multiverse
+ deb http://in.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse
+ deb-src http://in.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse
+ deb http://security.ubuntu.com/ubuntu trusty-security main restricted
+ deb-src http://security.ubuntu.com/ubuntu trusty-security main restricted
+ deb http://security.ubuntu.com/ubuntu trusty-security universe
+ deb-src http://security.ubuntu.com/ubuntu trusty-security universe
+ deb http://security.ubuntu.com/ubuntu trusty-security multiverse
+ deb-src http://security.ubuntu.com/ubuntu trusty-security multiverse
+ deb http://extras.ubuntu.com/ubuntu trusty main
+ deb-src http://extras.ubuntu.com/ubuntu trusty main
+EOF
+elif [ "$OS_ID" == "centos" ]; then
+
+ echo centos
+fi