diff options
Diffstat (limited to 'src/framework')
165 files changed, 21498 insertions, 18371 deletions
diff --git a/src/framework/CMakeLists.txt b/src/framework/CMakeLists.txt index 6b22e51..138b45d 100644 --- a/src/framework/CMakeLists.txt +++ b/src/framework/CMakeLists.txt @@ -14,50 +14,34 @@ # limitations under the License. ######################################################################### -if(WITH_HAL_LIB) -else() - SET(PAL_H_DIRECTORIES "/usr/include/dpdk/") - FILE(GLOB_RECURSE LIBCOMM lib_common_mem/*.c) -endif() - FILE(GLOB_RECURSE COMMON common/*.c) FILE(GLOB INIT init/*.c) FILE(GLOB_RECURSE IPC ipc/*.c) FILE(GLOB LOG log/*.c) FILE(GLOB SNAPSHOT snapshot/*.c) -FILE(GLOB STARTUP startup/*.c) FILE(GLOB MAINTAIN maintain/*.c) +FILE(GLOB EVENT event/epoll/*.c) FILE(GLOB HAL hal/*.c) -FILE(GLOB DMM_ADPT ../adapt/*.c) -FILE(GLOB MEM mem/*.c) - -ADD_LIBRARY(dmm_api SHARED - ${COMMON} ${INIT} ${IPC} ${LOG} ${SNAPSHOT} - ${STARTUP} ${MAINTAIN} ${TRACEING} ${HAL} - ${DMM_ADPT} ${LIBCOMM} ${MEM}) - -if(WITH_SECUREC_LIB) -ADD_DEPENDENCIES(dmm_api SECUREC JSON GLOG) -else() -ADD_DEPENDENCIES(dmm_api JSON GLOG) -endif() +FILE(GLOB RD rd/*.c) +FILE(GLOB RES res/*.c) +FILE(GLOB_RECURSE MEM mem/*.c) +FILE(GLOB RING ring/*.c) +FILE(GLOB DFX dfx/*.c) INCLUDE_DIRECTORIES( - dmm_api - PRIVATE - ${JSON_C_SRC} - ${GLOG_SRC} - ${SECUREC_SRC_H} - ipc/mgr_com/ - hal/ - include/ - common/base/include/generic - common/base/include/ - ${PAL_H_DIRECTORIES} - common/base/liblinuxapi/ - common/mem_mgr/include - common/mem_mgr/nsfw_shmem/ - common/mem_mgr/nsfw_nshmem/ - ${CMAKE_CURRENT_LIST_DIR}/../nSocket/nstack/event/ - ${CMAKE_CURRENT_LIST_DIR}/../nSocket/nstack/event/epoll - ${CMAKE_CURRENT_LIST_DIR}/../nSocket/include + nStackFw + PRIVATE + ${JSON_C_SRC} + ${GLOG_SRC} + ${CMAKE_SOURCE_DIR}/src/include + ${CMAKE_SOURCE_DIR}/src/nSocket/nstack + ${CMAKE_SOURCE_DIR}/src/nSocket/include + ${CMAKE_CURRENT_LIST_DIR}/ipc/mgr_com + ${CMAKE_CURRENT_LIST_DIR}/include/common/ + ${CMAKE_CURRENT_LIST_DIR}/include/common/generic + ${CMAKE_CURRENT_LIST_DIR}/common/base/liblinuxapi + ${CMAKE_CURRENT_LIST_DIR}/dfx + ${CMAKE_CURRENT_LIST_DIR}/mem/basic_mem + ${CMAKE_SOURCE_DIR}/src/framework/event/epoll ) +ADD_LIBRARY(nStackFw STATIC ${COMMON} ${INIT} ${IPC} ${LOG} ${SNAPSHOT} ${MAINTAIN} ${TRACEING} ${EVENT} ${RES} ${RD} ${HAL} ${MEM} ${RING} ${DFX}) +ADD_DEPENDENCIES(nStackFw JSON GLOG DPDK) diff --git a/src/framework/common/base/include/common/common_func.h b/src/framework/common/base/include/common/common_func.h deleted file mode 100644 index 2b84b7a..0000000 --- a/src/framework/common/base/include/common/common_func.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* -* 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 _RTE_COMM_FUNC_H_ -#define _RTE_COMM_FUNC_H_ - -#ifdef HAL_LIB - -#else - -#define common_mem_rwlock_t rte_rwlock_t -#define common_mem_spinlock_t rte_spinlock_t - //typedef rte_rwlock_t common_mem_rwlock_t; - -#define nsfw_write_lock(plock) rte_rwlock_write_lock(plock) -#define nsfw_write_unlock(plock) rte_rwlock_write_unlock(plock) -#define nsfw_read_lock(plock) rte_rwlock_read_lock(plock) -#define nsfw_read_unlock(plock) rte_rwlock_read_unlock(plock) - -#define common_mem_align32pow2 rte_align32pow2 - -#define common_mem_atomic32_cmpset rte_atomic32_cmpset -#define common_mem_pause rte_pause - -#define COMMON_MEM_MAX_MEMZONE RTE_MAX_MEMZONE - -#define common_mem_atomic32_t rte_atomic32_t - -#define common_mem_memseg rte_memseg -#define common_mem_mem_config rte_mem_config - -#define common_mem_pal_get_configuration rte_eal_get_configuration - - //#define commem_mem_pal_module_info rte_eal_module_info - // -#define common_mem_pal_init rte_eal_init - -#define COMMON_MEM_MEMPOOL_NAMESIZE RTE_MEMPOOL_NAMESIZE - -#define common_mem_memzone_lookup rte_memzone_lookup -#define common_mem_memzone rte_memzone -#define common_mem_atomic32_add_return rte_atomic32_add_return - -#define common_mem_spinlock_init rte_spinlock_init -#define common_mem_spinlock_lock rte_spinlock_lock -#define common_mem_spinlock_unlock rte_spinlock_unlock - -#define common_mem_memzone_free rte_memzone_free -#define common_mem_pktmbuf_pool_create rte_pktmbuf_pool_create - -#define common_mem_pktmbuf_alloc rte_pktmbuf_alloc - -#define common_mem_mempool rte_mempool - -#define common_mem_pktmbuf_free rte_pktmbuf_free -#define common_mem_mbuf rte_mbuf - -#define common_mem_mempool_lookup rte_mempool_lookup - -#define common_mem_ring_get_memsize rte_ring_get_memsize -#define common_mem_ring rte_ring - -#define COMMON_MEM_MAX_MEMSEG RTE_MAX_MEMSEG - -#define common_mem_memzone_reserve rte_memzone_reserve -#define common_mem_rwlock_read_lock rte_rwlock_read_lock -#define common_mem_rwlock_read_unlock rte_rwlock_read_unlock - -#define common_mem_rwlock_write_lock rte_rwlock_write_lock -#define common_mem_rwlock_write_unlock rte_rwlock_write_unlock -#define common_mem_spinlock_trylock rte_spinlock_trylock - -#define common_mem_socket_id rte_socket_id -#define common_mem_malloc_socket_stats rte_malloc_socket_stats - -#define COMMON_MEM_MIN RTE_MIN - -#define common_pal_module_init nscomm_pal_module_init -#define common_memzone_data_reserve_name nscomm_memzone_data_reserve_name -#define common_memzone_data_lookup_name nscomm_memzone_data_lookup_name - -#define common_dump_stack rte_dump_stack -#define COMMON_PKTMBUF_HEADROOM RTE_PKTMBUF_HEADROOM - -#define common_pktmbuf_mtod rte_pktmbuf_mtod -#define common_memcpy rte_memcpy -#define common_spinlock_try_lock_with_pid dmm_spinlock_try_lock_with_pid -#define common_spinlock_unlock rte_spinlock_unlock -#define common_atomic64_t rte_atomic64_t -#define common_atomic64_inc rte_atomic64_inc -#define common_atomic64_read rte_atomic64_read -#define common_atomic64_dec rte_atomic64_dec -#define common_mbuf_refcnt_set rte_mbuf_refcnt_set -#define common_mbuf_refcnt_read rte_mbuf_refcnt_read -#define common_exit rte_exit -#define COMMON_CACHE_LINE_SIZE RTE_CACHE_LINE_SIZE -#define common_eal_process_type rte_eal_process_type -#define COMMON_PROC_PRIMARY RTE_PROC_PRIMARY - -#endif - -#endif // _RTE_COMM_FUNC_H_ diff --git a/src/framework/common/base/include/common/common_mem_api.h b/src/framework/common/base/include/common/common_mem_api.h deleted file mode 100644 index 40b01b9..0000000 --- a/src/framework/common/base/include/common/common_mem_api.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -* -* 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 __COMMON_MEM_API_H__ -#define __COMMON_MEM_API_H__ - -#ifdef HAL_LIB -#else - -#include "rte_atomic.h" -#include "common_mem_spinlock.h" -#include <sys/types.h> -#include <unistd.h> -#include <semaphore.h> - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ -#endif - -#ifndef NSTACK_LINT_CODE_DISABLE -#define NSTACK_LINT_CODE_DISABLE(code) /*lint -e#code */ -#endif - -#ifndef NSTACK_LINT_CODE_ENABLE -#define NSTACK_LINT_CODE_ENABLE(code) /*lint +e#code */ -#endif - -#define SYS_MBOX_NULL (sys_mbox_t)0 - -typedef sem_t *sys_sem_t_v1; -typedef sem_t sys_sem_st_v1; -typedef struct queue *sys_mbox_t; - -typedef rte_spinlock_t *sys_sem_t_v2; -typedef rte_spinlock_t sys_sem_st_v2; - -#ifndef u32_t -typedef uint32_t u32_t; -#endif - -#ifndef u8_t -typedef uint8_t u8_t; -#endif - -#ifndef s8_t -typedef int8_t s8_t; -#endif - -#ifndef err_t -typedef s8_t err_t; -#endif - -/** 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 - -void sys_sem_signal_s_v2 (sys_sem_t_v2 sem); -void sys_sem_init_v2 (sys_sem_t_v2 sem); -u32_t sys_arch_sem_trywait_v2 (sys_sem_t_v2 * sem); - -u32_t sys_arch_sem_wait_s_v2 (sys_sem_t_v2 sem); - -#define SYS_HOST_INITIAL_PID 1 -extern volatile pid_t g_sys_host_pid; -pid_t sys_get_hostpid_from_file (pid_t pid); -static inline pid_t -get_sys_pid () -{ - if (SYS_HOST_INITIAL_PID == g_sys_host_pid) - (void) sys_get_hostpid_from_file (getpid ()); - return g_sys_host_pid; -} - -pid_t update_sys_pid (); -u32_t sys_now (void); - -#define sys_sem_t sys_sem_t_v2 -#define sys_sem_st sys_sem_st_v2 -#define sys_sem_new(sem, count) sys_sem_new_v2(sem, count) -#define sys_sem_free(sem) sys_sem_free_v2(sem) -#define sys_sem_signal(sem) sys_sem_signal_v2(sem) -#define sys_arch_sem_wait(sem, timeout) sys_arch_sem_wait_v2(sem) -#define sys_arch_sem_trywait(sem) sys_arch_sem_trywait_v2(sem) - -#define sys_sem_init(sem) sys_sem_init_v2(sem) -#define sys_sem_s_signal(sem) sys_sem_signal_s_v2(sem) -#define sys_arch_sem_s_wait(sem, timeout) sys_arch_sem_wait_s_v2(sem) -#define sys_arch_lock_with_pid(sem) (void)sys_arch_lock_with_pid_v2(sem) - -#define BUF_SIZE_FILEPATH 256 -#define STR_PID "pid:" -#define READ_FILE_BUFLEN 512 - -extern pid_t sys_get_hostpid_from_file (pid_t pid); -extern pid_t get_hostpid_from_file (u32_t pid); -extern void get_exec_name_by_pid (pid_t pid, char *task_name, - int task_name_len); - -static inline u32_t -sys_arch_lock_with_pid_v2 (sys_sem_t_v2 sem) -{ - if (SYS_HOST_INITIAL_PID == g_sys_host_pid) - (void) sys_get_hostpid_from_file (getpid ()); - dmm_spinlock_lock_with_pid (sem, g_sys_host_pid); - return 0; -} - -#define NSTACK_SEM_MALLOC(sys_sem,count) \ -{ \ - rte_spinlock_init(&(sys_sem)); \ - if (!(count)) \ - { \ - rte_spinlock_lock(&(sys_sem)); \ - } \ -} - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif -#endif - -#endif /* __COMMON_MEM_API_H__ */ diff --git a/src/framework/common/base/include/common/common_mem_base_type.h b/src/framework/common/base/include/common/common_mem_base_type.h deleted file mode 100644 index 01707d9..0000000 --- a/src/framework/common/base/include/common/common_mem_base_type.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* -* 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 _COMMON_MEM_BASE_TYPE_H_ -#define _COMMON_MEM_BASE_TYPE_H_ - -#ifdef HAL_LIB - -#else - -#define ALIGN_TYPE uint64_t -#define PTR_ALIGN_TYPE uint64_t - -/*alignment define*/ -#define ALIGNMENT_DEF(name, type, aligntype) \ - union { \ - type name; \ - aligntype name##_align; \ - } - -#define PTR_ALIGNMENT_DEF(name, type) ALIGNMENT_DEF(name, type, PTR_ALIGN_TYPE) - -#define OTHER_ALIGNMENT_DEF(name, type) ALIGNMENT_DEF(name, type, ALIGN_TYPE) - -/* - * * List definitions. - * */ -#define DMM_LIST_HEAD(name, type) \ -struct name { \ - PTR_ALIGNMENT_DEF(lh_first, struct type *); /* first element */ \ -} - -#define DMM_LIST_ENTRY(type) \ -struct { \ - PTR_ALIGNMENT_DEF(le_next, struct type *); /* next element */\ - PTR_ALIGNMENT_DEF(le_prev, struct type **); /* address of previous next element */ \ -} - -/* - * * Tail queue definitions. - * */ -#define _DMM_TAILQ_HEAD(name, type, qual) \ -struct name { \ - PTR_ALIGNMENT_DEF(tqh_first, qual type *); /* first element */ \ - PTR_ALIGNMENT_DEF(tqh_last, qual type * qual *); /* addr of last next element */ \ -} - -#define DMM_TAILQ_HEAD(name, type) _DMM_TAILQ_HEAD(name, struct type,) - -#define _DMM_TAILQ_ENTRY(type, qual) \ -struct { \ - PTR_ALIGNMENT_DEF(tqe_next, qual type *); /* next element */\ - PTR_ALIGNMENT_DEF(tqe_prev, qual type * qual*); /* address of previous next element */\ -} -#define DMM_TAILQ_ENTRY(type) _DMM_TAILQ_ENTRY(struct type,) - -/* - * * Singly-linked Tail queue declarations. - * */ -#define DMM_STAILQ_HEAD(name, type) \ - struct name { \ - PTR_ALIGNMENT_DEF(stqh_first, struct type *); /* first element */ \ - PTR_ALIGNMENT_DEF(stqh_last, struct type **); /* addr of last next element */ \ - } - -#define DMM_STAILQ_ENTRY(type) \ - struct { \ - PTR_ALIGNMENT_DEF(stqe_next, struct type *); /* next element */ \ - } -#endif - -#endif diff --git a/src/framework/common/base/include/common/common_mem_buf.h b/src/framework/common/base/include/common/common_mem_buf.h deleted file mode 100644 index c9bb9fd..0000000 --- a/src/framework/common/base/include/common/common_mem_buf.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* -* 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 _COMMON_MEM_BUF_H_ -#define _COMMON_MEM_BUF_H_ - -#ifdef HAL_LIB -#else - -#include "nsfw_mem_api.h" -#include "common_mem_base_type.h" -#include "types.h" - -typedef enum __DMM_PROC_TYPE -{ - DMM_PROC_T_AUTO = 0, /*auto detect */ - DMM_PROC_T_PRIMARY = 1, /* set to primary */ - DMM_PROC_T_SECONDARY = 2, /* set to secondary */ - DMM_PROC_T_INVALID -} DMM_PROC_TYPE; - -#define DMM_MBUF_RET_OK 0 -#define DMM_MBUF_RET_ERR 1 - -#define LCORE_MAX 128 -#define LCORE_MASK_PER (sizeof(int) * 8) -#define LCORE_MASK_MAX (LCORE_MAX/LCORE_MASK_PER) - -#define LCORE_MASK_SET(ilcoremask, value) \ - if (value < LCORE_MAX) \ - { \ - ilcoremask[(value/LCORE_MASK_PER)] = (int) ( (ilcoremask[(value/LCORE_MASK_PER)]) | (1< (value%LCORE_MASK_PER))); \ - } \ - -#define DMM_HUGTBL_ENABLE 0 -#define DMM_HUGTBL_DISABLE 1 - -typedef struct __common_pal_module_info -{ - int ishare_mem_size; /*shared memory size */ - int ilcoremask[LCORE_MASK_MAX]; - /**/ unsigned char uchugeflag; - unsigned char ucproctype; - unsigned char ucinstance; - unsigned char ucresrv2; -} common_mem_pal_module_info; - -/** - * rte pal module init. - * - * - * @param name - * The name of the buf pool. - */ -int nscomm_pal_module_init (nsfw_mem_para * para, - common_mem_pal_module_info * pinfo, u8 app_mode); - -void *nscomm_memzone_data_reserve_name (const char *name, size_t len, - int socket_id); - -void *nscomm_memzone_data_lookup_name (const char *name); - -#endif - -#endif /* _COMMON_MEM_BUF_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_malloc.h b/src/framework/common/base/include/common/common_mem_malloc.h deleted file mode 100644 index 68721cd..0000000 --- a/src/framework/common/base/include/common/common_mem_malloc.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -* -* 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 _COMMON_MEM_MALLOC_H_ -#define _COMMON_MEM_MALLOC_H_ - -#ifdef HAL_LIB -#else -#include "rte_malloc.h" -#endif - -#endif /* _COMMON_MEM_MALLOC_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_mbuf.h b/src/framework/common/base/include/common/common_mem_mbuf.h deleted file mode 100644 index 0bb7696..0000000 --- a/src/framework/common/base/include/common/common_mem_mbuf.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* -* 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. -*/ - -/******************************************************************* - Copyright 2017 - 2047, Huawei Tech. Co., Ltd. - ALL RIGHTS RESERVED - -Filename : common_mem_mbuf.h -Description : -Version : 1.1 -********************************************************************/ - -#ifndef _COMMON_MEM_MBUF_H_ -#define _COMMON_MEM_MBUF_H_ - -#ifdef HAL_LIB -#else -#include "rte_mbuf.h" -#include "common_func.h" - -typedef uint32_t (*dmm_mbuf_item_fun) (void *data, void *argv); -int32_t dmm_pktmbuf_pool_iterator (struct common_mem_mempool *mp, - uint32_t start, uint32_t end, - dmm_mbuf_item_fun fun, void *argv); -#endif - -#endif /* _COMMON_MEM_MBUF_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_mempool.h b/src/framework/common/base/include/common/common_mem_mempool.h deleted file mode 100644 index 58a8e82..0000000 --- a/src/framework/common/base/include/common/common_mem_mempool.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -* -* 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 _COMMON_MEM_MEMPOOL_H_ -#define _COMMON_MEM_MEMPOOL_H_ - -#ifdef HAL_LIB -#else -#include "rte_mempool.h" -#endif - -#endif /* _COMMON_MEM_MEMPOOL_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_memzone.h b/src/framework/common/base/include/common/common_mem_memzone.h deleted file mode 100644 index 20e18c2..0000000 --- a/src/framework/common/base/include/common/common_mem_memzone.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -* -* 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 _COMMON_MEM_MEMZONE_H_ -#define _COMMON_MEM_MEMZONE_H_ - -#ifdef HAL_LIB -#else -#include "rte_memzone.h" -#endif - -#endif /* _COMMON_MEM_MEMZONE_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_pal.h b/src/framework/common/base/include/common/common_mem_pal.h deleted file mode 100644 index 209b8bd..0000000 --- a/src/framework/common/base/include/common/common_mem_pal.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* -* 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 _COMMON_MEM_PAL_H_ -#define _COMMON_MEM_PAL_H_ - -#ifdef HAL_LIB -#else - -#include "nsfw_base_linux_api.h" - -/*print the map address*/ -void dmm_addr_print (void); - -#endif - -#endif /* _COMMON_MEM_PAL_H_ */ diff --git a/src/framework/common/base/include/common/common_mem_spinlock.h b/src/framework/common/base/include/common/common_mem_spinlock.h deleted file mode 100644 index 23f6b1e..0000000 --- a/src/framework/common/base/include/common/common_mem_spinlock.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* -* 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 _COMMON_MEM_SPINLOCK_X86_64_H_ -#define _COMMON_MEM_SPINLOCK_X86_64_H_ - -#ifdef HAL_LIB -#else -#include "rte_spinlock.h" - -static inline void -dmm_spinlock_lock_with_pid (rte_spinlock_t * sl, int pid) -{ - while (!__sync_bool_compare_and_swap (&sl->locked, 0, pid)) - while (sl->locked) - rte_pause (); -} - -static inline int -dmm_spinlock_try_lock_with_pid (rte_spinlock_t * sl, int pid) -{ - return __sync_bool_compare_and_swap (&sl->locked, 0, pid); -} - -#endif - -#endif /* _COMMON_MEM_SPINLOCK_X86_64_H_ */ diff --git a/src/framework/common/base/include/common/common_sys_config.h b/src/framework/common/base/include/common/common_sys_config.h deleted file mode 100644 index 736c47b..0000000 --- a/src/framework/common/base/include/common/common_sys_config.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* -* 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 __COMMON_SYS_CONFIG_H_ -#define __COMMON_SYS_CONFIG_H_ - -/* Below compile macro is used only in UT makefile */ -#if (HAL_LIB) -#else -#undef RTE_CACHE_LINE_SIZE -#define RTE_CACHE_LINE_SIZE 64 /* RTE_CACHE_LINE_SIZE */ -#undef RTE_MAX_LCORE -#define RTE_MAX_LCORE 128 /* RTE_MAX_LCORE */ -#undef RTE_MAX_NUMA_NODES -#define RTE_MAX_NUMA_NODES 8 /* RTE_MAX_NUMA_NODES */ -#undef RTE_MAX_MEMSEG -#define RTE_MAX_MEMSEG 256 /* RTE_MAX_MEMSEG */ -#undef RTE_MAX_MEMZONE -#define RTE_MAX_MEMZONE 2560 /* RTE_MAX_MEMZONE */ -#undef RTE_MAX_TAILQ -#define RTE_MAX_TAILQ 32 /* RTE_MAX_TAILQ */ -#undef RTE_ARCH_X86 -#define RTE_ARCH_X86 1 /* RTE_ARCH_64 */ -#undef RTE_ARCH_64 -#define RTE_ARCH_64 1 /* RTE_ARCH_64 */ -#undef RTE_PKTMBUF_HEADROOM -#define RTE_PKTMBUF_HEADROOM 128 /* RTE_PKTMBUF_HEADROOM */ -#undef RTE_MEMPOOL_CACHE_MAX_SIZE -#define RTE_MEMPOOL_CACHE_MAX_SIZE 512 /* RTE_MEMPOOL_CACHE_MAX_SIZE */ - -#endif - -#endif // __COMMON_SYS_CONFIG_H_ diff --git a/src/framework/common/base/include/common/generic/common_mem_rwlock.h b/src/framework/common/base/include/common/generic/common_mem_rwlock.h deleted file mode 100644 index 2eed259..0000000 --- a/src/framework/common/base/include/common/generic/common_mem_rwlock.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -* -* 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 _COMMON_MEM_RWLOCK_H_ -#define _COMMON_MEM_RWLOCK_H_ - -#ifdef HAL_LIB -#else -#include "rte_rwlock.h" -#endif - -#endif /* _COMMON_MEM_RWLOCK_H_ */ diff --git a/src/framework/common/base/include/common_pal_bitwide_adjust.h b/src/framework/common/base/include/common_pal_bitwide_adjust.h deleted file mode 100644 index 0e68533..0000000 --- a/src/framework/common/base/include/common_pal_bitwide_adjust.h +++ /dev/null @@ -1,202 +0,0 @@ -/* -* -* 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 _COMMON_PAL_BITWIDE_ADJUST_H_ -#define _COMMON_PAL_BITWIDE_ADJUST_H_ - -#ifdef HAL_LIB -#include "pal_bitwide_adjust.h" -#else -#define MODULE(name) (1) - -#include "common_mem_common.h" - -#include "common_func.h" - -#define ALIGN_SIZET(size) ((uint64_t)(size)) -#define ALIGN_PTR(PTR) ((uint64_t)(PTR)) - -extern struct common_mem_memseg *g_PMemSegArry; -extern void **g_LMegAddrArry; - -/*get Local Seg addr by segIdx*/ -#define HMEM_SEG_LVADDR(segid) (g_LMegAddrArry[segid]) -/*get SegIDX by PrimSegAddr, just get the array Idx of g_PMemSegArry*/ -#define HMEM_SEGID(segaddr) ((struct common_mem_memseg*)segaddr - &(g_PMemSegArry[0])) - -/***************************************************************** -Parameters : LMegAddrArry[] Local common_mem_memseg addr Array - SegNum common_mem_memseg Num. -Return : -Description : init g_PrimAddr2LocalMap g_LocalAddr2PrimMap while the process start -*****************************************************************/ -void *pal_shddr_to_laddr (uint64_t shaddr); -uint64_t pal_laddr_to_shddr (void *laddr); -int dmm_pal_addr_align (); - -extern int g_PrimSameFlg; - -/* if __NSTACK_MAIN__ is defined, no need do addr trans*/ -#ifndef __NSTACK_MAIN__ -/* g_PrimSameFlg check should be done before calling cast functions */ - -/*share memory address to local virtual address*/ -#define ADDR_SHTOL(addr) (g_PrimSameFlg ? ((void*) (addr)) : pal_shddr_to_laddr((uint64_t)(addr))) - -/*local virtual address to share memory address according to memseg*/ -#define ADDR_LTOSH(addr) (g_PrimSameFlg ? ((uint64_t)(addr)) : pal_laddr_to_shddr((void*)(addr))) - -#define PTR_SHTOL(type, addr) ((type)ADDR_SHTOL(addr)) - -/*local virtual address to share memory address; for compatible, not delete ADDR_LTOSH_EXT*/ -#define ADDR_LTOSH_EXT(addr) ADDR_LTOSH(addr) -#else -/*share memory address to local virtual address*/ -#define ADDR_SHTOL(addr) ((void*)(addr)) - -/*local virtual address to share memory address according to memseg*/ -#define ADDR_LTOSH(addr) ((uint64_t)(addr)) - -#define PTR_SHTOL(type, addr) ((type)(addr)) - -/*local virtual address to share memory address; for compatible, not delete ADDR_LTOSH_EXT*/ -#define ADDR_LTOSH_EXT(addr) ADDR_LTOSH(addr) -#endif - -#if MODULE("list") -#define COMMON_LIST_INSERT_HEAD(lhead, lelm, field) do { \ - if (((lelm)->field.le_next_align = (lhead)->lh_first_align) != ((typeof((lhead)->lh_first_align))(long)NULL)) \ - ((typeof((lhead)->lh_first))ADDR_SHTOL((lhead)->lh_first_align))->field.le_prev_align = \ - ADDR_LTOSH(&(lelm)->field.le_next); \ - (lhead)->lh_first_align = ADDR_LTOSH(lelm); \ - (lelm)->field.le_prev_align = ADDR_LTOSH(&(lhead)->lh_first); \ -} while (/*CONSTCOND*/0) - -#define COMMON_LIST_REMOVE(lelm, field) do { \ - if ((lelm)->field.le_next_align != ((typeof((lelm)->field.le_next_align))ALIGN_PTR(NULL))) \ - ((typeof((lelm)->field.le_next))ADDR_SHTOL((lelm)->field.le_next_align))->field.le_prev_align = \ - (lelm)->field.le_prev_align; \ - if (EOK != (MEMCPY_S((typeof((lelm)->field.le_prev))ADDR_SHTOL((lelm)->field.le_prev_align), \ - sizeof((lelm)->field.le_next_align), \ - &((lelm)->field.le_next_align), \ - sizeof((lelm)->field.le_next_align)))) \ - {\ - NSCOMM_LOGERR("MEMCPY_S failed.");\ - return;\ - }\ -} while (/*CONSTCOND*/0) - -#define COMMON_LIST_EMPTY(lhead) ((typeof((lhead)->lh_first))ADDR_SHTOL((lhead)->lh_first_align) == NULL) -#define COMMON_LIST_FIRST(lhead) ((typeof((lhead)->lh_first))ADDR_SHTOL((lhead)->lh_first_align)) -#define COMMON_LIST_NEXT(lelm, field) ((typeof((lelm)->field.le_next))ADDR_SHTOL((lelm)->field.le_next_align)) - -#endif - -#if MODULE("tailq") - -#define COMMON_TAILQ_INSERT_TAIL(lhead, lelm, field) do { \ - (lelm)->field.tqe_next_align = (typeof((lelm)->field.tqe_next_align))NULL; \ - (lelm)->field.tqe_prev_align = (lhead)->tqh_last_align; \ - typeof((lhead)->tqh_last_align) tempelm = ADDR_LTOSH(lelm);\ - if (EOK != (MEMCPY_S(ADDR_SHTOL((lhead)->tqh_last_align), sizeof(tempelm), &tempelm, sizeof(tempelm)))) \ - {\ - NSCOMM_LOGERR("MEMCPY_S failed.");\ - }\ - (lhead)->tqh_last_align = ADDR_LTOSH(&(lelm)->field.tqe_next); \ -} while (/*CONSTCOND*/0) - -#define COMMON_TAILQ_FOREACH(lvar, lhead, field) \ - for ((lvar) = (typeof(lvar))ADDR_SHTOL((lhead)->tqh_first_align); \ - (lvar); \ - (lvar) = (typeof(lvar))ADDR_SHTOL((lvar)->field.tqe_next_align)) - -#define COMMON_TAILQ_REMOVE(lhead, lelm, field) do { \ - if (((lelm)->field.tqe_next_align) != (typeof((lelm)->field.tqe_next_align))NULL) \ - ((typeof((lelm)->field.tqe_next))ADDR_SHTOL((lelm)->field.tqe_next_align))->field.tqe_prev_align = \ - (lelm)->field.tqe_prev_align; \ - else \ - (lhead)->tqh_last_align = (lelm)->field.tqe_prev_align; \ - if (EOK != (MEMCPY_S(ADDR_SHTOL((lelm)->field.tqe_prev_align), \ - sizeof((lelm)->field.tqe_next_align), \ - &((lelm)->field.tqe_next_align), \ - sizeof((lelm)->field.tqe_next_align)))) \ - {\ - NSCOMM_LOGERR("MEMCPY_S failed.");\ - }\ - } while (/*CONSTCOND*/0) - -/* - * Tail queue functions. - */ -#define COMMON_TAILQ_INIT(head) do { \ - (head)->tqh_first_align = (typeof((head)->tqh_first_align))NULL; \ - (head)->tqh_last_align = ADDR_LTOSH(&(head)->tqh_first); \ - } while (/*CONSTCOND*/0) - -/* - * Tail queue access methods. - */ -#define COMMON_TAILQ_EMPTY(head) ((head)->tqh_first_align == (typeof((head)->tqh_first_align))NULL) -#define COMMON_TAILQ_FIRST(head) ((typeof((head)->tqh_first))ADDR_SHTOL((head)->tqh_first_align)) -#define COMMON_TAILQ_NEXT(elm, field) ((typeof((elm)->field.tqe_next))ADDR_SHTOL((elm)->field.tqe_next_align)) - -#endif - -#if MODULE("stailq") -/* -* Singly-linked Tail queue functions. -*/ -#define COMMON_STAILQ_INIT(head) do { \ - (head)->stqh_first_align = ALIGN_PTR(NULL); \ - (head)->stqh_last_align = ADDR_LTOSH(&(head)->stqh_first); \ -} while (/*CONSTCOND*/0) - -#define COMMON_STAILQ_INSERT_TAIL(head, elm, field) do { \ - (elm)->field.stqe_next_align = ALIGN_PTR(NULL); \ - typeof((head)->stqh_last_align) telm = ADDR_LTOSH(elm);\ - if (EOK != (MEMCPY_S(ADDR_SHTOL((head)->stqh_last_align), sizeof(telm), &telm, sizeof(telm))))\ - {\ - NSCOMM_LOGERR("MEMCPY_S failed.");\ - }\ - (head)->stqh_last_align = ADDR_LTOSH(&(elm)->field.stqe_next); \ -} while (/*CONSTCOND*/0) - -#define COMMON_STAILQ_REMOVE_HEAD(head, field) do { \ - if (((head)->stqh_first_align = \ - ((typeof((head)->stqh_first))ADDR_SHTOL((head)->stqh_first_align))->field.stqe_next_align) == \ - (PTR_ALIGN_TYPE)NULL) \ - (head)->stqh_last_align = ADDR_LTOSH(&(head)->stqh_first); \ -} while (/*CONSTCOND*/0) - -#define COMMON_STAILQ_FOREACH(var, head, field) \ - for ((var) = ADDR_SHTOL((head)->stqh_first_align); \ - (var); \ - (var) = ADDR_SHTOL((var)->field.stqe_next_align)) - -/* -* Singly-linked Tail queue access methods. -*/ - -#define COMMON_STAILQ_EMPTY(head) ((head)->stqh_first_align == (PTR_ALIGN_TYPE)NULL) - -#define COMMON_STAILQ_FIRST(head) (ADDR_SHTOL((head)->stqh_first_align)) - -#define COMMON_STAILQ_NEXT(elm, field) (ADDR_SHTOL((elm)->field.stqe_next_align)) -#endif - -#endif - -#endif diff --git a/src/framework/common/base/include/nsfw_base_linux_api.h b/src/framework/common/base/include/nsfw_base_linux_api.h deleted file mode 100644 index 83b5a32..0000000 --- a/src/framework/common/base/include/nsfw_base_linux_api.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* -* 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 _NSFW_BASE_LINUX_API_H_ -#define _NSFW_BASE_LINUX_API_H_ - -#include <sys/types.h> -#include <sys/socket.h> -#include <sys/epoll.h> -#include <unistd.h> - -int nsfw_base_socket (int, int, int); -int nsfw_base_bind (int, const struct sockaddr *, socklen_t); -int nsfw_base_listen (int, int); -int nsfw_base_shutdown (int, int); -int nsfw_base_getsockname (int, struct sockaddr *, socklen_t *); -int nsfw_base_getpeername (int, struct sockaddr *, socklen_t *); -int nsfw_base_getsockopt (int, int, int, void *, socklen_t *); -int nsfw_base_setsockopt (int, int, int, const void *, socklen_t); -int nsfw_base_accept (int, struct sockaddr *, socklen_t *); -int nsfw_base_accept4 (int, struct sockaddr *, socklen_t *, int flags); -int nsfw_base_connect (int, const struct sockaddr *, socklen_t); -ssize_t nsfw_base_recv (int, void *, size_t, int); -ssize_t nsfw_base_send (int, const void *, size_t, int); -ssize_t nsfw_base_read (int, void *, size_t); -ssize_t nsfw_base_write (int, const void *, size_t); -ssize_t nsfw_base_writev (int, const struct iovec *, int); -ssize_t nsfw_base_readv (int, const struct iovec *, int); -ssize_t nsfw_base_sendto (int, const void *, size_t, int, - const struct sockaddr *, socklen_t); -ssize_t nsfw_base_recvfrom (int, void *, size_t, int, struct sockaddr *, - socklen_t *); -ssize_t nsfw_base_sendmsg (int, const struct msghdr *, int flags); -ssize_t nsfw_base_recvmsg (int, struct msghdr *, int flags); -int nsfw_base_close (int); -int nsfw_base_select (int, fd_set *, fd_set *, fd_set *, struct timeval *); -int nsfw_base_ioctl (int, unsigned long, unsigned long); -int nsfw_base_fcntl (int, int, unsigned long); -int nsfw_base_epoll_create (int); -int nsfw_base_epoll_create1 (int); -int nsfw_base_epoll_ctl (int, int, int, struct epoll_event *); -int nsfw_base_epoll_wait (int, struct epoll_event *, int, int); -pid_t nsfw_base_fork (void); - -#endif diff --git a/src/framework/common/base/liblinuxapi/base_linux_api_declare.h b/src/framework/common/base/liblinuxapi/base_linux_api_declare.h index 943ae04..3f96e6c 100644 --- a/src/framework/common/base/liblinuxapi/base_linux_api_declare.h +++ b/src/framework/common/base/liblinuxapi/base_linux_api_declare.h @@ -14,38 +14,42 @@ * limitations under the License. */ -BASE_MK_DECL (int, socket, (int, int, int)); -BASE_MK_DECL (int, bind, (int, const struct sockaddr *, socklen_t)); -BASE_MK_DECL (int, listen, (int, int)); -BASE_MK_DECL (int, shutdown, (int, int)); -BASE_MK_DECL (int, getsockname, (int, struct sockaddr *, socklen_t *)); -BASE_MK_DECL (int, getpeername, (int, struct sockaddr *, socklen_t *)); -BASE_MK_DECL (int, getsockopt, (int, int, int, void *, socklen_t *)); -BASE_MK_DECL (int, setsockopt, (int, int, int, const void *, socklen_t)); -BASE_MK_DECL (int, accept, (int, struct sockaddr *, socklen_t *)); -BASE_MK_DECL (int, accept4, (int, struct sockaddr *, socklen_t *, int flags)); -BASE_MK_DECL (int, connect, (int, const struct sockaddr *, socklen_t)); -BASE_MK_DECL (ssize_t, recv, (int, void *, size_t, int)); -BASE_MK_DECL (ssize_t, send, (int, const void *, size_t, int)); -BASE_MK_DECL (ssize_t, read, (int, void *, size_t)); -BASE_MK_DECL (ssize_t, write, (int, const void *, size_t)); -BASE_MK_DECL (ssize_t, writev, (int, const struct iovec *, int)); -BASE_MK_DECL (ssize_t, readv, (int, const struct iovec *, int)); -BASE_MK_DECL (ssize_t, sendto, - (int, const void *, size_t, int, const struct sockaddr *, - socklen_t)); -BASE_MK_DECL (ssize_t, recvfrom, - (int, void *, size_t, int, struct sockaddr *, socklen_t *)); -BASE_MK_DECL (ssize_t, sendmsg, (int, const struct msghdr *, int flags)); -BASE_MK_DECL (ssize_t, recvmsg, (int, struct msghdr *, int flags)); -BASE_MK_DECL (int, close, (int)); -BASE_MK_DECL (int, select, - (int, fd_set *, fd_set *, fd_set *, struct timeval *)); -BASE_MK_DECL (int, ioctl, (int, unsigned long, unsigned long)); -BASE_MK_DECL (int, fcntl, (int, int, unsigned long)); -BASE_MK_DECL (int, epoll_create, (int)); -BASE_MK_DECL (int, epoll_create1, (int)); -BASE_MK_DECL (int, epoll_ctl, (int, int, int, struct epoll_event *)); -BASE_MK_DECL (int, epoll_wait, (int, struct epoll_event *, int, int)); -BASE_MK_DECL (pid_t, fork, (void)); +BASE_MK_DECL(int, socket, (int, int, int)); +BASE_MK_DECL(int, bind, (int, const struct sockaddr *, socklen_t)); +BASE_MK_DECL(int, listen, (int, int)); +BASE_MK_DECL(int, shutdown, (int, int)); +BASE_MK_DECL(int, getaddrinfo, + (const char *, const char *, const struct addrinfo *, + struct addrinfo **)); +BASE_MK_DECL(int, getsockname, (int, struct sockaddr *, socklen_t *)); +BASE_MK_DECL(int, getpeername, (int, struct sockaddr *, socklen_t *)); +BASE_MK_DECL(int, getsockopt, (int, int, int, void *, socklen_t *)); +BASE_MK_DECL(int, setsockopt, (int, int, int, const void *, socklen_t)); +BASE_MK_DECL(int, accept, (int, struct sockaddr *, socklen_t *)); +BASE_MK_DECL(int, accept4, (int, struct sockaddr *, socklen_t *, int flags)); +BASE_MK_DECL(int, connect, (int, const struct sockaddr *, socklen_t)); +BASE_MK_DECL(ssize_t, recv, (int, void *, size_t, int)); +BASE_MK_DECL(ssize_t, send, (int, const void *, size_t, int)); +BASE_MK_DECL(ssize_t, read, (int, void *, size_t)); +BASE_MK_DECL(ssize_t, write, (int, const void *, size_t)); +BASE_MK_DECL(ssize_t, writev, (int, const struct iovec *, int)); +BASE_MK_DECL(ssize_t, readv, (int, const struct iovec *, int)); +BASE_MK_DECL(ssize_t, sendto, + (int, const void *, size_t, int, const struct sockaddr *, + socklen_t)); +BASE_MK_DECL(ssize_t, recvfrom, + (int, void *, size_t, int, struct sockaddr *, socklen_t *)); +BASE_MK_DECL(ssize_t, sendmsg, (int, const struct msghdr *, int flags)); +BASE_MK_DECL(ssize_t, recvmsg, (int, struct msghdr *, int flags)); +BASE_MK_DECL(int, close, (int)); +BASE_MK_DECL(int, select, + (int, fd_set *, fd_set *, fd_set *, struct timeval *)); +BASE_MK_DECL(int, ioctl, (int, unsigned long, unsigned long)); +BASE_MK_DECL(int, fcntl, (int, int, unsigned long)); +BASE_MK_DECL(int, epoll_create, (int)); +BASE_MK_DECL(int, epoll_create1, (int)); +//BASE_MK_DECL(int , poll , (struct pollfd *, nfds_t, int)); +BASE_MK_DECL(int, epoll_ctl, (int, int, int, struct epoll_event *)); +BASE_MK_DECL(int, epoll_wait, (int, struct epoll_event *, int, int)); +BASE_MK_DECL(pid_t, fork, (void)); #undef BASE_MK_DECL diff --git a/src/framework/common/base/liblinuxapi/nsfw_base_linux_api.c b/src/framework/common/base/liblinuxapi/nsfw_base_linux_api.c index 4e59d68..734a09f 100644 --- a/src/framework/common/base/liblinuxapi/nsfw_base_linux_api.c +++ b/src/framework/common/base/liblinuxapi/nsfw_base_linux_api.c @@ -15,7 +15,6 @@ */ #include "nsfw_base_linux_api.h" -#include "nstack_log.h" #include <pthread.h> #include <stdio.h> #include <errno.h> @@ -39,9 +38,9 @@ typedef enum { - BASE_STATE_INIT, - BASE_STATE_SUCCESS, - BASE_STATE_FAIL + BASE_STATE_INIT, + BASE_STATE_SUCCESS, + BASE_STATE_FAIL } nsfw_base_state; typedef struct __base_linux_api @@ -50,27 +49,24 @@ typedef struct __base_linux_api #include "base_linux_api_declare.h" } base_linux_api; -nsfw_base_state g_nsfw_module_state = BASE_STATE_INIT; +nsfw_base_state g_nsfw_mudule_state = BASE_STATE_INIT; pthread_mutex_t g_nsfw_init_mutex = PTHREAD_MUTEX_INITIALIZER; base_linux_api g_nsfw_posix_api = { 0 }; void *g_linux_lib_handle = (void *) 0; -int -nsfw_posix_symbol_load () +int nsfw_posix_symbol_load() { - g_linux_lib_handle = dlopen ("libc.so.6", RTLD_NOW | RTLD_GLOBAL); - if ((void *) 0 == g_linux_lib_handle) + g_linux_lib_handle = dlopen("libc.so.6", RTLD_NOW | RTLD_GLOBAL); + if ((void *) 0 == g_linux_lib_handle) { - /* optimize dlopen err print */ - NSSOC_LOGERR ("cannot dlopen libc.so.6] err_string=%s", dlerror ()); - return NSFW_BASE_FAIL; + return NSFW_BASE_FAIL; } #define BASE_MK_DECL(ret, fn, args) \ g_nsfw_posix_api.pf##fn = (typeof(g_nsfw_posix_api.pf##fn))dlsym(g_linux_lib_handle, #fn); #include <base_linux_api_declare.h> - return NSFW_BASE_OK; + return NSFW_BASE_OK; } /***************************************************************** @@ -78,549 +74,191 @@ Parameters : void Return : Description : linux posix api init with threadonce *****************************************************************/ -static inline int -nsfw_posix_api_init () +static inline int nsfw_posix_api_init() { - int iret = NSFW_BASE_OK; + int iret = NSFW_BASE_OK; - /*if init already, just return success, if init fail before, just return err */ - if (BASE_STATE_INIT != g_nsfw_module_state) + /*if init already, just return success, if init fail before, just return err */ + if (BASE_STATE_INIT != g_nsfw_mudule_state) { - return (BASE_STATE_SUCCESS == - g_nsfw_module_state ? NSFW_BASE_OK : NSFW_BASE_FAIL); + return (BASE_STATE_SUCCESS == + g_nsfw_mudule_state ? NSFW_BASE_OK : NSFW_BASE_FAIL); } - (void) pthread_mutex_lock (&g_nsfw_init_mutex); + (void) pthread_mutex_lock(&g_nsfw_init_mutex); - /*if init already, just return success, if init fail before, just return err */ - if (BASE_STATE_INIT != g_nsfw_module_state) + /*if init already, just return success, if init fail before, just return err */ + if (BASE_STATE_INIT != g_nsfw_mudule_state) { - (void) pthread_mutex_unlock (&g_nsfw_init_mutex); - return (BASE_STATE_SUCCESS == - g_nsfw_module_state ? NSFW_BASE_OK : NSFW_BASE_FAIL); + (void) pthread_mutex_unlock(&g_nsfw_init_mutex); + return (BASE_STATE_SUCCESS == + g_nsfw_mudule_state ? NSFW_BASE_OK : NSFW_BASE_FAIL); } - iret = nsfw_posix_symbol_load (); - if (NSFW_BASE_OK == iret) + iret = nsfw_posix_symbol_load(); + if (NSFW_BASE_OK == iret) { - g_nsfw_module_state = BASE_STATE_SUCCESS; + g_nsfw_mudule_state = BASE_STATE_SUCCESS; } - else + else { - g_nsfw_module_state = BASE_STATE_FAIL; + g_nsfw_mudule_state = BASE_STATE_FAIL; } - (void) pthread_mutex_unlock (&g_nsfw_init_mutex); - return iret; + (void) pthread_mutex_unlock(&g_nsfw_init_mutex); + return iret; } /* *INDENT-OFF* */ -/***************************************************************************** -* Prototype : nsfw_base_socket -* Description : linux socket api -* Input : int a -* int b -* int c -* Output : None -* Return Value : int -* Calls : -* Called By : - -* -*****************************************************************************/ int nsfw_base_socket(int a, int b, int c) { nsfw_call_ret(socket, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_bind -* Description : linux fd bind api -* Input : int a -* const struct sockaddr* b -* socklen_t c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_bind(int a, const struct sockaddr* b, socklen_t c) { nsfw_call_ret(bind, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_listen -* Description : linux fd listen api -* Input : int a -* int b -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_listen(int a, int b) { nsfw_call_ret(listen, (a, b)) } -/***************************************************************************** -* Prototype : nsfw_base_shutdown -* Description : linux shutdown api -* Input : int a -* int b -* Output : None -* Return Value : int -* Calls : -* Called By : -* -* -*****************************************************************************/ int nsfw_base_shutdown(int a, int b) { nsfw_call_ret(shutdown, (a, b)) } -/***************************************************************************** -* Prototype : nsfw_base_getsockname -* Description : linux getsockname api -* Input : int a -* struct sockaddr* b -* socklen_t* c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ +int nsfw_base_getaddrinfo(const char *a, const char *b, const struct addrinfo *c, struct addrinfo **d) +{ + nsfw_call_ret(getaddrinfo, (a, b, c, d)) +} + int nsfw_base_getsockname(int a, struct sockaddr* b, socklen_t* c) { nsfw_call_ret(getsockname, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_getpeername -* Description : linux getpername api -* Input : int a -* struct sockaddr* b -* socklen_t* c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_getpeername(int a, struct sockaddr* b, socklen_t* c) { nsfw_call_ret(getpeername, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_getsockopt -* Description : linux getsockopt api -* Input : int a -* int b -* int c -* void* d -* socklen_t* e -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_getsockopt(int a, int b, int c, void* d, socklen_t* e) { nsfw_call_ret(getsockopt, (a, b, c, d, e)) } -/***************************************************************************** -* Prototype : nsfw_base_setsockopt -* Description : linux setsockopt api -* Input : int a -* int b -* int c -* const void* d -* socklen_t e -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ int nsfw_base_setsockopt(int a, int b, int c, const void* d, socklen_t e) { nsfw_call_ret(setsockopt, (a, b, c, d, e)) } -/***************************************************************************** -* Prototype : nsfw_base_accept -* Description : linux accept api -* Input : int a -* struct sockaddr* b -* socklen_t* c -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ int nsfw_base_accept(int a, struct sockaddr* b, socklen_t* c) { nsfw_call_ret(accept, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_accept4 -* Description : linux accept4 api -* Input : int a -* struct sockaddr* b -* socklen_t* c -* int flags -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ int nsfw_base_accept4(int a, struct sockaddr* b, socklen_t* c, int flags) { nsfw_call_ret(accept4, (a, b, c, flags)) } -/***************************************************************************** -* Prototype : nsfw_base_connect -* Description : linux connect api -* Input : int a -* const struct sockaddr* b -* socklen_t c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_connect(int a, const struct sockaddr* b, socklen_t c) { nsfw_call_ret(connect, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_recv -* Description : linux recv api -* Input : int a -* void* b -* size_t c -* int d -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_recv(int a, void* b, size_t c, int d) { nsfw_call_ret(recv, (a, b, c, d)) } -/***************************************************************************** -* Prototype : nsfw_base_send -* Description : linux send api -* Input : int a -* const void* b -* size_t c -* int d -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_send(int a, const void* b, size_t c, int d) { nsfw_call_ret(send, (a, b, c, d)) } -/***************************************************************************** -* Prototype : nsfw_base_read -* Description : linux read api -* Input : int a -* void* b -* size_t c -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_read(int a, void* b, size_t c) { nsfw_call_ret(read, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_write -* Description : linux write api -* Input : int a -* const void* b -* size_t c -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_write(int a, const void* b, size_t c) { nsfw_call_ret(write, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_writev -* Description : linux writev api -* Input : int a -* const struct iovec * b -* int c -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -*****************************************************************************/ ssize_t nsfw_base_writev(int a, const struct iovec * b, int c) { nsfw_call_ret(writev, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_readv -* Description : linux readv api -* Input : int a -* const struct iovec * b -* int c -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_readv(int a, const struct iovec * b, int c) { nsfw_call_ret(readv, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_sendto -* Description : linux sendto api -* Input : int a -* const void * b -* size_t c -* int d -* const struct sockaddr *e -* socklen_t f -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -*****************************************************************************/ ssize_t nsfw_base_sendto(int a, const void * b, size_t c, int d, const struct sockaddr *e, socklen_t f) { nsfw_call_ret(sendto, (a, b, c, d, e, f)) } -/***************************************************************************** -* Prototype : nsfw_base_recvfrom -* Description : linux recvfrom api -* Input : int a -* void *b -* size_t c -* int d -* struct sockaddr *e -* socklen_t *f -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -*****************************************************************************/ ssize_t nsfw_base_recvfrom(int a, void *b, size_t c, int d,struct sockaddr *e, socklen_t *f) { nsfw_call_ret(recvfrom, (a, b, c, d, e, f)) } -/***************************************************************************** -* Prototype : nsfw_base_sendmsg -* Description : linux sendmsg api -* Input : int a -* const struct msghdr *b -* int flags -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_sendmsg(int a, const struct msghdr *b, int flags) { nsfw_call_ret(sendmsg, (a, b, flags)) } -/***************************************************************************** -* Prototype : nsfw_base_recvmsg -* Description : linux recvmsg api -* Input : int a -* struct msghdr *b -* int flags -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ ssize_t nsfw_base_recvmsg(int a, struct msghdr *b, int flags) { nsfw_call_ret(recvmsg, (a, b, flags)) } -/***************************************************************************** -* Prototype : nsfw_base_close -* Description : linux close api -* Input : int a -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_close(int a) { nsfw_call_ret(close, (a)) } -/***************************************************************************** -* Prototype : nsfw_base_select -* Description : linux select api -* Input : int a -* fd_set *b -* fd_set *c -* fd_set *d -* struct timeval *e -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ int nsfw_base_select(int a, fd_set *b, fd_set *c, fd_set *d, struct timeval *e) { nsfw_call_ret(select, (a, b, c, d, e)) } -/***************************************************************************** -* Prototype : nsfw_base_ioctl -* Description : linux ioctl api -* Input : int a -* unsigned long b -* unsigned long c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_ioctl(int a, unsigned long b, unsigned long c) { nsfw_call_ret(ioctl, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_fcntl -* Description : linux fcntl api -* Input : int a -* int b -* unsigned long c -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_fcntl(int a, int b, unsigned long c) { nsfw_call_ret(fcntl, (a, b, c)) } -/***************************************************************************** -* Prototype : nsfw_base_epoll_create -* Description : linux epoll_create api -* Input : int a -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_epoll_create(int a) { nsfw_call_ret(epoll_create, (a)) } -/***************************************************************************** -* Prototype : nsfw_base_epoll_create1 -* Description : linux epoll_create1 api -* Input : int a -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_epoll_create1(int a) { nsfw_call_ret(epoll_create1, (a)) } -/***************************************************************************** -* Prototype : nsfw_base_epoll_ctl -* Description : linux epoll_ctl api -* Input : int a -* int b -* int c -* struct epoll_event *d -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_epoll_ctl(int a, int b, int c, struct epoll_event *d) { nsfw_call_ret(epoll_ctl, (a, b, c, d)) } -/***************************************************************************** -* Prototype : nsfw_base_epoll_wait -* Description : linux epoll_wait api -* Input : int a -* struct epoll_event *b -* int c -* int d -* Output : None -* Return Value : int -* Calls : -* Called By : -* -*****************************************************************************/ int nsfw_base_epoll_wait(int a, struct epoll_event *b, int c, int d) { nsfw_call_ret(epoll_wait, (a, b, c, d)) } -/***************************************************************************** -* Prototype : nsfw_base_fork -* Description : linux fork api -* Input : void -* Output : None -* Return Value : pid_t -* Calls : -* Called By : -* -*****************************************************************************/ pid_t nsfw_base_fork(void) { nsfw_call_ret(fork, ()) diff --git a/src/framework/common/base/liblinuxapi/nsfw_lock_file.c b/src/framework/common/base/liblinuxapi/nsfw_lock_file.c deleted file mode 100644 index cef8d95..0000000 --- a/src/framework/common/base/liblinuxapi/nsfw_lock_file.c +++ /dev/null @@ -1,169 +0,0 @@ -/* -* -* 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 <errno.h> -#include <fcntl.h> -#include <unistd.h> - -#include "types.h" -#include "nstack_securec.h" -#include "nsfw_init.h" -#include "common_mem_api.h" - -#include "nstack_log.h" -#include "nsfw_maintain_api.h" -#include "nsfw_mgr_com_api.h" - -#include "nsfw_base_linux_api.h" -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C"{ -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -#define NSFW_FILE_PATH_LEN 128 -#define LOCK_FOLDER "/ip_module/" -#define LOCK_SUFFIX ".pid" - -#define read_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_RDLCK, (offset), (whence), (len)) -#define readw_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len)) -#define write_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_WRLCK, (offset), (whence), (len)) -#define writew_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len)) -#define un_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_UNLCK, (offset), (whence), (len)) - -i32 -nsfw_lock_reg (i32 fd, i32 cmd, i32 type, off_t offset, i32 whence, off_t len) -{ - struct flock lock_file; - lock_file.l_type = type; - lock_file.l_start = offset; - lock_file.l_whence = whence; - lock_file.l_len = len; - return (fcntl (fd, cmd, &lock_file)); -} - -/***************************************************************************** -* Prototype : nsfw_proc_start_with_lock -* Description : lock file start -* Input : u8 proc_type -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_proc_start_with_lock (u8 proc_type) -{ - NSFW_LOGINF ("lock_file init]type=%u", proc_type); - char *module_name = nsfw_get_proc_name (proc_type); - if (NULL == module_name) - { - NSFW_LOGERR ("proc type error]proc_type=%u", proc_type); - return 0; - } - - const char *directory = NSFW_DOMAIN_DIR; - const char *home_dir = getenv ("HOME"); - - if (getuid () != 0 && home_dir != NULL) - { - directory = home_dir; - } - - int ret; - char lock_fpath[NSFW_FILE_PATH_LEN] = { 0 }; - ret = STRCPY_S (lock_fpath, NSFW_FILE_PATH_LEN, directory); - if (EOK != ret) - { - NSFW_LOGERR ("lock init STRCPY_S failed]ret=%d", ret); - return -1; - } - - nsfw_mgr_com_mkdir_domainpath (lock_fpath); - - ret = STRCAT_S (lock_fpath, NSFW_FILE_PATH_LEN, module_name); - if (EOK != ret) - { - NSFW_LOGERR ("lock init STRCAT_S failed]ret=%d", ret); - return -1; - } - - ret = STRCAT_S (lock_fpath, NSFW_FILE_PATH_LEN, LOCK_SUFFIX); - if (EOK != ret) - { - NSFW_LOGERR ("lock init STRCAT_S failed]ret=%d", ret); - return -1; - } - - i32 fd; - if ((fd = open (lock_fpath, O_RDWR | O_CREAT, 0640)) == -1) - { /* file permission no large than 0640 */ - NSFW_LOGERR ("open lock file error!]path=%s,error = %d", lock_fpath, - errno); - return -1; - } - - int rc = nsfw_set_close_on_exec (fd); - if (rc == -1) - { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", fd, errno); - return -1; - } - - if (write_lock (fd, 0, SEEK_SET, 0) < 0) - { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("get lock file error!]path=%s,error = %d", lock_fpath, - errno); - return -1; - } - - char buf[32] = { 0 }; - if (ftruncate (fd, 0) < 0) - { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("ftruncate file error!]path=%s,error = %d", lock_fpath, - errno); - return -1; - } - - ret = - SNPRINTF_S (buf, sizeof (buf), sizeof (buf) - 1, "%ld", (long) getpid ()); - if (-1 == ret) - { - NSTCP_LOGERR ("SNPRINTF_S failed]ret=%d", ret); - (void) nsfw_base_close (fd); - return -1; - } - - if (write (fd, buf, strlen (buf) + 1) < 0) - { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("write file error!]path=%s,error = %d", lock_fpath, errno); - return -1; - } - - return 0; -} - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ diff --git a/src/framework/common/data_struct/eprb_tree.c b/src/framework/common/data_struct/eprb_tree.c index c8e616d..81ac846 100644 --- a/src/framework/common/data_struct/eprb_tree.c +++ b/src/framework/common/data_struct/eprb_tree.c @@ -15,6 +15,7 @@ */ #include "eprb_tree.h" +#include "nsfw_mem_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -25,464 +26,455 @@ extern "C" { /* * This function returns the first node (in sort order) of the tree. */ -struct ep_rb_node * -ep_rb_first (const struct ep_rb_root *root) +struct ep_rb_node *ep_rb_first(const struct ep_rb_root *root) { - if (NULL == root) - return NULL; + if (NULL == root) + return NULL; - struct ep_rb_node *n; - n = (struct ep_rb_node *) ADDR_SHTOL (root->rb_node); + struct ep_rb_node *n; - if (!n) + n = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node); + + if (!n) { - return NULL; + return NULL; } - while (n->rb_left) + while (n->rb_left) { - n = (struct ep_rb_node *) ADDR_SHTOL (n->rb_left); + n = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(n->rb_left); } - return n; + return n; } -void -__ep_rb_rotate_left (struct ep_rb_node *X, struct ep_rb_root *root) +void __ep_rb_rotate_left(struct ep_rb_node *X, struct ep_rb_root *root) { /************************** * rotate Node X to left * **************************/ - struct ep_rb_node *Y = (struct ep_rb_node *) ADDR_SHTOL (X->rb_right); - /* establish X->Right link */ - X->rb_right = Y->rb_left; + struct ep_rb_node *Y = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_right); + + /* estblish X->Right link */ + X->rb_right = Y->rb_left; - if (Y->rb_left != NULL) + if (Y->rb_left != NULL) { - ((struct ep_rb_node *) ADDR_SHTOL (Y->rb_left))->rb_parent = - (struct ep_rb_node *) ADDR_LTOSH_EXT (X); + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(Y->rb_left))->rb_parent = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); } - /* establish Y->Parent link */ - Y->rb_parent = X->rb_parent; + /* estblish Y->Parent link */ + Y->rb_parent = X->rb_parent; - if (X->rb_parent) + if (X->rb_parent) { - struct ep_rb_node *xParent = - (struct ep_rb_node *) ADDR_SHTOL (X->rb_parent); + struct ep_rb_node *xParent = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_parent); - if (X == ADDR_SHTOL (xParent->rb_left)) + if (X == SHMEM_ADDR_SHTOL(xParent->rb_left)) { - xParent->rb_left = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + xParent->rb_left = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); } - else + else { - xParent->rb_right = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + xParent->rb_right = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); } } - else + else { - root->rb_node = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + root->rb_node = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); } - /* link X and Y */ - Y->rb_left = (struct ep_rb_node *) ADDR_LTOSH_EXT (X); - X->rb_parent = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + /* link X and Y */ + Y->rb_left = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); + X->rb_parent = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); - return; + return; } -void -__ep_rb_rotate_right (struct ep_rb_node *X, struct ep_rb_root *root) +void __ep_rb_rotate_right(struct ep_rb_node *X, struct ep_rb_root *root) { /**************************** * rotate Node X to right * ****************************/ - struct ep_rb_node *Y = (struct ep_rb_node *) ADDR_SHTOL (X->rb_left); - /* establish X->Left link */ - X->rb_left = Y->rb_right; + struct ep_rb_node *Y = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_left); - if (Y->rb_right != NULL) + /* estblish X->Left link */ + X->rb_left = Y->rb_right; + + if (Y->rb_right != NULL) { - ((struct ep_rb_node *) ADDR_SHTOL (Y->rb_right))->rb_parent = - (struct ep_rb_node *) ADDR_LTOSH_EXT (X); + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(Y->rb_right))->rb_parent = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); } - /* establish Y->Parent link */ - Y->rb_parent = X->rb_parent; + /* estblish Y->Parent link */ + Y->rb_parent = X->rb_parent; - if (X->rb_parent) + if (X->rb_parent) { - struct ep_rb_node *xParent = - (struct ep_rb_node *) ADDR_SHTOL (X->rb_parent); + struct ep_rb_node *xParent = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_parent); - if (X == (struct ep_rb_node *) ADDR_SHTOL (xParent->rb_right)) + if (X == (struct ep_rb_node *) SHMEM_ADDR_SHTOL(xParent->rb_right)) { - xParent->rb_right = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + xParent->rb_right = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); } - else + else { - xParent->rb_left = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + xParent->rb_left = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); } } - else + else + { + root->rb_node = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); + } + + /* link X and Y */ + Y->rb_right = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); + X->rb_parent = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(Y); + + return; +} + +static inline int __ep_rb_is_color_local(struct ep_rb_node *node, int color) +{ + return (!node || node->color == color); +} + +static inline int __ep_rb_is_color(struct ep_rb_node *node, int color) +{ + return (!node + || ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(node))->color == + color); +} + +static inline void __ep_rb_set_color(struct ep_rb_node *node, int color) +{ + if (node != NULL) { - root->rb_node = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(node))->color = color; } +} - /* link X and Y */ - Y->rb_right = (struct ep_rb_node *) ADDR_LTOSH_EXT (X); - X->rb_parent = (struct ep_rb_node *) ADDR_LTOSH_EXT (Y); +/* Oops... What's the proper name? */ +static inline void __ep_rb_adjust(struct ep_rb_node *X, + struct ep_rb_root *root, + struct ep_rb_node *node) +{ + struct ep_rb_node *Parent = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_parent); + if (Parent) + { + if (Parent->rb_left == + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(node)) + { + Parent->rb_left = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); + } + else + { + Parent->rb_right = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); + } + } + else + { + root->rb_node = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(X); + } - return; } -#define EP_RBTREE_PARENT(X) ((struct ep_rb_node*) ADDR_SHTOL((X)->rb_parent)) +#define EP_RBTREE_PARENT(X) ((struct ep_rb_node*) SHMEM_ADDR_SHTOL((X)->rb_parent)) #define EP_RBTREE_GRANDF(X) EP_RBTREE_PARENT(EP_RBTREE_PARENT(X)) /* X, Y are for application */ -void -ep_rb_insert_color (struct ep_rb_node *X, struct ep_rb_root *root) +void ep_rb_insert_color(struct ep_rb_node *X, struct ep_rb_root *root) { /************************************* * maintain red-black tree balance * * after inserting node X * *************************************/ - /* check red-black properties */ - while (X != (struct ep_rb_node *) ADDR_SHTOL (root->rb_node) - && EP_RBTREE_PARENT (X)->color == EP_RB_RED) + + /* check red-black properties */ + while (X != (struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node) + && EP_RBTREE_PARENT(X)->color == EP_RB_RED) { - /* we have a violation */ - if (X->rb_parent == EP_RBTREE_GRANDF (X)->rb_left) + /* we have a violation */ + if (X->rb_parent == EP_RBTREE_GRANDF(X)->rb_left) { - struct ep_rb_node *Y = - (struct ep_rb_node *) ADDR_SHTOL (EP_RBTREE_GRANDF (X)->rb_right); + struct ep_rb_node *Y = + (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(EP_RBTREE_GRANDF(X)->rb_right); - if (Y && Y->color == EP_RB_RED) + if (!__ep_rb_is_color_local(Y, EP_RB_BLACK)) { - /* uncle is red */ - EP_RBTREE_PARENT (X)->color = EP_RB_BLACK; - Y->color = EP_RB_BLACK; - EP_RBTREE_GRANDF (X)->color = EP_RB_RED; - X = EP_RBTREE_GRANDF (X); + /* uncle is red */ + EP_RBTREE_PARENT(X)->color = EP_RB_BLACK; + Y->color = EP_RB_BLACK; + EP_RBTREE_GRANDF(X)->color = EP_RB_RED; + X = EP_RBTREE_GRANDF(X); } - else + else { - /* uncle is black */ - if (X == - (struct ep_rb_node *) - ADDR_SHTOL (EP_RBTREE_PARENT (X)->rb_right)) + /* uncle is black */ + if (X == + (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(EP_RBTREE_PARENT(X)->rb_right)) { - /* make X a left child */ - X = EP_RBTREE_PARENT (X); - __ep_rb_rotate_left (X, root); + /* make X a left child */ + X = EP_RBTREE_PARENT(X); + __ep_rb_rotate_left(X, root); } - /* recolor and rotate */ - EP_RBTREE_PARENT (X)->color = EP_RB_BLACK; - EP_RBTREE_GRANDF (X)->color = EP_RB_RED; - __ep_rb_rotate_right (EP_RBTREE_GRANDF (X), root); + /* recolor and rotate */ + EP_RBTREE_PARENT(X)->color = EP_RB_BLACK; + EP_RBTREE_GRANDF(X)->color = EP_RB_RED; + __ep_rb_rotate_right(EP_RBTREE_GRANDF(X), root); } } - else + else { - /* mirror image of above code */ - struct ep_rb_node *Y = - (struct ep_rb_node *) ADDR_SHTOL (EP_RBTREE_GRANDF (X)->rb_left); + /* miror image of above code */ + struct ep_rb_node *Y = + (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(EP_RBTREE_GRANDF(X)->rb_left); - if (Y && (Y->color == EP_RB_RED)) + if (!__ep_rb_is_color_local(Y, EP_RB_BLACK)) { - /* uncle is red */ - EP_RBTREE_PARENT (X)->color = EP_RB_BLACK; - Y->color = EP_RB_BLACK; - EP_RBTREE_GRANDF (X)->color = EP_RB_RED; - X = EP_RBTREE_GRANDF (X); + /* uncle is red */ + EP_RBTREE_PARENT(X)->color = EP_RB_BLACK; + Y->color = EP_RB_BLACK; + EP_RBTREE_GRANDF(X)->color = EP_RB_RED; + X = EP_RBTREE_GRANDF(X); } - else + else { - /* uncle is black */ - if (X == - (struct ep_rb_node *) - ADDR_SHTOL (EP_RBTREE_PARENT (X)->rb_left)) + /* uncle is black */ + if (X == + (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(EP_RBTREE_PARENT(X)->rb_left)) { - X = EP_RBTREE_PARENT (X); - __ep_rb_rotate_right (X, root); + X = EP_RBTREE_PARENT(X); + __ep_rb_rotate_right(X, root); } - EP_RBTREE_PARENT (X)->color = EP_RB_BLACK; - EP_RBTREE_GRANDF (X)->color = EP_RB_RED; - __ep_rb_rotate_left (EP_RBTREE_GRANDF (X), root); + EP_RBTREE_PARENT(X)->color = EP_RB_BLACK; + EP_RBTREE_GRANDF(X)->color = EP_RB_RED; + __ep_rb_rotate_left(EP_RBTREE_GRANDF(X), root); } } } - ((struct ep_rb_node *) ADDR_SHTOL (root->rb_node))->color = EP_RB_BLACK; + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node))->color = + EP_RB_BLACK; - return; + return; } -void -__ep_rb_erase_color (struct ep_rb_node *X, struct ep_rb_node *Parent, - struct ep_rb_root *root) +void __ep_rb_erase_color(struct ep_rb_node *X, struct ep_rb_node *Parent, + struct ep_rb_root *root) { /************************************* * maintain red-black tree balance * * after deleting node X * *************************************/ - while (X != (struct ep_rb_node *) ADDR_SHTOL (root->rb_node) - && (!X || X->color == EP_RB_BLACK)) + + while (X != (struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node) + && __ep_rb_is_color_local(X, EP_RB_BLACK)) { - if (Parent == NULL) + if (Parent == NULL) { - break; + break; } - if (X == (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_left)) + if (X == (struct ep_rb_node *) SHMEM_ADDR_SHTOL(Parent->rb_left)) { - struct ep_rb_node *W = - (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_right); + struct ep_rb_node *W = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(Parent->rb_right); - if (W->color == EP_RB_RED) + if (W->color == EP_RB_RED) { - W->color = EP_RB_BLACK; - Parent->color = EP_RB_RED; /* Parent != NIL? */ - __ep_rb_rotate_left (Parent, root); - W = (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_right); + W->color = EP_RB_BLACK; + Parent->color = EP_RB_RED; /* Parent != NIL? */ + __ep_rb_rotate_left(Parent, root); + W = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(Parent->rb_right); } - if ((!W->rb_left - || ((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color == - EP_RB_BLACK) && (!W->rb_right - || ((struct ep_rb_node *) - ADDR_SHTOL (W->rb_right))->color == - EP_RB_BLACK)) + if (__ep_rb_is_color(W->rb_left, EP_RB_BLACK) + && __ep_rb_is_color(W->rb_right, EP_RB_BLACK)) { - W->color = EP_RB_RED; - X = Parent; - Parent = (struct ep_rb_node *) ADDR_SHTOL (X->rb_parent); + W->color = EP_RB_RED; + X = Parent; + Parent = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_parent); } - else + else { - if (!W->rb_right - || ((struct ep_rb_node *) ADDR_SHTOL (W->rb_right))->color - == EP_RB_BLACK) + if (__ep_rb_is_color(W->rb_right, EP_RB_BLACK)) { - if (W->rb_left != NULL) - { - ((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color - = EP_RB_BLACK; - } - - W->color = EP_RB_RED; - __ep_rb_rotate_right (W, root); - W = (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_right); + __ep_rb_set_color(W->rb_left, EP_RB_BLACK); + + W->color = EP_RB_RED; + __ep_rb_rotate_right(W, root); + W = (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(Parent->rb_right); } - W->color = Parent->color; - Parent->color = EP_RB_BLACK; + W->color = Parent->color; + Parent->color = EP_RB_BLACK; - if (((struct ep_rb_node *) ADDR_SHTOL (W->rb_right))->color != - EP_RB_BLACK) - { - ((struct ep_rb_node *) ADDR_SHTOL (W->rb_right))->color = - EP_RB_BLACK; - } + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(W->rb_right))->color + = EP_RB_BLACK; - __ep_rb_rotate_left (Parent, root); - X = (struct ep_rb_node *) ADDR_SHTOL (root->rb_node); - break; + __ep_rb_rotate_left(Parent, root); + X = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node); + break; } } - else + else { - struct ep_rb_node *W = - (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_left); + struct ep_rb_node *W = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(Parent->rb_left); - if (W->color == EP_RB_RED) + if (W->color == EP_RB_RED) { - W->color = EP_RB_BLACK; - Parent->color = EP_RB_RED; /* Parent != NIL? */ - __ep_rb_rotate_right (Parent, root); - W = (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_left); + W->color = EP_RB_BLACK; + Parent->color = EP_RB_RED; /* Parent != NIL? */ + __ep_rb_rotate_right(Parent, root); + W = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(Parent->rb_left); } - if ((!W->rb_left - || (((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color == - EP_RB_BLACK)) && (!W->rb_right - || - (((struct ep_rb_node *) - ADDR_SHTOL (W->rb_right))->color == - EP_RB_BLACK))) + if (__ep_rb_is_color(W->rb_left, EP_RB_BLACK) + && __ep_rb_is_color(W->rb_right, EP_RB_BLACK)) { - W->color = EP_RB_RED; - X = Parent; - Parent = (struct ep_rb_node *) ADDR_SHTOL (X->rb_parent); + W->color = EP_RB_RED; + X = Parent; + Parent = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(X->rb_parent); } - else + else { - if (!W->rb_left - || ((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color - == EP_RB_BLACK) + if (__ep_rb_is_color(W->rb_left, EP_RB_BLACK)) { - if (W->rb_right != NULL) - { - ((struct ep_rb_node *) - ADDR_SHTOL (W->rb_right))->color = EP_RB_BLACK; - } - - W->color = EP_RB_RED; - __ep_rb_rotate_left (W, root); - W = (struct ep_rb_node *) ADDR_SHTOL (Parent->rb_left); + __ep_rb_set_color(W->rb_right, EP_RB_BLACK); + W->color = EP_RB_RED; + __ep_rb_rotate_left(W, root); + W = (struct ep_rb_node *) + SHMEM_ADDR_SHTOL(Parent->rb_left); } - W->color = Parent->color; - Parent->color = EP_RB_BLACK; + W->color = Parent->color; + Parent->color = EP_RB_BLACK; - if (((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color != - EP_RB_BLACK) - { - ((struct ep_rb_node *) ADDR_SHTOL (W->rb_left))->color = + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(W->rb_left))->color = EP_RB_BLACK; - } - __ep_rb_rotate_right (Parent, root); - X = (struct ep_rb_node *) ADDR_SHTOL (root->rb_node); - break; + __ep_rb_rotate_right(Parent, root); + X = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(root->rb_node); + break; } } } - if (X) + if (X) { - X->color = EP_RB_BLACK; + X->color = EP_RB_BLACK; } - return; + return; } -void -ep_rb_erase (struct ep_rb_node *node, struct ep_rb_root *root) +void ep_rb_erase(struct ep_rb_node *node, struct ep_rb_root *root) { - struct ep_rb_node *child, *parent; - int color; + struct ep_rb_node *child, *parent; + int color; - if (!node->rb_left) + if (!node->rb_left) { - child = (struct ep_rb_node *) ADDR_SHTOL (node->rb_right); + child = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_right); } - else if (!node->rb_right) + else if (!node->rb_right) { - child = (struct ep_rb_node *) ADDR_SHTOL (node->rb_left); + child = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_left); } - else + else { - struct ep_rb_node *old = node, *left; + struct ep_rb_node *old = node, *left; - node = (struct ep_rb_node *) ADDR_SHTOL (node->rb_right); + node = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_right); - while ((left = - (struct ep_rb_node *) ADDR_SHTOL (node->rb_left)) != NULL) + while ((left = + (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_left)) != + NULL) { - node = left; + node = left; } - if (old->rb_parent) - { - struct ep_rb_node *oldParent = - (struct ep_rb_node *) ADDR_SHTOL (old->rb_parent); - - if (oldParent->rb_left == - (struct ep_rb_node *) ADDR_LTOSH_EXT (old)) - { - oldParent->rb_left = - (struct ep_rb_node *) ADDR_LTOSH_EXT (node); - } - else - { - oldParent->rb_right = - (struct ep_rb_node *) ADDR_LTOSH_EXT (node); - } - } - else - { - root->rb_node = (struct ep_rb_node *) ADDR_LTOSH_EXT (node); - } + __ep_rb_adjust(node, root, old); - child = (struct ep_rb_node *) ADDR_SHTOL (node->rb_right); - parent = (struct ep_rb_node *) ADDR_SHTOL (node->rb_parent); - color = node->color; + child = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_right); + parent = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_parent); + color = node->color; - if (parent == old) + if (parent == old) { - parent = node; + parent = node; } - else + else { - if (child) + if (child) { - child->rb_parent = - (struct ep_rb_node *) ADDR_LTOSH_EXT (parent); + child->rb_parent = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(parent); } - parent->rb_left = (struct ep_rb_node *) ADDR_LTOSH_EXT (child); + parent->rb_left = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(child); - node->rb_right = old->rb_right; - ((struct ep_rb_node *) ADDR_SHTOL (old->rb_right))->rb_parent = - (struct ep_rb_node *) ADDR_LTOSH_EXT (node); + node->rb_right = old->rb_right; + ((struct ep_rb_node *) + SHMEM_ADDR_SHTOL(old->rb_right))->rb_parent = +(struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(node); } - node->color = old->color; - node->rb_parent = old->rb_parent; - node->rb_left = old->rb_left; - ((struct ep_rb_node *) ADDR_SHTOL (old->rb_left))->rb_parent = - (struct ep_rb_node *) ADDR_LTOSH_EXT (node); + node->color = old->color; + node->rb_parent = old->rb_parent; + node->rb_left = old->rb_left; + ((struct ep_rb_node *) SHMEM_ADDR_SHTOL(old->rb_left))->rb_parent = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(node); - if (color == EP_RB_BLACK) + if (color == EP_RB_BLACK) { - __ep_rb_erase_color (child, parent, root); + __ep_rb_erase_color(child, parent, root); } - return; + return; } - parent = (struct ep_rb_node *) ADDR_SHTOL (node->rb_parent); - color = node->color; + parent = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(node->rb_parent); + color = node->color; - if (child) + if (child) { - child->rb_parent = (struct ep_rb_node *) ADDR_LTOSH_EXT (parent); + child->rb_parent = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(parent); } - if (parent) - { - if (parent->rb_left == (struct ep_rb_node *) ADDR_LTOSH_EXT (node)) - { - parent->rb_left = (struct ep_rb_node *) ADDR_LTOSH_EXT (child); - } - else - { - parent->rb_right = (struct ep_rb_node *) ADDR_LTOSH_EXT (child); - } - } - else - { - root->rb_node = (struct ep_rb_node *) ADDR_LTOSH_EXT (child); - } + __ep_rb_adjust(child, root, node); - if (color == EP_RB_BLACK) + if (color == EP_RB_BLACK) { - __ep_rb_erase_color (child, parent, root); + __ep_rb_erase_color(child, parent, root); } - return; + + return; } #ifdef __cplusplus diff --git a/src/framework/common/data_struct/list.c b/src/framework/common/data_struct/list.c index d9ea5a4..ccdb039 100644 --- a/src/framework/common/data_struct/list.c +++ b/src/framework/common/data_struct/list.c @@ -17,87 +17,80 @@ #include "list.h" /** - * function-name : list_empty - * description : tests whether a list is empty - * parameter @head : the list to test. + * list_empty - tests whether a list is empty + * @head: the list to test. */ -inline int -list_empty (const struct list_head *head_of_list) +inline int list_empty(const struct list_head *head) { - return head_of_list->next == head_of_list; + return head->next == head; } -inline void -list_del (struct list_head *entry) +inline void list_del(struct list_head *entry) { - if (entry->prev == NULL || entry->next == NULL) + if (entry->prev == NULL || entry->next == NULL) { - return; + return; } - entry->next->prev = entry->prev; - entry->prev->next = entry->next; - entry->next = NULL; - entry->prev = NULL; + entry->next->prev = entry->prev; + entry->prev->next = entry->next; + entry->next = NULL; + entry->prev = NULL; } /*get the first element of the list, need to check if list empty or not before calling this.*/ -inline struct list_head * -list_get_first (struct list_head *head) +inline struct list_head *list_get_first(struct list_head *head) { - return head->next; + return head->next; } -inline void -list_add (struct list_head *newp, struct list_head *head) +inline void list_add(struct list_head *newp, struct list_head *head) { - head->next->prev = newp; - newp->next = head->next; - newp->prev = head; - head->next = newp; + head->next->prev = newp; + newp->next = head->next; + newp->prev = head; + head->next = newp; } -inline void -list_link (struct list_head *newhead, struct list_head *head) +inline void list_link(struct list_head *newhead, struct list_head *head) { - struct list_head *tmp; + struct list_head *tmp; - newhead->prev->next = head; - head->prev->next = newhead; + newhead->prev->next = head; + head->prev->next = newhead; - tmp = newhead->prev; - newhead->prev = head->prev; - head->prev = tmp; + tmp = newhead->prev; + newhead->prev = head->prev; + head->prev = tmp; } -inline void -list_add_tail (struct list_head *newp, struct list_head *head) +inline void list_add_tail(struct list_head *newp, struct list_head *head) { - list_add (newp, head->prev); + list_add(newp, head->prev); } -inline void -hlist_del_init (struct hlist_node *n) +inline void hlist_del_init(struct hlist_node *n) { - struct hlist_node *next_node = n->next; - struct hlist_node **pprev = n->pprev; + struct hlist_node *next = n->next; + struct hlist_node **pprev = n->pprev; - if (pprev == NULL && next_node == NULL) + if (pprev == NULL && next == NULL) { - return; + return; } - if (pprev) + /*null pointer validation already done. */ + if (pprev) { - *pprev = next_node; + *pprev = next; } - if (next_node) + if (next) { - next_node->pprev = pprev; + next->pprev = pprev; } - n->next = NULL; - n->pprev = NULL; + n->next = NULL; + n->pprev = NULL; } /** @@ -107,13 +100,12 @@ hlist_del_init (struct hlist_node *n) * @n: new node * @next: node in the hlist */ -inline void -hlist_add_before (struct hlist_node *node, struct hlist_node *next) +inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next) { - node->pprev = next->pprev; - node->next = next; - next->pprev = &node->next; - *(node->pprev) = node; + n->pprev = next->pprev; + n->next = next; + next->pprev = &n->next; + *(n->pprev) = n; } /** @@ -123,42 +115,38 @@ hlist_add_before (struct hlist_node *node, struct hlist_node *next) * @n: node in the hlist * @next: new node */ -inline void -hlist_add_after (struct hlist_node *node, struct hlist_node *next) +inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next) { - next->next = node->next; - node->next = next; - next->pprev = &node->next; - if (next->next) + next->next = n->next; + n->next = next; + next->pprev = &n->next; + if (next->next) { - next->next->pprev = &next->next; + next->next->pprev = &next->next; } } /* add after the head */ -inline void -hlist_add_head (struct hlist_node *node, struct hlist_head *h) +inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) { - struct hlist_node *first = h->first; + struct hlist_node *first = h->first; - node->next = first; - if (first) + n->next = first; + if (first) { - first->pprev = &node->next; + first->pprev = &n->next; } - h->first = node; - node->pprev = &h->first; + h->first = n; + n->pprev = &h->first; } -inline int -hlist_unhashed (const struct hlist_node *node) +inline int hlist_unhashed(const struct hlist_node *h) { - return !node->pprev; + return !h->pprev; } -inline int -hlist_empty (const struct hlist_head *node) +inline int hlist_empty(const struct hlist_head *h) { - return !node->first; + return !h->first; } diff --git a/src/framework/common/data_struct/pidinfo.c b/src/framework/common/data_struct/pidinfo.c index 08e551f..3095c0d 100644 --- a/src/framework/common/data_struct/pidinfo.c +++ b/src/framework/common/data_struct/pidinfo.c @@ -17,109 +17,105 @@ #include "pidinfo.h" #include "nstack_securec.h" -inline i32 -nsfw_pidinfo_init (nsfw_pidinfo * pidinfo) +inline i32 nsfw_pidinfo_init(nsfw_pidinfo * pidinfo) { - int retVal = - MEMSET_S (pidinfo, sizeof (nsfw_pidinfo), 0, sizeof (nsfw_pidinfo)); - if (EOK != retVal) + /*add return value check */ + int retVal = + memset_s(pidinfo, sizeof(nsfw_pidinfo), 0, sizeof(nsfw_pidinfo)); + if (EOK != retVal) { - return -1; + return -1; } - return 0; + return 0; } -inline int -nsfw_add_pid (nsfw_pidinfo * pidinfo, u32 pid) +inline int nsfw_add_pid(nsfw_pidinfo * pidinfo, u32 pid) { - u32 i; + u32 i; - for (i = 0; i < NSFW_MAX_FORK_NUM; i++) + for (i = 0; i < NSFW_MAX_FORK_NUM; i++) { - if ((0 == pidinfo->apid[i]) - && (__sync_bool_compare_and_swap (&pidinfo->apid[i], 0, pid))) + + if ((0 == pidinfo->apid[i]) + && (__sync_bool_compare_and_swap(&pidinfo->apid[i], 0, pid))) { - if (pidinfo->used_size < i + 1) + if (pidinfo->used_size < i + 1) { - pidinfo->used_size = i + 1; + pidinfo->used_size = i + 1; } - return 0; + return 0; } } - return -1; + return -1; } -inline int -nsfw_del_pid (nsfw_pidinfo * pidinfo, u32 pid) +inline int nsfw_del_pid(nsfw_pidinfo * pidinfo, u32 pid) { - u32 i; + u32 i; - for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) + for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) { - if (pid == pidinfo->apid[i]) + if (pid == pidinfo->apid[i]) { - pidinfo->apid[i] = 0; - return 0; + pidinfo->apid[i] = 0; + return 0; } } - return -1; + return -1; } -inline int -nsfw_del_last_pid (nsfw_pidinfo * pidinfo, u32 pid) +inline int nsfw_del_last_pid(nsfw_pidinfo * pidinfo, u32 pid) { - u32 i; - int count = 0; - int deleted = 0; - for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) + u32 i; + int count = 0; + int deleted = 0; + for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) { - if (pid == pidinfo->apid[i]) + if (pid == pidinfo->apid[i]) { - pidinfo->apid[i] = 0; - deleted = 1; - continue; + pidinfo->apid[i] = 0; + deleted = 1; + continue; } - if (pidinfo->apid[i] != 0) + if (pidinfo->apid[i] != 0) { - ++count; + ++count; } } - if (!deleted) + if (!deleted) { - return -1; + return -1; } - return count; + return count; } -inline int -nsfw_pid_exist (nsfw_pidinfo * pidinfo, u32 pid) +inline int nsfw_pid_exist(nsfw_pidinfo * pidinfo, u32 pid) { - u32 i; + u32 i; - for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) + for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) { - if (pid == pidinfo->apid[i]) + if (pid == pidinfo->apid[i]) { - return 1; + return 1; } } - return 0; + return 0; } -inline int -nsfw_pidinfo_empty (nsfw_pidinfo * pidinfo) +inline int nsfw_pidinfo_empty(nsfw_pidinfo * pidinfo) { - u32 i; - for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) + u32 i; + for (i = 0; i < pidinfo->used_size && i < NSFW_MAX_FORK_NUM; i++) { - if (pidinfo->apid[i] != 0) + if (pidinfo->apid[i] != 0) { - return 0; + return 0; } } - return 1; + return 1; } diff --git a/src/framework/common/data_struct/sha256.c b/src/framework/common/data_struct/sha256.c deleted file mode 100644 index f0773cf..0000000 --- a/src/framework/common/data_struct/sha256.c +++ /dev/null @@ -1,383 +0,0 @@ -/* -* -* 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. -*/ - -/*Possible access of out-of-bounds pointer: - The algorithms has been tested on purify. So no - out of bounds access possible.*/ - -/*Possible creation of out-of-bounds pointer - No Out of bounds pointers are created.- false positive.*/ - -#include <string.h> /* for mem copy function etc. */ -#include "sha256.h" -#include "nstack_securec.h" -#include "types.h" -#include "nstack_log.h" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ -#endif - -#define rotleft32(x,n) (((x) << n) | ((x) >> (32 - n))) -#define rotright32(x,n) (((x) >> n) | ((x) << (32 - n))) - -#if !defined(bswap_32) -#define bswap_32(x) ((rotright32((x), 24) & 0x00ff00ff) | (rotright32((x), 8) & 0xff00ff00)) -#endif - -#ifdef LITTLE_ENDIAN -#define SWAP_THE_BYTES -#else -#undef SWAP_THE_BYTES -#endif - -#define ch(a,b,c) ((c) ^ ((a) & ((b) ^ (c)))) -#define maj(a,b,c) (((a) & (b)) | ((c) & ((a) ^ (b)))) - - /* round transforms for the SHA256 & SHA512 compression functions */ - -#define vf(m,n) v[(m - n) & 7] - -#define hf(n) (p[n & 15] += \ - g_1(p[(n + 14) & 15]) + p[(n + 9) & 15] + g_0(p[(n + 1) & 15])) - -#define v_cycle(m,n) \ -{ \ - vf(7,m) += (n ? hf(m) : p[m]) + k_0[m+n] \ - + s_1(vf(4,m)) + ch(vf(4,m),vf(5,m),vf(6,m)); \ - vf(3,m) += vf(7,m); \ - vf(7,m) += s_0(vf(0,m))+ maj(vf(0,m),vf(1,m),vf(2,m)); \ -} - -#define SHA256_MASK (SHA256_BLOCK_SIZE - 1) /* SHA256_MASK */ - -#if defined(SWAP_THE_BYTES) -#define bsw_32(p,n) \ -{ \ - u32 _i = (n); \ - while (_i--) \ - { \ - ((u32*)p)[_i] = bswap_32(((u32*)p)[_i]); \ - } \ -} - -#else -#define bsw_32(p,n) -#endif - -#define s_0(x) (rotright32((x), 2) ^ rotright32((x), 13) ^ rotright32((x), 22)) -#define s_1(x) (rotright32((x), 6) ^ rotright32((x), 11) ^ rotright32((x), 25)) -#define g_0(x) (rotright32((x), 7) ^ rotright32((x), 18) ^ ((x) >> 3)) -#define g_1(x) (rotright32((x), 17) ^ rotright32((x), 19) ^ ((x) >> 10)) -#define k_0 k256 - -/* rotated SHA256 round definition. Unlike swapping the variables as in */ -/* FIPS-180, different variables are being 'rotated' on each round, */ -/* returning to their starting positions every 8 rounds */ - -#define q(i) v##i - -#define one_cycle(a,b,c,d,e,f,g,h,k,w) \ - q(h) += s_1(q(e)) + ch(q(e), q(f), q(g)) + k + w; \ - q(d) += q(h); q(h) += s_0(q(a)) + maj(q(a), q(b), q(c)) - -/* -Description: SHA256 mixing data -Value Range: None -Access: Used to mix with data to create SHA256 key. -Remarks: -*/ -static const u32 k256[64] = { - 010242427630, 016115642221, 026560175717, 035155355645, - 07125541133, 013174210761, 022217701244, 025307057325, - 033001725230, 02240655401, 04414302676, 012503076703, - 016257456564, 020067530776, 023367003247, 030146770564, - 034446664701, 035757443606, 01760316706, 04403120714, - 05572226157, 011235102252, 013454124734, 016676304332, - 023017450522, 025014343155, 026000623710, 027726277707, - 030670005763, 032551710507, 0662461521, 02412224547, - 04755605205, 05606620470, 011513066774, 012316006423, - 014502471524, 016632405273, 020160544456, 022234426205, - 024257764241, 025006463113, 030222705560, 030733050643, - 032144564031, 032646203044, 036403432605, 02032520160, - 03151140426, 03615666010, 04722073514, 06454136265, - 07107006263, 011666125112, 013347145117, 015013467763, - 016443701356, 017051261557, 020462074024, 021461601010, - 022057577772, 024424066353, 027676321767, 030634274362, -}; - -#define v_ v -#define ptr p - -/*===========================================================================*\ - Function :Sha256_compile__ - Description : This function generates the digest value for SHA256. - Compile 64 bytes of hash data into SHA256 digest value - Calls : mem copy - Secure mem copy function. - Called by : - Return : This is a static internal function which doesn't return any value. - Parameters : - SHA256_CTX ctx[1] - - Note : this routine assumes that the byte order in the - ctx->wbuf[] at this point is such that low address bytes in - the ORIGINAL byte stream will go into the high end of - words on BOTH big and little endian systems. -\*===========================================================================*/ -NSTACK_STATIC void -Sha256_compile__ (SHA256_CTX ctx[1]) -{ - - /* macros defined above to this function i.e. v_ and ptr should not be removed */ - /* v_cycle - for 0 to 15 */ - u32 i; - u32 *ptr = ctx->wbuf; - u32 v_[8]; - - int ret = MEMCPY_S (v_, 8 * sizeof (u32), ctx->hash, 8 * sizeof (u32)); - if (EOK != ret) - { - NSPOL_LOGERR ("MEMCPY_S failed"); - return; - } - - for (i = 0; i < 64; i += 16) - { - /*v_cycle operations from 0 to 15 */ - v_cycle (0, i); - v_cycle (1, i); - v_cycle (2, i); - v_cycle (3, i); - v_cycle (4, i); - v_cycle (5, i); - v_cycle (6, i); - v_cycle (7, i); - v_cycle (8, i); - v_cycle (9, i); - v_cycle (10, i); - v_cycle (11, i); - v_cycle (12, i); - v_cycle (13, i); - v_cycle (14, i); - v_cycle (15, i); - } - - /* update the context */ - ctx->hash[0] += v_[0]; - ctx->hash[1] += v_[1]; - ctx->hash[2] += v_[2]; - ctx->hash[3] += v_[3]; - ctx->hash[4] += v_[4]; - ctx->hash[5] += v_[5]; - ctx->hash[6] += v_[6]; - ctx->hash[7] += v_[7]; - - return; -} - -#undef v_ -#undef ptr - -/*===========================================================================*\ - Function :Sha256_upd - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - const unsigned char data[] - - size_t len - - Note : -\*===========================================================================*/ -void -Sha256_upd (SHA256_CTX sha256_ctx[1], const u8 data[], size_t len) -{ - u32 pos = (u32) (sha256_ctx->count[0] & SHA256_MASK); - u32 capacity = SHA256_BLOCK_SIZE - pos; - const u8 *sp = data; - int ret; - - if ((sha256_ctx->count[0] += (u32) len) < len) - { - ++(sha256_ctx->count[1]); - } - - while (len >= capacity) - { - - /* tranfer whole blocks while possible */ - ret = - MEMCPY_S (((u8 *) sha256_ctx->wbuf) + pos, capacity, sp, capacity); - if (EOK != ret) - { - NSPOL_LOGERR ("MEMCPY_S failed"); - return; - } - - sp += capacity; - len -= capacity; - capacity = SHA256_BLOCK_SIZE; - pos = 0; - bsw_32 (sha256_ctx->wbuf, SHA256_BLOCK_SIZE >> 2); - Sha256_compile__ (sha256_ctx); - } - - if (len != 0) - { - ret = - MEMCPY_S (((u8 *) sha256_ctx->wbuf) + pos, (u32) len, sp, (u32) len); - if (EOK != ret) - { - NSPOL_LOGERR ("MEMCPY_S failed"); - return; - } - } - - return; -} - -/* the Final padding and digest calculation of SHA256 */ - -/*===========================================================================*\ - Function :SHA_fin1 - Description : - Calls : - Called by : - Return :void - - Parameters : - unsigned char hval[] - - SHA256_CTX ctx[1] - - const unsigned int hlen - - Note : -\*===========================================================================*/ -NSTACK_STATIC void -SHA_fin1 (u8 hval[], SHA256_CTX ctx[1], const unsigned int hlen) -{ - u32 i = (u32) (ctx->count[0] & SHA256_MASK); - - /* Not unusual shift operation. Checked with purify. */ - - /*put bytes in the buffer in an order in which references to */ - /*32-bit words will put bytes with lower addresses into the */ - /*top of 32 bit words on BOTH big and little endian machines */ - bsw_32 (ctx->wbuf, (i + 3) >> 2); - - /*now it is needed to mask valid bytes and add padding which is */ - /*a single 1 bit and as many zero bits as necessary. Note that */ - /*we can always add the first padding byte here because the */ - /*buffer always has at least one empty slot */ - ctx->wbuf[i >> 2] &= (u32) 0xffffff80 << 8 * (~i & 3); - ctx->wbuf[i >> 2] |= (u32) 0x00000080 << 8 * (~i & 3); - - if (i > SHA256_BLOCK_SIZE - 9) - { - if (i < 60) - { - ctx->wbuf[15] = 0; - } - - Sha256_compile__ (ctx); - i = 0; - } - else - { - /* compute a word index for the empty buffer positions */ - i = (i >> 2) + 1; - } - - while (i < 14) - { - /* and zero pad all but last two positions */ - ctx->wbuf[i++] = 0; - } - - ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 29); - ctx->wbuf[15] = ctx->count[0] << 3; - Sha256_compile__ (ctx); - - for (i = 0; i < hlen; ++i) - { - hval[i] = (u8) (ctx->hash[i >> 2] >> (8 * (~i & 3))); - } - - return; -} - -/* -Description: Internal data for SHA256 digest calculation -Value Range: None -Access: Used to store internal data for SHA256 digest calculation -Remarks: -*/ -static const u32 g_i256[] = { - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 -}; - -/*===========================================================================*\ - Function :Sha256_set - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - Note : -\*===========================================================================*/ -void -Sha256_set (SHA256_CTX sha256_ctx[1]) -{ - int ret; - sha256_ctx->count[0] = sha256_ctx->count[1] = 0; - - ret = - MEMCPY_S (sha256_ctx->hash, sizeof (sha256_ctx->hash), g_i256, - sizeof (g_i256)); - if (EOK != ret) - { - NSPOL_LOGERR ("MEMCPY_S failed"); - return; - } - - return; -} - -/*===========================================================================*\ - Function :Sha256_fin - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - unsigned char hval[] - - Note : -\*===========================================================================*/ -void -Sha256_fin (SHA256_CTX ctx[1], u8 hval[]) -{ - SHA_fin1 (hval, ctx, SHA256_DIGEST_SIZE); - - return; -} - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif diff --git a/src/framework/common/include/arch/x86/dmm_atomic.h b/src/framework/common/include/arch/x86/dmm_atomic.h deleted file mode 100644 index fae99c2..0000000 --- a/src/framework/common/include/arch/x86/dmm_atomic.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* -* 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 _DMM_ATOMIC_H__ARCH_X86_ -#define _DMM_ATOMIC_H__ARCH_X86_ - -#include "generic/dmm_atomic.h" - -#endif /* #ifndef _DMM_ATOMIC_H__ARCH_X86_ */ diff --git a/src/framework/common/include/arch/x86/dmm_barrier.h b/src/framework/common/include/arch/x86/dmm_barrier.h deleted file mode 100644 index bf53650..0000000 --- a/src/framework/common/include/arch/x86/dmm_barrier.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* -* 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 _DMM_BARRIER_H__ARCH_X86_ -#define _DMM_BARRIER_H__ARCH_X86_ - -#include "generic/dmm_barrier.h" - -#endif /* #ifndef _DMM_BARRIER_H__ARCH_X86_ */ diff --git a/src/framework/common/include/arch/x86/dmm_pause.h b/src/framework/common/include/arch/x86/dmm_pause.h deleted file mode 100644 index 56c60f0..0000000 --- a/src/framework/common/include/arch/x86/dmm_pause.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* -* 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 _DMM_PAUSE_H_ -#define _DMM_PAUSE_H_ - -#include <emmintrin.h> - -inline static void -dmm_pause (void) -{ - _mm_pause (); -} - -#define DMM_PAUSE_WHILE(cond) do { dmm_pause(); } while (!!(cond)) -#define DMM_WHILE_PAUSE(cond) do { while (!!(cond)) dmm_pause(); } while (0) - -#endif /* #ifndef _DMM_PAUSE_H_ */ diff --git a/src/framework/common/include/arch/x86/dmm_rwlock.h b/src/framework/common/include/arch/x86/dmm_rwlock.h deleted file mode 100644 index 0c31329..0000000 --- a/src/framework/common/include/arch/x86/dmm_rwlock.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* -* 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 _DMM_RWLOCK_H__ARCH_X86_ -#define _DMM_RWLOCK_H__ARCH_X86_ - -#include "generic/dmm_rwlock.h" - -#endif /* #ifndef _DMM_RWLOCK_H__ARCH_X86_ */ diff --git a/src/framework/common/include/arch/x86/dmm_spinlock.h b/src/framework/common/include/arch/x86/dmm_spinlock.h deleted file mode 100644 index 69ed9a6..0000000 --- a/src/framework/common/include/arch/x86/dmm_spinlock.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* -* 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 _DMM_SPINLOCK_H__ARCH_X86_ -#define _DMM_SPINLOCK_H__ARCH_X86_ - -#include "generic/dmm_spinlock.h" - -#endif /* #ifndef _DMM_SPINLOCK_H__ARCH_X86_ */ diff --git a/src/framework/common/include/ephlist.h b/src/framework/common/include/ephlist.h deleted file mode 100644 index 90491b0..0000000 --- a/src/framework/common/include/ephlist.h +++ /dev/null @@ -1,199 +0,0 @@ -/* -* -* 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 _EPHLIST_H_ -#define _EPHLIST_H_ - -#include <stdio.h> -#include "types.h" -#include "common_mem_pal.h" -#include "common_mem_buf.h" -#include "common_pal_bitwide_adjust.h" -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ -#endif - -struct ep_hlist_node -{ - struct ep_hlist_node *next, **pprev; -}; - -struct ep_node_list -{ - struct ep_hlist_node *head; - struct ep_hlist_node *tail; -}; - -struct ep_hlist -{ - struct ep_hlist_node node; - struct ep_hlist_node *head; - struct ep_hlist_node *tail; -}; - -#define ep_hlist_entry(ptr, type, member) container_of(ptr, type, member) - -#define EP_HLIST_INIT_NODE(node) {\ - (node)->next = NULL;\ - (node)->pprev = NULL; \ - } - -#define EP_HLIST_INIT(ptr) {\ - EP_HLIST_INIT_NODE(&((ptr)->node)); \ - (ptr)->head = (struct ep_hlist_node*)ADDR_LTOSH_EXT(&((ptr)->node)); \ - (ptr)->tail = (struct ep_hlist_node*)ADDR_LTOSH_EXT(&((ptr)->node)); \ - } - -#define EP_HLIST_PREV(ptr) ((struct ep_hlist_node*)(ADDR_SHTOL((ptr)->pprev))) -/* list check may below zero check header, because if app crash before - do list->size++, it will lead problem */ -#define EP_HLIST_EMPTY(list) (NULL == ((struct ep_hlist_node*)ADDR_SHTOL((list)->head))->next) -#define EP_HLIST_NODE_LINKED(node) (!(!(node)->pprev)) - -static __inline void ep_hlist_del (struct ep_hlist *list, - struct ep_hlist_node *n); -static __inline void ep_hlist_add_tail (struct ep_hlist *list, - struct ep_hlist_node *node); - -/* - * list , n are local pointer, don't need to cast - */ -static __inline void -ep_hlist_del (struct ep_hlist *list, struct ep_hlist_node *n) -{ - if (!EP_HLIST_NODE_LINKED (n)) - return; - EP_HLIST_PREV (n)->next = n->next; - if (n->next) - { - ((struct ep_hlist_node *) ADDR_SHTOL (n->next))->pprev = n->pprev; - } - else - { - list->tail = (struct ep_hlist_node *) (n->pprev); - } - EP_HLIST_INIT_NODE (n); -} - -/** - * list, node are local pointer , don't need to case - */ -static __inline void -ep_hlist_add_tail (struct ep_hlist *list, struct ep_hlist_node *node) -{ - struct ep_hlist_node *tail = - (struct ep_hlist_node *) ADDR_SHTOL (list->tail); - EP_HLIST_INIT_NODE (node); - node->pprev = (struct ep_hlist_node **) ADDR_LTOSH_EXT (&tail->next); - tail->next = (struct ep_hlist_node *) ADDR_LTOSH_EXT (node); - list->tail = (struct ep_hlist_node *) ADDR_LTOSH_EXT (node); -} - -/*#########################################################*/ -struct list_node -{ - struct list_node *next; -}; - -struct ep_list -{ - struct list_node node; - struct list_node *head; -}; - -#define ep_list_entry(ptr, type, member) container_of(ptr, type, member) - -#define EP_LIST_INIT_NODE(node) {\ - (node)->next = NULL;\ - } - -#define EP_LIST_INIT(ptr) {\ - EP_LIST_INIT_NODE(&((ptr)->node)); \ - (ptr)->head = (struct list_node*)ADDR_LTOSH_EXT(&((ptr)->node)); \ - } - -#define EP_LIST_EMPTY(list) (NULL == ((struct list_node*)ADDR_SHTOL((list)->head))->next) - -static __inline void ep_list_del (struct ep_list *list, struct list_node *n); -static __inline void ep_list_add_tail (struct ep_list *list, - struct list_node *node); - -/* - * list , n are local pointer, don't need to cast - */ -static __inline void -ep_list_del (struct ep_list *list, struct list_node *n) -{ - if (NULL == n) - { - return; - } - - struct list_node *p_node; - struct list_node *p_prev = NULL; - p_node = ((struct list_node *) ADDR_SHTOL (list->head)); - while (NULL != p_node && p_node != n) - { - p_prev = p_node; - p_node = ((struct list_node *) ADDR_SHTOL (p_node->next)); - } - - if (p_node != n || p_prev == NULL) - { - return; - } - - p_prev->next = n->next; - - EP_LIST_INIT_NODE (n); - return; -} - -/** - * list, node are local pointer , don't need to case - */ -static __inline void -ep_list_add_tail (struct ep_list *list, struct list_node *node) -{ - - struct list_node *p_node; - struct list_node *p_prev = NULL; - p_node = ((struct list_node *) ADDR_SHTOL (list->head)); - while (NULL != p_node) - { - p_prev = p_node; - p_node = ((struct list_node *) ADDR_SHTOL (p_node->next)); - } - - if (NULL == p_prev) - { - return; - } - - EP_LIST_INIT_NODE (node); - p_prev->next = (struct list_node *) ADDR_LTOSH_EXT (node); - return; -} - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif - -#endif /* _HLIST_H_ */ diff --git a/src/framework/common/include/generic/dmm_atomic.h b/src/framework/common/include/generic/dmm_atomic.h deleted file mode 100644 index 637306b..0000000 --- a/src/framework/common/include/generic/dmm_atomic.h +++ /dev/null @@ -1,177 +0,0 @@ -/* -* -* 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 _DMM_ATOMIC_H_ -#define _DMM_ATOMIC_H_ - -/* atomic 32 bit operation */ - -typedef struct -{ - volatile int cnt; -} dmm_atomic_t; - -inline static int -dmm_atomic_get (dmm_atomic_t * a) -{ - return a->cnt; -} - -inline static int -dmm_atomic_add (dmm_atomic_t * a, int n) -{ - return __sync_fetch_and_add (&a->cnt, n); -} - -inline static int -dmm_atomic_sub (dmm_atomic_t * a, int n) -{ - return __sync_fetch_and_sub (&a->cnt, n); -} - -inline static int -dmm_atomic_and (dmm_atomic_t * a, int n) -{ - return __sync_fetch_and_and (&a->cnt, n); -} - -inline static int -dmm_atomic_or (dmm_atomic_t * a, int n) -{ - return __sync_fetch_and_or (&a->cnt, n); -} - -inline static int -dmm_atomic_xor (dmm_atomic_t * a, int n) -{ - return __sync_fetch_and_xor (&a->cnt, n); -} - -inline static int -dmm_atomic_swap (dmm_atomic_t * a, int o, int n) -{ - return __sync_val_compare_and_swap (&a->cnt, o, n); -} - -inline static int -dmm_atomic_add_return (dmm_atomic_t * a, int n) -{ - return __sync_add_and_fetch (&a->cnt, n); -} - -inline static int -dmm_atomic_sub_return (dmm_atomic_t * a, int n) -{ - return __sync_sub_and_fetch (&a->cnt, n); -} - -inline static int -dmm_atomic_and_return (dmm_atomic_t * a, int n) -{ - return __sync_and_and_fetch (&a->cnt, n); -} - -inline static int -dmm_atomic_or_return (dmm_atomic_t * a, int n) -{ - return __sync_or_and_fetch (&a->cnt, n); -} - -inline static int -dmm_atomic_xor_return (dmm_atomic_t * a, int n) -{ - return __sync_xor_and_fetch (&a->cnt, n); -} - -/* atomit 64bit operation */ - -typedef struct -{ - volatile long long int cnt; -} dmm_atomic64_t; - -inline static long long int -dmm_atomic64_get (dmm_atomic64_t * a) -{ - return a->cnt; -} - -inline static long long int -dmm_atomic64_add (dmm_atomic64_t * a, int n) -{ - return __sync_fetch_and_add (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_sub (dmm_atomic64_t * a, int n) -{ - return __sync_fetch_and_sub (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_and (dmm_atomic64_t * a, int n) -{ - return __sync_fetch_and_and (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_or (dmm_atomic64_t * a, int n) -{ - return __sync_fetch_and_or (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_xor (dmm_atomic64_t * a, int n) -{ - return __sync_fetch_and_xor (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_swap (dmm_atomic_t * a, int o, int n) -{ - return __sync_val_compare_and_swap (&a->cnt, o, n); -} - -inline static long long int -dmm_atomic64_add_return (dmm_atomic64_t * a, int n) -{ - return __sync_add_and_fetch (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_sub_return (dmm_atomic64_t * a, int n) -{ - return __sync_sub_and_fetch (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_and_return (dmm_atomic64_t * a, int n) -{ - return __sync_and_and_fetch (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_or_return (dmm_atomic64_t * a, int n) -{ - return __sync_or_and_fetch (&a->cnt, n); -} - -inline static long long int -dmm_atomic64_xor_return (dmm_atomic64_t * a, int n) -{ - return __sync_xor_and_fetch (&a->cnt, n); -} - -#endif /* #ifndef _DMM_ATOMIC_H_ */ diff --git a/src/framework/common/include/generic/dmm_spinlock.h b/src/framework/common/include/generic/dmm_spinlock.h deleted file mode 100644 index be183a6..0000000 --- a/src/framework/common/include/generic/dmm_spinlock.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* -* 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 _DMM_SPINLOCK_H_ -#define _DMM_SPINLOCK_H_ - -#include "dmm_pause.h" - -typedef struct -{ - volatile int lock; -} dmm_spinlock_t; - -inline static void -dmm_spin_init (dmm_spinlock_t * spinlock) -{ - spinlock->lock = 0; -} - -inline static void -dmm_spin_lock (dmm_spinlock_t * spinlock) -{ - while (0 != __sync_lock_test_and_set (&spinlock->lock, 1)) - { - DMM_PAUSE_WHILE (spinlock->lock); - } -} - -inline static int -dmm_spin_trylock (dmm_spinlock_t * spinlock) -{ - return 0 == __sync_lock_test_and_set (&spinlock->lock, 1); -} - -inline static void -dmm_spin_unlock (dmm_spinlock_t * spinlock) -{ - spinlock->lock = 0; -} - -#endif /* #ifndef _DMM_SPINLOCK_H_ */ diff --git a/src/framework/common/include/sha256.h b/src/framework/common/include/sha256.h deleted file mode 100644 index b1c7f3c..0000000 --- a/src/framework/common/include/sha256.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -* -* 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 _SHA256_H_ -#define _SHA256_H_ -#include "types.h" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ -#endif - -/* Note that the following function prototypes are the same */ -/* for both the bit and byte oriented implementations. But */ -/* the length fields are in bytes or bits as is appropriate */ -/* for the version used. Bit sequences are arrays of bytes */ -/* in which bit sequence indexes increase from the most to */ -/* the least significant end of each byte */ - -#define SHA256_DIGEST_SIZE 32 /* in bytes */ -#define SHA256_BLOCK_SIZE 64 /* in bytes */ - -typedef struct -{ - u32 count[2]; - u32 hash[8]; - u32 wbuf[16]; -} SHA256_CTX; - -/* SHA256 hash data in an array of bytes into hash buffer */ -/* and call the hash_compile function as required. */ - -/*===========================================================================*\ - Function :Sha256_upd - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - const unsigned char data[] - - size_t len - - Note : -\*===========================================================================*/ -void Sha256_upd (SHA256_CTX ctx[1], const u8 data[], size_t len); - -/* SHA256 Final padding and digest calculation */ - -/*===========================================================================*\ - Function :Sha256_set - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - Note : -\*===========================================================================*/ -void Sha256_set (SHA256_CTX ctx[1]); - -/*===========================================================================*\ - Function :Sha256_fin - Description : - Calls : - Called by : - Return :void - - Parameters : - SHA256_CTX ctx[1] - - unsigned char hval[] - - Note : -\*===========================================================================*/ -void Sha256_fin (SHA256_CTX ctx[1], u8 hval[]); - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif - -#endif /* _SHA256_H_ */ diff --git a/src/framework/common/include/types.h b/src/framework/common/include/types.h deleted file mode 100644 index bd4d80b..0000000 --- a/src/framework/common/include/types.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* -* 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 clib_types_h -#define clib_types_h -#include <stddef.h> - -/* Standard CLIB types. */ - -/* Define signed and unsigned 8, 16, 32, and 64 bit types - and machine signed/unsigned word for all architectures. */ -typedef char i8; -typedef short i16; - -typedef unsigned char u8; -typedef unsigned short u16; - -typedef int i32; -typedef long long i64; - -typedef unsigned int u32; -typedef unsigned long long u64; - -#ifndef bool -#define bool int -#endif - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef true -#define true 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef false -#define false 0 -#endif - -#ifndef NULL -#define NULL ((void *)0) -#endif - -#define PRIMARY_ADDR - -typedef struct _nsfw_res -{ - u8 alloc_flag; - u8 u8Reserve; - u16 chk_count; - u32 data; -} nsfw_res; - -static inline void -res_alloc (nsfw_res * res) -{ - res->alloc_flag = TRUE; - res->chk_count = 0; - res->u8Reserve = 0; -} - -static inline int -res_free (nsfw_res * res) -{ - if (TRUE != res->alloc_flag) - { - return -1; - } - res->chk_count = 0; - res->alloc_flag = FALSE; - return 0; -} - -#define NSFW_THREAD __thread - -#endif /*clib_types_h */ diff --git a/src/framework/common/mem_mgr/include/nsfw_mem_desc.h b/src/framework/common/mem_mgr/include/nsfw_mem_desc.h deleted file mode 100644 index 9a14c8d..0000000 --- a/src/framework/common/mem_mgr/include/nsfw_mem_desc.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -* -* 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 _NSFW_MEM_DESC_H -#define _NSFW_MEM_DESC_H -#include <sys/types.h> -#include <unistd.h> -#include <string.h> -#include "nsfw_mem_api.h" -#include "nsfw_mgr_com_api.h" -#include "nsfw_ring_data.h" - -#define NSFW_MEM_NOT_INIT (0) -#define NSFW_MEM_INIT_ERR (1) -#define NSFW_MEM_INIT_OK (2) - -#define NSFW_NAME_LENCHECK_RET(name, desc) \ - { \ - i32 inamelen = strlen(name); \ - if (inamelen >= NSFW_MEM_APPNAME_LENGTH) \ - { \ - NSCOMM_LOGERR("name length check fail] desc=%s, name len=%d, expected max=%d", \ - #desc, inamelen, NSFW_MEM_APPNAME_LENGTH); \ - return NSFW_MEM_ERR; \ - } \ - } - -#define NSFW_NAME_LENCHECK_RET_NULL(name, desc) \ - { \ - i32 inamelen = strlen(name); \ - if (inamelen >= NSFW_MEM_APPNAME_LENGTH) \ - { \ - NSCOMM_LOGERR("name length check fail] desc=%s, name len=%d, expected max=%d", \ - #desc, inamelen, NSFW_MEM_APPNAME_LENGTH); \ - return NULL; \ - } \ - } - -#define NSFW_MEM_PARA_CHECK_RET(handle, pdata, desc, num) {\ - if ((NULL == (handle)) || (NULL == (pdata)) || (num <= 0)\ - || (((struct nsfw_mem_ring*)(handle))->memtype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s,mhandle=%p, pdata=%p, inum=%d", desc, (handle), (pdata), num); \ - return 0; \ - } \ - } - -#define NSFW_MEM_ENQ_PARA_CHECK_RET(handle, desc) {\ - if ((NULL == (handle)) \ - || (((struct nsfw_mem_ring*)(handle))->memtype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s,mhandle=%p", desc, (handle)); \ - return 0; \ - } \ - } - -#define NSFW_MEM_NAME_CHECK_RET_ERR(pname, desc) {\ - if ((NULL == (pname)) || ((pname)->entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s, pname=%p, mtype=%d", desc, pname, (pname) ? (pname)->entype:-1); \ - return NSFW_MEM_ERR; \ - } \ - } - -#define NSFW_MEM_NAME_CHECK_RET_NULL(pname, desc) {\ - if ((NULL == (pname)) || ((pname)->entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s, pname=%p, mtype=%d", desc, pname, (pname) ? (pname)->entype:-1); \ - return NULL; \ - } \ - } - -#define NSFW_MEM_RING_CHECK_RET(pringinfo, pringhandle_array, iringnum) {\ - if ((NULL == pringinfo) || (NULL == pringhandle_array) || (pringinfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] pringinfo=%p, iringnum=%d, pringhandle_array=%p, mtype=%d", \ - pringinfo, iringnum, pringhandle_array, pringinfo ? pringinfo[0].stname.entype : (-1)); \ - return NSFW_MEM_ERR; \ - } \ - } - -#define NSFW_MEM_RINGV_CHECK_RET(pmpinfo, inum, pringhandle_array, iarray_num) { \ - if ((NULL == pmpinfo) || (NULL == pringhandle_array) \ - || (inum != iarray_num) || (inum <= 0) || (pmpinfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] pmpinfo=%p, inum=%d, pringhandle_array=%p, iarray_num=%d", \ - pmpinfo, inum, pringhandle_array, iarray_num, pmpinfo ? pmpinfo[0].stname.entype : (-1)); \ - return NSFW_MEM_ERR; \ - } \ - } - -#define NSFW_MEM_MBUF_CHECK_RET_ERR(mhandle, entype, desc) {\ - if ((NULL == mhandle) || (entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s, mhandle=%p, mtype=%d", desc, mhandle, entype); \ - return NSFW_MEM_ERR; \ - } \ - } - -#define NSFW_MEM_MBUF_CHECK_RET_NULL(mhandle, entype, desc) {\ - if ((NULL == mhandle) || (entype >= NSFW_MEM_TYPEMAX)) \ - { \ - NSCOMM_LOGERR("input para error] desc=%s, mhandle=%p, mtype=%d", desc, mhandle, entype); \ - return NULL; \ - } \ - } - -/*memory access inferface define*/ -typedef struct -{ - i32 (*mem_ops_init) (nsfw_mem_para * para); - void (*mem_ops_destroy) (void); - mzone_handle (*mem_ops_zone_create) (nsfw_mem_zone * pinfo); - i32 (*mem_ops_zone_createv) (nsfw_mem_zone * pmeminfo, i32 inum, - mzone_handle * paddr_array, i32 iarray_num); - mzone_handle (*mem_ops_zone_lookup) (nsfw_mem_name * pname); - i32 (*mem_ops_mzone_release) (nsfw_mem_name * pname); - mpool_handle (*mem_ops_mbfmp_create) (nsfw_mem_mbfpool * pbufinfo); - i32 (*mem_ops_mbfmp_createv) (nsfw_mem_mbfpool * pmbfname, i32 inum, - mpool_handle * phandle_array, - i32 iarray_num); - mbuf_handle (*mem_ops_mbf_alloc) (mpool_handle mhandle); - i32 (*mem_ops_mbf_free) (mbuf_handle mhandle); - mpool_handle (*mem_ops_mbfmp_lookup) (nsfw_mem_name * pmbfname); - i32 (*mem_ops_mbfmp_release) (nsfw_mem_name * pname); - mring_handle (*mem_ops_sp_create) (nsfw_mem_sppool * pmpinfo); - i32 (*mem_ops_sp_createv) (nsfw_mem_sppool * pmpinfo, i32 inum, - mring_handle * pringhandle_array, - i32 iarray_num); - i32 (*mem_ops_spring_create) (nsfw_mem_mring * prpoolinfo, - mring_handle * pringhandle_array, - i32 iringnum); - i32 (*mem_ops_sp_release) (nsfw_mem_name * pname); - mring_handle (*mem_ops_sp_lookup) (nsfw_mem_name * pname); - mring_handle (*mem_ops_ring_create) (nsfw_mem_mring * pringinfo); - mring_handle (*mem_ops_ring_lookup) (nsfw_mem_name * pname); - i32 (*mem_ops_ring_release) (nsfw_mem_name * pname); - ssize_t (*mem_ops_mem_statics) (void *handle, nsfw_mem_struct_type type); - i32 (*mem_ops_mbuf_recycle) (mpool_handle handle); - i32 (*mem_ops_sp_iterator) (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); - i32 (*mem_ops_mbuf_iterator) (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); -} nsfw_mem_ops; - -typedef struct -{ - nsfw_mem_type entype; - nsfw_mem_ops *stmemop; -} nsfw_mem_attr; - -typedef struct -{ - fw_poc_type enflag; /*app, nStackMain, Master */ -} nsfw_mem_localdata; - -extern nsfw_mem_attr g_nsfw_mem_ops[]; -extern i32 g_mem_type_num; -#endif diff --git a/src/framework/common/mem_mgr/include/nsfw_ring_data.h b/src/framework/common/mem_mgr/include/nsfw_ring_data.h deleted file mode 100644 index e6007ab..0000000 --- a/src/framework/common/mem_mgr/include/nsfw_ring_data.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* -* 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 _NSFW_RING_DATA_H_ -#define _NSFW_RING_DATA_H_ - -#include <stdint.h> -#include "types.h" -#include "common_mem_api.h" - -#define VALUE_LEN 40 - -/* -Ring Data has two part; Ver&Data -val is a pointer offset base on rte_perf_ring::Addrbase, this struct support 1TB, it's enough now; -future __int128 maybe used, this type can perfectly solve the version & address rang problem. -*/ -union RingData_U -{ - struct RingData_S - { - /* - value of data, indeed it's a pointer offset base on rte_perf_ring::Addrbase;40bit is enough for user space addr - ver must using 24bit, so val using 40bit; a CAS now just support 64bit; in future, we may using __int128,now __int128 not support well. - */ - volatile unsigned long long val:VALUE_LEN; - /* - version of data, using 16b store version flg is more suitable for Address save, but using 16b version is too short, it's value range is [0-65535]; - between two cpu schedule time (TM-SPACE) of one process/thread, other processes/threads do N times queue oper. if N > 65535, still have a chance of ABA. - if using a 24bit save version flg, if ABA happened, 16777216 times queue oper need done in one TM-SPACE, it's impossible for today cpu. - */ - volatile unsigned long long ver:(64 - VALUE_LEN); - } data_s; - u64 data_l; -}; - -/* - this high perf Ring rely on the init value of Ring Slot; - Ring Must init using PerfRingInit, Pool Must init using PerfPoolInit - - the addrbase is base addr for all element; now we support 1024G offset; - for nstack the Ring element is from hugepage, and the addr is in stack space. - - 1. not support a ring who's element space range bigger than 1024GB - [if one element from heep, one from stack, range will bigger than 1024GB, we not support] - 2. one more thing addr from mmap is in stack - 3. rte_perf_ring must create by rte_perf_ring_create/rte_perf_pool_create -*/ -struct nsfw_mem_ring -{ - u8 memtype; //shared, no shared - u8 ringflag; //scmp, scsp, mcsp,mcmp - u16 reserv; //reserv data - u32 size; //size of the Ring, must 2^n - u32 eltsize; //for s-pool, it is the size of per buf, if is ring, eltsize is zero. - u32 mask; //mask of the Ring, used mask mod Head/Tail to get real pos, must 2^n-1 - void *Addrbase; /*Cause the Addr we support just 40b(1024G), we using a basAddr+offset to get the real addr; ring[x].data_s.val just store offset; - * not used when no shared mode - */ - volatile u32_t prodhflag; //for nshmem fork recover - volatile u32_t prodtflag; //for nshmem fork recover - volatile u32_t conshflag; //for nshmem fork recover - volatile u32_t constflag; //for nshmem fork recover - nsfw_res res_chk; - - struct - { - volatile u32 head; //Head of the Ring, used to indicate pos where to pull a val - volatile u32 tail; //for nshmem, shmem not used. - } prod; - struct - { - volatile u32 head; //for nshmem, shmem not used. - volatile u32 tail; //Tail of the Ring, used to indicate pos where to push a val - } cons; - u32 uireserv[4]; //reserved for update - union RingData_U ring[0]; //Value of Ring -}; - -#define PERFRING_ADDR_RANGE (0xFFFFFFFFFFL) - -#endif /*_NSFW_RING_DATA_H_*/ diff --git a/src/framework/common/mem_mgr/include/nsfw_ring_fun.h b/src/framework/common/mem_mgr/include/nsfw_ring_fun.h deleted file mode 100644 index d74cc4b..0000000 --- a/src/framework/common/mem_mgr/include/nsfw_ring_fun.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -* -* 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 _NSFW_RING_FUN_H_ -#define _NSFW_RING_FUN_H_ - -#include <stdint.h> -#include "common_pal_bitwide_adjust.h" -#include "nsfw_mem_api.h" -#include "nsfw_ring_data.h" - -/* - for nstack I advise addrbase set to lowest of mmaped hugepage Addr. - to simple: - 1. ring element is from mmaped mem, set Addrbase to 0x7fffffffffff - 0xffffffffff is OK; - 1. ring element is from heap, set Addrbase to NULL is ok; -*/ -static inline void -nsfw_mem_ring_init (struct nsfw_mem_ring *ring, unsigned int size, - void *addrbase, unsigned char memtype, unsigned char flag) -{ - unsigned int loop = 0; - - if (!ring) - { - return; - } - - ring->prod.head = 0; - ring->prod.tail = 0; - ring->cons.head = 0; - ring->cons.tail = 0; - ring->size = size; - ring->eltsize = 0; - ring->mask = size - 1; - ring->memtype = memtype; - ring->ringflag = flag; - ring->prodtflag = ring->prodhflag = get_sys_pid (); - ring->conshflag = ring->constflag = get_sys_pid (); - /*if shmem, addrbase already changed to primary memory address */ - ring->Addrbase = addrbase; - ring->uireserv[0] = 0; - ring->uireserv[1] = 0; - ring->uireserv[2] = 0; - ring->uireserv[3] = 0; - - /*init Ring */ - for (loop = 0; loop < size; loop++) - { - /* - for a empty ring, version is the mapping head val - size - so the empty ring's ver is loop-size; - */ - ring->ring[loop].data_s.ver = (loop - size); - ring->ring[loop].data_s.val = 0; - } -} - -/* -another way to init Pool while no continuous space -1. init a empty rte_perf_ring -2. add element to PerRing. -*/ -static inline void -nsfw_mem_pool_head_init (struct nsfw_mem_ring *ring, unsigned int size, - unsigned int eltsize, void *addrbase, - nsfw_mem_type memtype, nsfw_mpool_type flag) -{ - ring->prod.head = size; - ring->prod.tail = size; - ring->cons.head = 0; - ring->cons.tail = 0; - ring->size = size; - ring->eltsize = eltsize; - ring->mask = size - 1; - ring->memtype = memtype; - ring->ringflag = flag; - ring->prodtflag = ring->prodhflag = get_sys_pid (); - ring->conshflag = ring->constflag = get_sys_pid (); - /*if shmem, addrbase already changed to primary memory address */ - ring->Addrbase = addrbase; - ring->uireserv[0] = 0; - ring->uireserv[1] = 0; - ring->uireserv[2] = 0; - ring->uireserv[3] = 0; - return; -} - -#define NSFW_RING_FLAG_CHECK_RET(handle, desc) {\ - if (((struct nsfw_mem_ring*)mhandle)->ringflag >= NSFW_MPOOL_TYPEMAX) \ - { \ - NSCOMM_LOGERR("invalid ring] desc=%s, ringflag=%d", desc, ((struct nsfw_mem_ring*)mhandle)->ringflag); \ - return 0; \ - } \ - } - -#endif /*_NSFW_RING_FUN_H_*/ diff --git a/src/framework/common/mem_mgr/nsfw_mem_api.c b/src/framework/common/mem_mgr/nsfw_mem_api.c deleted file mode 100644 index c89ada1..0000000 --- a/src/framework/common/mem_mgr/nsfw_mem_api.c +++ /dev/null @@ -1,879 +0,0 @@ -/* -* -* 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 <sys/types.h> -#include <unistd.h> -#include "nsfw_mem_desc.h" -#include "nstack_securec.h" - -#ifdef SYS_MEM_RES_STAT -#include "common_mem_ring.h" -#include "common_mem_mempool.h" -#endif - -#define MEM_OP_CALL_OK_RET(mtype, fun, para) { \ - if (g_nsfw_mem_ops[mtype].stmemop->fun) \ - { \ - return g_nsfw_mem_ops[mtype].stmemop->fun para; \ - } \ - } - -/***************************************************************************** -* Prototype : nsfw_mem_init -* Description : memory mgr module init -* Input : point to nstack_fwmem_para -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_init (void *para) -{ - nsfw_mem_para *ptempara = NULL; - i32 iret = NSFW_MEM_OK; - i32 icount = 0; - i32 iindex = 0; - - if (NULL == para) - { - NSCOMM_LOGERR ("ns mem init input error"); - return NSFW_MEM_ERR; - } - - ptempara = (nsfw_mem_para *) para; - - if (ptempara->enflag >= NSFW_PROC_MAX) - { - NSCOMM_LOGERR ("ns mem init input enflag invalid] enflag=%d", - ptempara->enflag); - return NSFW_MEM_ERR; - } - - NSCOMM_LOGINF ("ns mem init begin] enflag=%d, iargsnum=%d", - ptempara->enflag, ptempara->iargsnum); - - for (iindex = 0; iindex < ptempara->iargsnum; iindex++) - { - NSCOMM_LOGINF ("%s", ptempara->pargs[iindex]); - } - - for (icount = 0; icount < g_mem_type_num; icount++) - { - if ((NULL != g_nsfw_mem_ops[icount].stmemop) - && (NULL != g_nsfw_mem_ops[icount].stmemop->mem_ops_init)) - { - iret = g_nsfw_mem_ops[icount].stmemop->mem_ops_init (ptempara); - - if (NSFW_MEM_OK != iret) - { - NSCOMM_LOGERR ("mem init failed]index=%d, memtype=%d", icount, - g_nsfw_mem_ops[icount].entype); - break; - } - } - } - - /*if some module init fail, destory the modules that success */ - if (icount < g_mem_type_num) - { - for (iindex = 0; iindex < icount; iindex++) - { - if (g_nsfw_mem_ops[icount].stmemop->mem_ops_destroy) - { - g_nsfw_mem_ops[icount].stmemop->mem_ops_destroy (); - } - } - - return NSFW_MEM_ERR; - } - - NSCOMM_LOGINF ("ns mem init end"); - return NSFW_MEM_OK; -} - -/***************************************************************************** -* Prototype : nsfw_mem_zone_create -* Description : create a block memory with name -* nsfw_mem_zone::stname -* nsfw_mem_zone::isize -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_zone* pinfo -* Output : None -* Return Value : mzone_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mzone_handle -nsfw_mem_zone_create (nsfw_mem_zone * pinfo) -{ - - if ((NULL == pinfo) || (pinfo->stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR ("zone create input para error] pinfo=%p, mtype=%d", - pinfo, pinfo ? pinfo->stname.entype : (-1)); - return NULL; - } - - MEM_OP_CALL_OK_RET (pinfo->stname.entype, mem_ops_zone_create, (pinfo)); - NSCOMM_LOGINF ("mem create fail] memtype=%d, name=%s, size=%zu", - pinfo->stname.entype, pinfo->stname.aname, pinfo->length); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_zone_createv -* Description : create some memory blocks -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_zone* pmeminfo -* i32 inum -* mzone_handle* paddr_array -* i32 iarray_num -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_zone_createv (nsfw_mem_zone * pmeminfo, i32 inum, - mzone_handle * paddr_array, i32 iarray_num) -{ - if ((NULL == pmeminfo) || (NULL == paddr_array) - || (inum != iarray_num) || (inum <= 0) - || (pmeminfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR - ("input para error] pmeminfo=%p, inum=%d, paddr_array=%p, iarray_num=%d, mtype=%d", - pmeminfo, inum, paddr_array, iarray_num, - pmeminfo ? pmeminfo[0].stname.entype : (-1)); - return NSFW_MEM_ERR; - } - - MEM_OP_CALL_OK_RET (pmeminfo[0].stname.entype, mem_ops_zone_createv, - (pmeminfo, inum, paddr_array, iarray_num)); - NSCOMM_LOGINF ("mem create fail] memtype=%d", pmeminfo[0].stname.entype); - return NSFW_MEM_ERR; -} - -/***************************************************************************** -* Prototype : nsfw_mem_zone_lookup -* Description : look up a memory -* 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* 2. if the memory is shared, pname->enowner indicate that who create this memory. -* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, -* end with none created by nStackMaster, and end with _<pid> created by other. -* 2. pname->enowner is available only when call look up shared memory. -* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, -* the name must be full name. -* for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, -* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add -* _(pid) at the end of name, nstack_123. -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : mzone_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mzone_handle -nsfw_mem_zone_lookup (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_NULL (pname, "mem zone look up"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_zone_lookup, (pname)); - NSCOMM_LOGERR ("mem lookup fail] memtype=%d, name=%s ", pname->entype, - pname->aname); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_zone_release -* Description : release a memory -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_zone_release (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_ERR (pname, "mem zone release"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_mzone_release, (pname)); - NSCOMM_LOGERR ("mem release fail] memtype=%d, name=%s", pname->entype, - pname->aname); - return NSFW_MEM_ERR; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbfmp_create -* Description : create a mbuf pool -* Input : nsfw_mem_mbfpool* pbufinfo -* Output : None -* Return Value : mpool_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mpool_handle -nsfw_mem_mbfmp_create (nsfw_mem_mbfpool * pbufinfo) -{ - if ((NULL == pbufinfo) || (pbufinfo->stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR ("input para error] pbufinfo=%p, mtype=%d", pbufinfo, - pbufinfo ? pbufinfo->stname.entype : (-1)); - return NULL; - } - - MEM_OP_CALL_OK_RET (pbufinfo->stname.entype, mem_ops_mbfmp_create, - (pbufinfo)); - NSCOMM_LOGERR ("mbufmp create fail] memtype=%d, name=%s ", - pbufinfo->stname.entype, pbufinfo->stname.aname); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbfmp_createv -* Description : create some mbuf pools -* 1. the name of length must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_mbfpool* pmbfname -* i32 inum -* mpool_handle* phandle_array -* i32 iarray_num -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_mbfmp_createv (nsfw_mem_mbfpool * pmbfname, i32 inum, - mpool_handle * phandle_array, i32 iarray_num) -{ - if ((NULL == pmbfname) || (NULL == phandle_array) - || (inum != iarray_num) || (inum <= 0) - || (pmbfname[0].stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR - ("input para error] pmbfname=%p, inum=%d, phandle_array=%p, iarray_num=%d", - pmbfname, inum, phandle_array, iarray_num, - pmbfname ? pmbfname[0].stname.entype : (-1)); - return NSFW_MEM_ERR; - } - - MEM_OP_CALL_OK_RET (pmbfname[0].stname.entype, mem_ops_mbfmp_createv, - (pmbfname, inum, phandle_array, iarray_num)); - NSCOMM_LOGERR ("mbufmp createv fail] memtype=%d", - pmbfname[0].stname.entype); - return NSFW_MEM_ERR; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbf_alloc -* Description : alloc a mbuf from mbuf pool -* Input : mpool_handle mhandle -* nsfw_mem_type entype -* Output : None -* Return Value : mbuf_handle -* Calls : -* Called By : -*****************************************************************************/ -mbuf_handle -nsfw_mem_mbf_alloc (mpool_handle mhandle, nsfw_mem_type entype) -{ - NSFW_MEM_MBUF_CHECK_RET_NULL (mhandle, entype, "mbf alloc"); - MEM_OP_CALL_OK_RET (entype, mem_ops_mbf_alloc, (mhandle)); - NSCOMM_LOGERR ("mbf alloc fail] handle=%p, type=%d", mhandle, entype); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbf_free -* Description : put a mbuf backintp mbuf pool -* Input : mbuf_handle mhandle -* nsfw_mem_type entype -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_mbf_free (mbuf_handle mhandle, nsfw_mem_type entype) -{ - NSFW_MEM_MBUF_CHECK_RET_ERR (mhandle, entype, "mbuf free"); - MEM_OP_CALL_OK_RET (entype, mem_ops_mbf_free, (mhandle)); - NSCOMM_LOGERR ("mbf free fail] handle=%p, type=%d", mhandle, entype); - return NSFW_MEM_ERR; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbfmp_lookup -* Description : look up mbuf mpool -* 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* 2. if the memory is shared, pname->enowner indicate that who create this memory. -* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, -* end with none created by nStackMaster, and end with _<pid> created by other. -* 2. pname->enowner is available only when call look up shared memory. -* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, -* the name must be full name. -* for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, -* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add -* _(pid) at the end of name, nstack_123. -* Input : nsfw_mem_name* pmbfname -* Output : None -* Return Value : mpool_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mpool_handle -nsfw_mem_mbfmp_lookup (nsfw_mem_name * pmbfname) -{ - NSFW_MEM_NAME_CHECK_RET_NULL (pmbfname, "mbuf pool look up"); - MEM_OP_CALL_OK_RET (pmbfname->entype, mem_ops_mbfmp_lookup, (pmbfname)); - NSCOMM_LOGERR ("mbufmp lookup fail] memtype=%d, name=%s ", pmbfname->entype, - pmbfname->aname); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbfmp_release -* Description : release mbuf pool -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_mbfmp_release (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_ERR (pname, "mbuf mp release"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_mbfmp_release, (pname)); - NSCOMM_LOGERR ("mbfmp release fail] memtype=%d, name=%s", pname->entype, - pname->aname); - return NSFW_MEM_ERR; -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_create -* Description : create a simple pool -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_sppool* pmpinfo -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mring_handle -nsfw_mem_sp_create (nsfw_mem_sppool * pmpinfo) -{ - if ((NULL == pmpinfo) || (pmpinfo->stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR ("input para error] pmpinfo=%p, mtype=%d", pmpinfo, - pmpinfo ? pmpinfo->stname.entype : (-1)); - return NULL; - } - - MEM_OP_CALL_OK_RET (pmpinfo->stname.entype, mem_ops_sp_create, (pmpinfo)); - NSCOMM_LOGERR ("sp create fail] memtype=%d, name=%s ", - pmpinfo->stname.entype, pmpinfo->stname.aname); - return NULL; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_createv -* Description : create some simple pools one time -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_sppool* pmpinfo -* i32 inum -* mring_handle* pringhandle_array -* i32 iarray_num -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_sp_createv (nsfw_mem_sppool * pmpinfo, i32 inum, - mring_handle * pringhandle_array, i32 iarray_num) -{ - NSFW_MEM_RINGV_CHECK_RET (pmpinfo, inum, pringhandle_array, iarray_num); - MEM_OP_CALL_OK_RET (pmpinfo[0].stname.entype, mem_ops_sp_createv, - (pmpinfo, inum, pringhandle_array, iarray_num)); - NSCOMM_LOGERR ("sp createv fail] memtype=%d", pmpinfo[0].stname.entype); - return NSFW_MEM_ERR; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_ring_create -* Description : create a simple pool with many rings -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_mring* pringinfo -* mring_handle* pringhandle_array -* i32 iringnum -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_sp_ring_create (nsfw_mem_mring * pringinfo, - mring_handle * pringhandle_array, i32 iringnum) -{ - NSFW_MEM_RING_CHECK_RET (pringinfo, pringhandle_array, iringnum); - MEM_OP_CALL_OK_RET (pringinfo[0].stname.entype, mem_ops_spring_create, - (pringinfo, pringhandle_array, iringnum)); - NSCOMM_LOGERR ("mppool spring creat fail] memtype=%d", - pringinfo[0].stname.entype); - return NSFW_MEM_ERR; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_release -* Description : release a simple mempool -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_mem_sp_release (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_ERR (pname, "sp release"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_sp_release, (pname)); - NSCOMM_LOGERR ("sp release fail] memtype=%d, name=%s ", pname->entype, - pname->aname); - return NSFW_MEM_ERR; -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_lookup -* Description : look up a simpile ring -* 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* 2. if the memory is shared, pname->enowner indicate that who create this memory. -* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, -* end with none created by nStackMaster, and end with _<pid> created by other. -* 2. pname->enowner is available only when call look up shared memory. -* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, -* the name must be full name. -* for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, -* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add -* _(pid) at the end of name, nstack_123. -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mring_handle -nsfw_mem_sp_lookup (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_NULL (pname, "sp look up"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_sp_lookup, (pname)); - NSCOMM_LOGERR ("sp lookup fail] memtype=%d, name=%s", pname->entype, - pname->aname); - return NULL; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_create -* Description : create a ring -* note : 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* 2. shared memory ring (NSFW_SHMEM) just can put a pointer into the queue, the queue also point to a shared block memory. -* no shared memory ring(NSFW_NSHMEM) is other wise. -* Input : nsfw_mem_mring* pringinfo -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mring_handle -nsfw_mem_ring_create (nsfw_mem_mring * pringinfo) -{ - if ((NULL == pringinfo) || (pringinfo->stname.entype >= NSFW_MEM_TYPEMAX)) - { - NSCOMM_LOGERR ("input para error] pmpinfo=%p, mtype=%d", pringinfo, - pringinfo ? pringinfo->stname.entype : (-1)); - return NULL; - } - - MEM_OP_CALL_OK_RET (pringinfo->stname.entype, mem_ops_ring_create, - (pringinfo)); - NSCOMM_LOGERR ("ring create fail] memtype=%d, name=%s ", - pringinfo->stname.entype, pringinfo->stname.aname); - return NULL; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_lookup -* Description : look up a ring by name -* 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. -* 2. if the memory is shared, pname->enowner indicate that who create this memory. -* note: -* 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, -* end with none created by nStackMaster, and end with _<pid> created by other. -* 2. pname->enowner is available only when call look up shared memory. -* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, -* the name must be full name. -* for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, -* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add -* _(pid) at the end of name, nstack_123. -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -* -* -*****************************************************************************/ -mring_handle -nsfw_mem_ring_lookup (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_NULL (pname, "ring lookup"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_ring_lookup, (pname)); - NSCOMM_LOGERR ("ring lookup fail] memtype=%d, name=%s", pname->entype, - pname->aname); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_reset -* Description : reset the number of producer and consumer, also, the -* state of ring reset to empty -* notes : must be called before doing any operations base on the ring -* Input : mring_handle mhandle -* nsfw_mpool_type entype -* Output : None -* Return Value : void -* Calls : -* Called By : -* -*****************************************************************************/ -void -nsfw_mem_ring_reset (mring_handle mhandle, nsfw_mpool_type entype) -{ - u32 loop = 0; - struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) mhandle; - - if (!ring) - { - return; - } - - ring->prod.head = 0; - ring->cons.tail = 0; - ring->ringflag = (u8) entype; - - /*init Ring */ - for (loop = 0; loop < ring->size; loop++) - { - /* - for a empty ring, version is the mapping head val - size - so the empty ring's ver is loop-size; - */ - ring->ring[loop].data_s.ver = (loop - ring->size); - ring->ring[loop].data_s.val = 0; - } - - return; -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_free_count -* Description : get the free number of ring -* Input : mring_handle mhandle -* Output : None -* Return Value : u32 -* Calls : -* Called By : -* -*****************************************************************************/ -u32 -nsfw_mem_ring_free_count (mring_handle mhandle) -{ - struct nsfw_mem_ring *temp = NULL; - u32 thead = 0; - u32 ttail = 0; - if (NULL == mhandle) - { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return 0; - } - - temp = (struct nsfw_mem_ring *) mhandle; - thead = temp->prod.head; - ttail = temp->cons.tail; - return ttail + temp->size - thead; -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_using_count -* Description : get the in using number of ring -* Input : mring_handle mhandle -* Output : None -* Return Value : u32 -* Calls : -* Called By : -* -*****************************************************************************/ -u32 -nsfw_mem_ring_using_count (mring_handle mhandle) -{ - struct nsfw_mem_ring *temp = NULL; - u32 thead = 0; - u32 ttail = 0; - if (NULL == mhandle) - { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return 0; - } - - temp = (struct nsfw_mem_ring *) mhandle; - thead = temp->prod.head; - ttail = temp->cons.tail; - return thead - ttail; -} - -/***************************************************************************** -* Prototype : nsfw_mem_ring_size -* Description : get size of ring -* Input : mring_handle mhandle -* Output : None -* Return Value : u32 -* Calls : -* Called By : -*****************************************************************************/ -u32 -nsfw_mem_ring_size (mring_handle mhandle) -{ - struct nsfw_mem_ring *temp = NULL; - - if (NULL == mhandle) - { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return 0; - } - - temp = (struct nsfw_mem_ring *) mhandle; - - return temp->size; -} - -#ifdef SYS_MEM_RES_STAT -/***************************************************************************** -* Prototype : nsfw_mem_mbfpool_free_count -* Description : get the free mbuf count of a mbuf pool -* Input : mpool_handle mhandle -* Output : None -* Return Value : u32 -* Calls : -* Called By : -* -*****************************************************************************/ -u32 -nsfw_mem_mbfpool_free_count (mpool_handle mhandle) -{ - if (!mhandle) - { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return 0; - } - struct common_mem_mempool *mp = (struct common_mem_mempool *) mhandle; - struct common_mem_ring *mp_ring = - (struct common_mem_ring *) (mp->ring_align); - if (!mp_ring) - { - NSCOMM_LOGERR ("ring is null"); - return 0; - } - u32 p_head = mp_ring->prod.head; - u32 c_tail = mp_ring->cons.tail; - - return p_head - c_tail; -} -#endif /* SYS_MEM_RES_STAT */ - -/***************************************************************************** -* Prototype : nsfw_mem_ring_release -* Description : release a ring memory -* notes : the length of name must be less than NSFW_MEM_APPNAME_LENGTH -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_mem_ring_release (nsfw_mem_name * pname) -{ - NSFW_MEM_NAME_CHECK_RET_ERR (pname, "ring release"); - MEM_OP_CALL_OK_RET (pname->entype, mem_ops_ring_release, (pname)); - NSCOMM_LOGERR ("ring release fail] name=%s, type=%d", pname->aname, - pname->entype); - return NSFW_MEM_ERR; - -} - -/***************************************************************************** -* Prototype : nsfw_mem_get_len -* Description : statics mbufpool, sppool, ring mem size. -* return: <=0, err happen, >0 mem size -* NSFW_MEM_MZONE: not surport because you already know the length when create -* Input : void * handle -* nsfw_mem_struct_type type -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -*****************************************************************************/ -ssize_t -nsfw_mem_get_len (void *handle, nsfw_mem_struct_type type) -{ - if (NULL == handle) - { - NSCOMM_LOGERR ("input para error] handle=%p", handle); - return -1; - } - if ((NSFW_MEM_SPOOL == type) || (NSFW_MEM_RING == type)) - { - struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) handle; - if (ring->memtype >= NSFW_MEM_TYPEMAX) - { - NSCOMM_LOGERR ("invalid ring] ring type=%u ,handle=%p", - ring->memtype, handle); - return -1; - } - MEM_OP_CALL_OK_RET (ring->memtype, mem_ops_mem_statics, (handle, type)); - } - else - { - MEM_OP_CALL_OK_RET (NSFW_SHMEM, mem_ops_mem_statics, (handle, type)); - } - return -1; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbuf_pool_recycle -* Description : recycle mbuf -* Input : mpool_handle handle -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_mem_mbuf_pool_recycle (mpool_handle handle) -{ - MEM_OP_CALL_OK_RET (NSFW_SHMEM, mem_ops_mbuf_recycle, (handle)); - return -1; -} - -/***************************************************************************** -* Prototype : nsfw_mem_sp_iterator -* Description : spool iterator -* Input : mpool_handle handle -* u32 start -* u32 end -* nsfw_mem_item_fun fun -* void *argv -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_sp_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv) -{ - MEM_OP_CALL_OK_RET (NSFW_SHMEM, mem_ops_sp_iterator, - (handle, start, end, fun, argv)); - return -1; -} - -/***************************************************************************** -* Prototype : nsfw_mem_mbuf_iterator -* Description : mbuf iterator -* Input : mpool_handle handle -* u32 start -* u32 end -* nsfw_mem_item_fun fun -* void *argv -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_mem_mbuf_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv) -{ - MEM_OP_CALL_OK_RET (NSFW_SHMEM, mem_ops_mbuf_iterator, - (handle, start, end, fun, argv)); - return -1; -} - -/***************************************************************************** -* Prototype : nsfw_mem_dfx_ring_print -* Description : print ring info -* Input : mring_handle mhandle -* Output : None -* Return Value : if no err happen, return the length of string print, 0 or -1 maybe err happen -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_mem_dfx_ring_print (mring_handle mhandle, char *pbuf, int length) -{ - struct nsfw_mem_ring *temp = (struct nsfw_mem_ring *) mhandle; - u32 head = 0; - u32 tail = 0; - int ret = 0; - if ((!temp) || (!pbuf) || (length <= 0)) - { - return 0; - } - head = temp->prod.head; - tail = temp->cons.tail; - ret = - SPRINTF_S (pbuf, length, - "[.Head=%u,\n .Tail=%u,\n .(|Tail-Head|)=%u,\n .size=%u,\n .mask=%u]\n", - head, tail, (tail >= head) ? (tail - head) : (head - tail), - temp->size, temp->mask); - return ret; -} diff --git a/src/framework/common/mem_mgr/nsfw_mem_construct.c b/src/framework/common/mem_mgr/nsfw_mem_construct.c deleted file mode 100644 index ed6fe27..0000000 --- a/src/framework/common/mem_mgr/nsfw_mem_construct.c +++ /dev/null @@ -1,21 +0,0 @@ -/* -* -* 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_init.h" -#include "nsfw_mem_api.h" - -NSFW_MODULE_NAME (NSFW_MEM_MGR_MODULE) -NSFW_MODULE_PRIORITY (10) NSFW_MODULE_INIT (nsfw_mem_init) diff --git a/src/framework/common/mem_mgr/nsfw_mem_desc.c b/src/framework/common/mem_mgr/nsfw_mem_desc.c deleted file mode 100644 index d0fbfd3..0000000 --- a/src/framework/common/mem_mgr/nsfw_mem_desc.c +++ /dev/null @@ -1,92 +0,0 @@ -/* -* -* 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 <sys/types.h> -#include <unistd.h> -#include "nsfw_mem_desc.h" -#include "nsfw_shmem_mdesc.h" -#include "nsfw_nshmem_mdesc.h" -#include "nsfw_shmem_ring.h" -#include "nsfw_nshmem_ring.h" - -/* *INDENT-OFF* */ -/*the order you add must be NSFW_SHMEM, NSFW_NSHMEM*/ -nsfw_mem_attr g_nsfw_mem_ops[] = -{ - {NSFW_SHMEM, &g_shmem_ops}, - {NSFW_NSHMEM, &g_nshmem_ops}, -}; - -i32 g_mem_type_num = sizeof(g_nsfw_mem_ops) / sizeof(nsfw_mem_attr); - - -nsfw_ring_ops g_ring_ops_arry[NSFW_MEM_TYPEMAX][NSFW_MPOOL_TYPEMAX] = { - { - { - (nsfw_mem_ring_enqueue_fun)nsfw_shmem_ring_sp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_shmem_ring_sc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_shmem_ring_sc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_shmem_ring_mp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_shmem_ring_sc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_shmem_ring_sc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_shmem_ring_sp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_shmem_ring_mc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_shmem_ring_mc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_shmem_ring_mp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_shmem_ring_mc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_shmem_ring_mc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_shmem_ring_singlethread_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_shmem_ring_singlethread_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_shmem_ring_singlethread_dequeuev - } - }, - { - { - (nsfw_mem_ring_enqueue_fun)nsfw_nshmem_ring_sp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_nshmem_ring_sc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_nshmem_ring_sc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_nshmem_ring_mp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_nshmem_ring_sc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_nshmem_ring_sc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_nshmem_ring_sp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_nshmem_ring_mc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_nshmem_ring_mc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_nshmem_ring_mp_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_nshmem_ring_mc_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_nshmem_ring_mc_dequeuev - }, - { - (nsfw_mem_ring_enqueue_fun)nsfw_nshmem_ring_singlethread_enqueue, \ - (nsfw_mem_ring_dequeue_fun)nsfw_nshmem_ring_singlethread_dequeue, \ - (nsfw_mem_ring_dequeuev_fun)nsfw_nshmem_ring_singlethread_dequeuev - } - } -}; -/* *INDENT-ON* */ diff --git a/src/framework/common/mem_mgr/nsfw_mem_stat.c b/src/framework/common/mem_mgr/nsfw_mem_stat.c deleted file mode 100644 index f7a1f41..0000000 --- a/src/framework/common/mem_mgr/nsfw_mem_stat.c +++ /dev/null @@ -1,292 +0,0 @@ -/* -* -* 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" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C"{ -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -#define NSFW_MEM_STAT_NUM 512 - -#define NSFW_MEM_STAT_MODULE "nsfw_mem_stat_module" - -typedef struct _nsfw_mem_stat -{ - u8 mem_type; - u8 alloc_flag; - char module[NSFW_MEM_MODULE_LEN]; - char mem_name[NSFW_MEM_NAME_LEN]; - u32 mem_size; -} nsfw_mem_stat_t; - -nsfw_mem_stat_t g_mem_stat[NSFW_MEM_STAT_NUM]; - -#ifdef SYS_MEM_RES_STAT -#define MAX_STAT_ITEM_NUM 20 -typedef struct _mem_stat_item_t -{ - char name[32]; - u64 size; -} mem_stat_item_t; - -typedef struct _mem_stat_mgr_t -{ - u32 item_num; - mem_stat_item_t item[MAX_STAT_ITEM_NUM]; -} mem_stat_mgr; - -mem_stat_mgr g_max_mem_list; -#endif - -/***************************************************************************** -* Prototype : nsfw_mem_stat -* Description : add memory stat -* Input : char *module -* char *mem_name -* u8 mem_type -* u32 mem_size -* Output : None -* Return Value : void -* Calls : -* Called By : -* -*****************************************************************************/ -void -nsfw_mem_stat (char *module, char *mem_name, u8 mem_type, u32 mem_size) -{ - if (NULL == module || NULL == mem_name) - { - NSFW_LOGERR ("argv err]module=%p,mem_name=%p", module, mem_name); - return; - } - - int i; - nsfw_mem_stat_t *mem_stat_item = NULL; - for (i = 0; i < NSFW_MEM_STAT_NUM; i++) - { - if (FALSE == g_mem_stat[i].alloc_flag) - { - g_mem_stat[i].alloc_flag = TRUE; - mem_stat_item = &g_mem_stat[i]; - break; - } - } - - if (NULL == mem_stat_item) - { - NSFW_LOGERR ("mem stat full]module=%s,type=%u,name=%s,size=%u", - module, mem_type, mem_name, mem_size); - return; - } - - mem_stat_item->mem_type = mem_type; - mem_stat_item->mem_size = mem_size; - - if (EOK != STRCPY_S (mem_stat_item->module, NSFW_MEM_MODULE_LEN, module)) - { - NSFW_LOGERR ("STRNCPY_S failed"); - return; - } - if (EOK != STRCPY_S (mem_stat_item->mem_name, NSFW_MEM_NAME_LEN, mem_name)) - { - NSFW_LOGERR ("STRNCPY_S failed"); - return; - } - - return; -} - -/***************************************************************************** -* Prototype : nsfw_mem_stat_print -* Description : print all memory info -* Input : None -* Output : None -* Return Value : void -* Calls : -* Called By : -* -*****************************************************************************/ -void -nsfw_mem_stat_print () -{ - int i; - for (i = 0; i < NSFW_MEM_STAT_NUM; i++) - { - if (TRUE == g_mem_stat[i].alloc_flag) - { - NSFW_LOGINF ("mem_module=%s,name=%s,type=%u,size=%u", - g_mem_stat[i].module, g_mem_stat[i].mem_name, - g_mem_stat[i].mem_type, g_mem_stat[i].mem_size); - } - } - -} - -#ifdef SYS_MEM_RES_STAT -void -clear_mem_stat_item () -{ - if (EOK != MEMSET_S ((char *) &g_max_mem_list, sizeof (mem_stat_mgr), - 0, sizeof (mem_stat_mgr))) - { - NSFW_LOGERR ("MEMSET_S failed"); - } -} - -void -insert_mem_stat_item (char *name, u64 len) -{ - int j, temp; - - if (g_max_mem_list.item_num == 0) - { - if (EOK != - STRCPY_S (g_max_mem_list.item[0].name, - sizeof (g_max_mem_list.item[0].name), name)) - { - NSFW_LOGERR ("STRCPY_S failed"); - } - g_max_mem_list.item[0].size = len; - g_max_mem_list.item_num++; - return; - } - else if (g_max_mem_list.item_num < MAX_STAT_ITEM_NUM) - { - if (len <= g_max_mem_list.item[g_max_mem_list.item_num - 1].size) - { - if (EOK != - STRCPY_S (g_max_mem_list.item[g_max_mem_list.item_num].name, - sizeof (g_max_mem_list.item - [g_max_mem_list.item_num].name), name)) - { - NSFW_LOGERR ("STRCPY_S failed"); - } - g_max_mem_list.item[g_max_mem_list.item_num].size = len; - g_max_mem_list.item_num++; - return; - } - j = 0; - temp = g_max_mem_list.item_num; - while (j < temp) - { - if (len >= g_max_mem_list.item[j].size) - { - goto insert_it; - } - j++; - } - if (j == temp) - { - if (EOK != - STRCPY_S (g_max_mem_list.item[j].name, - sizeof (g_max_mem_list.item[j].name), name)) - { - NSFW_LOGERR ("STRCPY_S failed"); - } - g_max_mem_list.item[j].size = len; - g_max_mem_list.item_num++; - return; - } - } - else - { - j = 0; - temp = MAX_STAT_ITEM_NUM - 1; - while (j < MAX_STAT_ITEM_NUM) - { - if (len >= g_max_mem_list.item[j].size) - { - goto insert_it; - } - j++; - } - } - - return; - -insert_it: - while (temp - 1 >= j) - { - if (EOK != - STRCPY_S (g_max_mem_list.item[temp].name, - sizeof (g_max_mem_list.item[temp].name), - g_max_mem_list.item[temp - 1].name)) - { - NSFW_LOGERR ("STRCPY_S failed"); - } - g_max_mem_list.item[temp].size = g_max_mem_list.item[temp - 1].size; - temp--; - } - if (EOK != - STRCPY_S (g_max_mem_list.item[j].name, - sizeof (g_max_mem_list.item[j].name), name)) - { - NSFW_LOGERR ("STRCPY_S failed"); - } - g_max_mem_list.item[j].size = len; - g_max_mem_list.item_num++; - return; -} - -int -get_mem_stat_item (int idx, char **name, u64 * len) -{ - if (idx < 0 || idx >= MAX_STAT_ITEM_NUM) - { - return -1; - } - - *name = g_max_mem_list.item[idx].name; - *len = g_max_mem_list.item[idx].size; - - return 0; -} -#endif - -static int nsfw_mem_stat_init (void *param); -static int -nsfw_mem_stat_init (void *param) -{ - MEM_STAT (NSFW_MEM_STAT_MODULE, "g_mem_stat", NSFW_NSHMEM, - sizeof (g_mem_stat)); - nsfw_mem_stat_print (); -#ifdef SYS_MEM_RES_STAT - clear_mem_stat_item (); -#endif - return 0; -} - -/* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_MEM_STAT_MODULE) -NSFW_MODULE_PRIORITY (99) -NSFW_MODULE_INIT (nsfw_mem_stat_init) -/* *INDENT-ON* */ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.c b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.c deleted file mode 100644 index fdb2079..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.c +++ /dev/null @@ -1,47 +0,0 @@ -/* -* -* 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_mem_desc.h" -#include "nsfw_nshmem_mng.h" -#include "nsfw_nshmem_mdesc.h" - -/*no share memory access inferface*/ -nsfw_mem_ops g_nshmem_ops = { - nsfw_nshmem_init, - nsfw_nshmem_destory, - nsfw_nshmem_create, - NULL, - nsfw_nshmem_lookup, - nsfw_nshmem_release, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - nsfw_nshmem_spcreate, - NULL, - NULL, - nsfw_nshmem_sprelease, - nsfw_nshmem_sp_lookup, - nsfw_nshmem_ringcreate, - NULL, - nsfw_nshmem_ringrelease, - nsfw_nshmem_static, - NULL, - NULL, /*mem_ops_sp_iterator */ - NULL, /*mem_ops_mbuf_iterator */ -}; diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.h b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.h deleted file mode 100644 index 1b63520..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mdesc.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -* -* 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 _NSFW_NSHMEM_MDESC_H -#define _NSFW_NSHMEM_MDESC_H - -extern nsfw_mem_ops g_nshmem_ops; - -#endif diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.c b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.c deleted file mode 100644 index 49e3769..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.c +++ /dev/null @@ -1,544 +0,0 @@ -/* -* -* 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 "nstack_log.h" -#include "nstack_securec.h" -#include "nsfw_mem_desc.h" -#include "nsfw_ring_fun.h" -#include "nsfw_nshmem_ring.h" -#include "nsfw_nshmem_mng.h" - -#include "common_func.h" - -#define nsfw_get_glb_lock() (&g_nshmem_internal_cfg->mlock) - -#define NSFW_NSHMEM_INIT_CHK_RET_NULL() \ - if ((!g_nshmem_internal_cfg) || (!g_nshmem_localdata)) \ - { \ - NSCOMM_LOGDBG("Error] g_nshmem_internal_cfg=%p, g_nshmem_localdata=%p", g_nshmem_internal_cfg, g_nshmem_localdata); \ - return NULL; \ - } - -#define NSFW_NSHMEM_INIT_CHK_RET() \ - if ((!g_nshmem_internal_cfg) || (!g_nshmem_localdata)) \ - { \ - NSCOMM_LOGDBG("Error] g_nshmem_internal_cfg=%p, g_nshmem_localdata=%p", g_nshmem_internal_cfg, g_nshmem_localdata); \ - return NSFW_MEM_ERR; \ - } - -nsfw_mem_localdata *g_nshmem_localdata = NULL; -nsfw_nshmem_cfg *g_nshmem_internal_cfg = NULL; - -/*look up a mem zone*/ -NSTACK_STATIC inline nsfw_nshmem_mzone * -nsfw_nshmem_get_free_zone (void) -{ - int icnt = 0; - - /*g_nshmem_internal_cfg must not be null if come here */ - for (icnt = 0; icnt < COMMON_MEM_MAX_MEMZONE; icnt++) - { - if (g_nshmem_internal_cfg->amemzone[icnt].addr == NULL) - { - return &g_nshmem_internal_cfg->amemzone[icnt]; - } - } - - return NULL; -} - -NSTACK_STATIC inline void -nsfw_nshmem_free_zone (nsfw_nshmem_mzone * pzone) -{ - nsfw_nshmem_mzone *pzonebase = &g_nshmem_internal_cfg->amemzone[0]; - nsfw_nshmem_mzone *pzoneend = - &g_nshmem_internal_cfg->amemzone[NSFW_NSHMEM_ZONE_MAX - 1]; - - if ((((int) ((char *) pzone - (char *) pzonebase) < 0) - || ((int) ((char *) pzone - (char *) pzoneend) > 0)) - && ((unsigned int) ((char *) pzone - (char *) pzonebase) % - sizeof (nsfw_nshmem_mzone) != 0)) - { - NSCOMM_LOGERR ("nshmem free fail] mem=%p", pzone); - return; - } - if (pzone->addr) - { - free (pzone->addr); - } - pzone->addr = NULL; - - int ret = MEMSET_S ((void *) pzone, sizeof (nsfw_nshmem_mzone), 0, - sizeof (nsfw_nshmem_mzone)); - if (EOK != ret) - { - NSCOMM_LOGERR ("MEMSET_S failed] mem=%p, ret=%d", pzone, ret); - } - return; -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_init -* Description : nsh module init -* Input : nsfw_mem_para* para -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_nshmem_init (nsfw_mem_para * para) -{ - i32 iret = NSFW_MEM_OK; - NSCOMM_LOGINF ("nsfw nshmem init begin"); - g_nshmem_localdata = - (nsfw_mem_localdata *) malloc (sizeof (nsfw_mem_localdata)); - - if (NULL == g_nshmem_localdata) - { - NSCOMM_LOGERR ("nshmem init g_nshmem_localdata malloc fail"); - return NSFW_MEM_ERR; - } - - iret = - MEMSET_S (g_nshmem_localdata, sizeof (nsfw_mem_localdata), 0, - sizeof (nsfw_mem_localdata)); - - if (EOK != iret) - { - NSCOMM_LOGERR ("nshmem init g_nshmem_localdata MEMSET_S fail"); - goto ERROR; - } - - g_nshmem_internal_cfg = - (nsfw_nshmem_cfg *) malloc (sizeof (nsfw_nshmem_cfg)); - - if (NULL == g_nshmem_internal_cfg) - { - NSCOMM_LOGERR ("nshmem init g_nshmem_internal_cfg malloc fail"); - goto ERROR; - } - - iret = - MEMSET_S (g_nshmem_internal_cfg, sizeof (nsfw_nshmem_cfg), 0, - sizeof (nsfw_nshmem_cfg)); - - if (EOK != iret) - { - NSCOMM_LOGERR ("nshmem init g_nshmem_internal_cfg MEMSET_S fail"); - goto ERROR; - } - - g_nshmem_localdata->enflag = para->enflag; - NSCOMM_LOGINF ("nsfw nshmem init end"); - goto OK; - -ERROR: - iret = NSFW_MEM_ERR; - nsfw_nshmem_destory (); - return iret; -OK: - iret = NSFW_MEM_OK; - return iret; -} - -/* - * memory destory - */ -void -nsfw_nshmem_destory (void) -{ - if (g_nshmem_localdata) - { - free (g_nshmem_localdata); - g_nshmem_localdata = NULL; - } - - if (g_nshmem_internal_cfg) - { - free (g_nshmem_internal_cfg); - g_nshmem_internal_cfg = NULL; - } - - return; -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_reserv_safe -* Description : malloc a memory and save to memzone -* Input : const char* name -* size_t length -* Output : None -* Return Value : mzone_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mzone_handle -nsfw_nshmem_reserv_safe (const char *name, size_t length) -{ - void *addr = NULL; - i32 iret = NSFW_MEM_OK; - nsfw_nshmem_mzone *pmemzone = NULL; - - if (length <= 0) - { - return NULL; - } - - nsfw_write_lock (nsfw_get_glb_lock ()); - - addr = malloc (length); - if (!addr) - { - NSCOMM_LOGERR ("nshmem malloc addr fail] addr=%p", addr); - nsfw_write_unlock (nsfw_get_glb_lock ()); - return NULL; - } - - iret = MEMSET_S (addr, length, 0, length); - if (EOK != iret) - { - NSCOMM_LOGERR ("nshmem malloc addr MEMSET_S fail] addr=%p", addr); - free (addr); - nsfw_write_unlock (nsfw_get_glb_lock ()); - return NULL; - } - - pmemzone = nsfw_nshmem_get_free_zone (); - - if (!pmemzone) - { - NSCOMM_LOGERR ("nshmem get free zone fail"); - free (addr); - nsfw_write_unlock (nsfw_get_glb_lock ()); - return NULL; - } - - pmemzone->addr = addr; - pmemzone->length = length; - /*name must be less than NSFW_MEM_APPNAME_LENGTH */ - if (EOK != - STRCPY_S ((char *) pmemzone->aname, sizeof (pmemzone->aname), name)) - { - NSCOMM_LOGERR ("STRCPY_S failed]name=%s", name); - free (addr); - nsfw_write_unlock (nsfw_get_glb_lock ()); - return NULL; - } - - nsfw_write_unlock (nsfw_get_glb_lock ()); - return addr; -} - -/* - * create no shared memory - * nsfw_mem_zone::stname no shared memory name - * nsfw_mem_zone::isize memory size - */ -mzone_handle -nsfw_nshmem_create (nsfw_mem_zone * pinfo) -{ - - NSFW_NAME_LENCHECK_RET_NULL (pinfo->stname.aname, "nshmem create"); - NSFW_NSHMEM_INIT_CHK_RET_NULL (); - return nsfw_nshmem_reserv_safe (pinfo->stname.aname, pinfo->length); -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_lookup -* Description : find a block memory by name -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : mzone_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mzone_handle -nsfw_nshmem_lookup (nsfw_mem_name * pname) -{ - int icnt = 0; - nsfw_nshmem_mzone *mz = NULL; - - NSFW_NAME_LENCHECK_RET_NULL (pname->aname, "nshmem lookup"); - NSFW_NSHMEM_INIT_CHK_RET_NULL (); - nsfw_read_lock (nsfw_get_glb_lock ()); - - for (icnt = 0; icnt < NSFW_NSHMEM_ZONE_MAX; icnt++) - { - mz = &g_nshmem_internal_cfg->amemzone[icnt]; - - if (mz->addr != NULL - && !strncmp (pname->aname, mz->aname, NSFW_MEM_NAME_LENGTH)) - { - nsfw_read_unlock (nsfw_get_glb_lock ()); - return mz->addr; - } - } - - nsfw_read_unlock (nsfw_get_glb_lock ()); - return NULL; -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_release -* Description : free a block memory -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_nshmem_release (nsfw_mem_name * pname) -{ - int icnt = 0; - nsfw_nshmem_mzone *mz = NULL; - - NSFW_NAME_LENCHECK_RET (pname->aname, "nshmem release"); - NSFW_NSHMEM_INIT_CHK_RET (); - nsfw_read_lock (nsfw_get_glb_lock ()); - - for (icnt = 0; icnt < NSFW_NSHMEM_ZONE_MAX; icnt++) - { - mz = &g_nshmem_internal_cfg->amemzone[icnt]; - - if (mz->addr != NULL - && !strncmp (pname->aname, mz->aname, NSFW_MEM_NAME_LENGTH)) - { - nsfw_nshmem_free_zone (mz); - nsfw_read_unlock (nsfw_get_glb_lock ()); - return NSFW_MEM_OK; - } - } - - nsfw_read_unlock (nsfw_get_glb_lock ()); - return NSFW_MEM_OK; - -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_spcreate -* Description : create a memory pool by ring -* Input : nsfw_mem_sppool* pmpinfo -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -*****************************************************************************/ -mring_handle -nsfw_nshmem_spcreate (nsfw_mem_sppool * pmpinfo) -{ - size_t len = 0; - unsigned int usnum = common_mem_align32pow2 (pmpinfo->usnum + 1); - unsigned int uselt_size = pmpinfo->useltsize; - struct nsfw_mem_ring *pringhead = NULL; - unsigned int uscnt = 0; - char *pmz = NULL; - NSFW_NAME_LENCHECK_RET_NULL (pmpinfo->stname.aname, "nshmem sp create"); - NSFW_NSHMEM_INIT_CHK_RET_NULL (); - - len = - sizeof (struct nsfw_mem_ring) + - (size_t) usnum *sizeof (union RingData_U) + (size_t) usnum *uselt_size; - pringhead = - (struct nsfw_mem_ring *) nsfw_nshmem_reserv_safe (pmpinfo->stname.aname, - len); - - if (!pringhead) - { - NSCOMM_LOGERR ("nshmem sp create mzone reserv fail"); - return NULL; - } - - nsfw_mem_ring_init (pringhead, usnum, pringhead, NSFW_NSHMEM, - pmpinfo->enmptype); - pmz = - ((char *) pringhead + sizeof (struct nsfw_mem_ring) + - usnum * sizeof (union RingData_U)); - - for (uscnt = 0; uscnt < usnum; uscnt++) - { - if (0 == - g_ring_ops_arry[pringhead->memtype][pringhead-> - ringflag].ring_ops_enqueue - (pringhead, (void *) pmz)) - { - NSCOMM_LOGERR ("nsfw_nshmem_ringenqueue enqueue fail] uscnt=%u", - uscnt); - } - - pmz = pmz + uselt_size; - } - - return pringhead; -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_sp_lookup -* Description : look up a sppool memory -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -*****************************************************************************/ -mring_handle -nsfw_nshmem_sp_lookup (nsfw_mem_name * pname) -{ - return nsfw_nshmem_lookup (pname); -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_sprelease -* Description : release a sp pool -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_nshmem_sprelease (nsfw_mem_name * pname) -{ - NSFW_NAME_LENCHECK_RET (pname->aname, "nshmem sp mempool release"); - NSFW_NSHMEM_INIT_CHK_RET (); - return nsfw_nshmem_release (pname); -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_ringcreate -* Description : create a ring -* Input : nsfw_mem_mring* pringinfo -* Output : None -* Return Value : mring_handle -* Calls : -* Called By : -* -*****************************************************************************/ -mring_handle -nsfw_nshmem_ringcreate (nsfw_mem_mring * pringinfo) -{ - size_t len = 0; - unsigned int usnum = common_mem_align32pow2 (pringinfo->usnum + 1); - struct nsfw_mem_ring *pringhead = NULL; - NSFW_NAME_LENCHECK_RET_NULL (pringinfo->stname.aname, "nshmem ring create"); - NSFW_NSHMEM_INIT_CHK_RET_NULL (); - - len = sizeof (struct nsfw_mem_ring) + usnum * sizeof (union RingData_U); - pringhead = - (struct nsfw_mem_ring *) nsfw_nshmem_reserv_safe (pringinfo->stname.aname, - len); - - if (!pringhead) - { - NSCOMM_LOGERR ("nshmem ring create mzone reserv fail"); - return NULL; - } - - nsfw_mem_ring_init (pringhead, usnum, (void *) pringhead, NSFW_NSHMEM, - pringinfo->enmptype); - return pringhead; - -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_ringrelease -* Description : release a nsh ring memory -* Input : nsfw_mem_name* pname -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 -nsfw_nshmem_ringrelease (nsfw_mem_name * pname) -{ - NSFW_NAME_LENCHECK_RET (pname->aname, "nshmem ring mempool release"); - NSFW_NSHMEM_INIT_CHK_RET (); - return nsfw_nshmem_release (pname); -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_sppool_statics -* Description : static the memory size of sppool -* Input : mring_handle sppool -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ -ssize_t -nsfw_nshmem_sppool_statics (mring_handle sppool) -{ - struct nsfw_mem_ring *phead = (struct nsfw_mem_ring *) sppool; - - return sizeof (struct nsfw_mem_ring) + - (ssize_t) phead->size * sizeof (union RingData_U) + - (ssize_t) phead->size * phead->eltsize; -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_ring_statics -* Description : static the memory size of ring -* Input : mring_handle handle -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ -ssize_t -nsfw_nshmem_ring_statics (mring_handle handle) -{ - struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) handle; - return ring->size * sizeof (union RingData_U) + - sizeof (struct nsfw_mem_ring); -} - -/***************************************************************************** -* Prototype : nsfw_nshmem_static -* Description : static the memory size according to mem type -* Input : void* handle -* nsfw_mem_struct_type type -* Output : None -* Return Value : ssize_t -* Calls : -* Called By : -* -*****************************************************************************/ -ssize_t -nsfw_nshmem_static (void *handle, nsfw_mem_struct_type type) -{ - switch (type) - { - case NSFW_MEM_MBUF: - return -1; - case NSFW_MEM_SPOOL: - return nsfw_nshmem_sppool_statics (handle); - case NSFW_MEM_RING: - return nsfw_nshmem_ring_statics (handle); - default: - break; - } - return -1; -} diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.h b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.h deleted file mode 100644 index 06ab562..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_mng.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* -* 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 _NSFW_NSHMEM_MNG_H_ -#define _NSFW_NSHMEM_MNG_H_ - -#include "generic/common_mem_rwlock.h" - -#include "common_func.h" - -#define NSFW_NSHMEM_ZONE_MAX 2560 - -typedef struct -{ - i8 aname[NSFW_MEM_NAME_LENGTH]; - void *addr; - int length; -} nsfw_nshmem_mzone; - -typedef struct -{ - nsfw_nshmem_mzone amemzone[NSFW_NSHMEM_ZONE_MAX]; - common_mem_rwlock_t mlock; -} nsfw_nshmem_cfg; - -/* - * no share memory module init - */ -i32 nsfw_nshmem_init (nsfw_mem_para * para); - -/* - * no share memory module destory - */ -void nsfw_nshmem_destory (void); - -/* - * create a no shared memory - */ -mzone_handle nsfw_nshmem_create (nsfw_mem_zone * pinfo); - -mzone_handle nsfw_nshmem_lookup (nsfw_mem_name * pname); - -i32 nsfw_nshmem_release (nsfw_mem_name * pname); - -mring_handle nsfw_nshmem_spcreate (nsfw_mem_sppool * pmpinfo); - -i32 nsfw_nshmem_sprelease (nsfw_mem_name * pname); - -mring_handle nsfw_nshmem_sp_lookup (nsfw_mem_name * pname); - -mring_handle nsfw_nshmem_ringcreate (nsfw_mem_mring * pringinfo); - -i32 nsfw_nshmem_ringrelease (nsfw_mem_name * pname); - -ssize_t nsfw_nshmem_static (void *handle, nsfw_mem_struct_type type); - -#endif diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.c b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.c deleted file mode 100644 index 7e56f3c..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.c +++ /dev/null @@ -1,437 +0,0 @@ -/* -* -* 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 <sched.h> -#include "nstack_securec.h" - -#include "nsfw_mem_desc.h" -#include "nsfw_nshmem_ring.h" -#include "nsfw_ring_fun.h" -#include "common_func.h" - -/*copy the data to obj*/ -NSTACK_STATIC inline void -nsfw_nshmem_ring_obj_copy (struct nsfw_mem_ring *r, uint32_t cons_head, - void **obj_table, unsigned n) -{ - uint32_t idx = cons_head & r->mask; - unsigned i = 0; - const uint32_t size = r->size; - - if (likely (idx + n < size)) - { - for (i = 0; i < (n & (~(unsigned) 0x3)); i += 4, idx += 4) - { - obj_table[i] = (void *) r->ring[idx].data_l; - obj_table[i + 1] = (void *) r->ring[idx + 1].data_l; - obj_table[i + 2] = (void *) r->ring[idx + 2].data_l; - obj_table[i + 3] = (void *) r->ring[idx + 3].data_l; - } - switch (n & 0x3) - { - case 3: - obj_table[i++] = (void *) r->ring[idx++].data_l; - - case 2: - obj_table[i++] = (void *) r->ring[idx++].data_l; - - case 1: - obj_table[i++] = (void *) r->ring[idx++].data_l; - } - } - else - { - for (i = 0; idx < size; i++, idx++) - { - obj_table[i] = (void *) r->ring[idx].data_l; - } - - for (idx = 0; i < n; i++, idx++) - { - obj_table[i] = (void *) r->ring[idx].data_l; - } - } -} - -/*fork recover*/ -NSTACK_STATIC inline void -nsfw_nshmem_enqueue_fork_recov (struct nsfw_mem_ring *r) -{ - u32_t pidflag = 0; - u32_t curpid = get_sys_pid (); - int success = 0; - /*if pid is not the same, maybe mult thread fork happen */ - pidflag = r->prodhflag; - - if (unlikely (pidflag != curpid)) - { - success = common_mem_atomic32_cmpset (&r->prodhflag, pidflag, curpid); - - if (unlikely (success != 0)) - { - /*recover it */ - if (r->prod.tail != r->prod.head) - { - r->prod.head = r->prod.tail; - } - - r->prodtflag = curpid; - } - } - - return; -} - -NSTACK_STATIC inline void -nsfw_nshmem_dequeue_fork_recov (struct nsfw_mem_ring *r) -{ - u32_t pidflag = 0; - u32_t curpid = get_sys_pid (); - int success = 0; - /*if pid is not the same, maybe mult thread fork happen */ - pidflag = r->conshflag; - - if (unlikely (pidflag != curpid)) - { - success = common_mem_atomic32_cmpset (&r->conshflag, pidflag, curpid); - - if (unlikely (success != 0)) - { - /*recover it */ - if (r->cons.tail != r->cons.head) - { - r->cons.head = r->cons.tail; - } - - r->constflag = curpid; - } - } - - return; -} - -/* -this is a multi thread/process enqueue function, please pay attention to the bellow point -1. while Enqueue corrupt, we may lose one element; because no one to add the Head -*/ -int -nsfw_nshmem_ring_mp_enqueue (struct nsfw_mem_ring *mem_ring, void *obj_table) -{ - uint32_t producer_head, producer_next; - uint32_t consumer_tail, free_entries; - int success; - unsigned rep = 0; - uint32_t mask = mem_ring->mask; - uint32_t size = mem_ring->size; - uint32_t n = 1; - - /* move prod.head atomically */ - do - { - - producer_head = mem_ring->prod.head; - consumer_tail = mem_ring->cons.tail; - /* The subtraction is done between two unsigned 32bits value - * (the result is always modulo 32 bits even if we have - * producer_head > consumer_tail). So 'free_entries' is always between 0 - * and size(ring)-1. */ - free_entries = (size + consumer_tail - producer_head); - - /* check that we have enough room in ring */ - if (unlikely (n > free_entries)) - { - return 0; - /* Below code is commented currenlty as its a dead code. */ - } - - /*if pid is not the same, maybe mult thread fork happen */ - nsfw_nshmem_enqueue_fork_recov (mem_ring); - - while (unlikely - ((mem_ring->prod.tail != mem_ring->prod.head) - || (mem_ring->prodtflag != mem_ring->prodhflag))) - { - common_mem_pause (); - } - - producer_next = producer_head + n; - success = - common_mem_atomic32_cmpset (&mem_ring->prod.head, producer_head, - producer_next); - } - while (unlikely (success == 0)); - - mem_ring->ring[producer_head & mask].data_l = (u64) obj_table; - - /* - * If there are other enqueues in progress that preceded us, - * we need to wait for them to complete - */ - while (unlikely (mem_ring->prod.tail != producer_head)) - { - common_mem_pause (); - - /* Set COMMON_RING_PAUSE_REP_COUNT to avoid spin too long waiting - * for other thread finish. It gives pre-emptied thread a chance - * to proceed and finish with ring dequeue operation. */ - /* check the queue can be operate */ - if (++rep == 5) - { - rep = 0; - (void) sched_yield (); - } - } - - mem_ring->prod.tail = producer_next; - return (int) n; -} - -/* - this is a single thread/process enqueue function - */ -int -nsfw_nshmem_ring_sp_enqueue (struct nsfw_mem_ring *r, void *obj_table) -{ - uint32_t producer_head, consumer_tail; - uint32_t producer_next, free_entries; - uint32_t mask = r->mask; - uint32_t n = 1; - uint32_t size = r->size; - - producer_head = r->prod.head; - consumer_tail = r->cons.tail; - /* The subtraction is done between two unsigned 32bits value - * (the result is always modulo 32 bits even if we have - * producer_head > consumer_tail). So 'free_entries' is always between 0 - * and size(ring)-1. */ - free_entries = size + consumer_tail - producer_head; - - /* check that we have enough room in ring */ - if (unlikely (n > free_entries)) - { - return 0; - } - - nsfw_nshmem_enqueue_fork_recov (r); - - producer_next = producer_head + n; - r->prod.head = producer_next; - - r->ring[producer_head & mask].data_l = (u64) obj_table; - - r->prod.tail = producer_next; - return (int) n; -} - -/* - this is enhanced mc_ring_dequeue, support dequeue multi element one time. -*/ -int -nsfw_nshmem_ring_mc_dequeuev (struct nsfw_mem_ring *r, void **obj_table, - unsigned int n) -{ - uint32_t consumer_head, producer_tail; - uint32_t consumer_next, entries; - int success; - unsigned rep = 0; - uint32_t num = n; - - /* Avoid the unnecessary cmpset operation below, which is also - * potentially harmful when n equals 0. */ - if (unlikely (num == 0)) - { - return 0; - } - - nsfw_nshmem_dequeue_fork_recov (r); - - /* move cons.head atomically */ - do - { - num = n; - consumer_head = r->cons.head; - producer_tail = r->prod.tail; - /* The subtraction is done between two unsigned 32bits value - * (the result is always modulo 32 bits even if we have - * cons_head > prod_tail). So 'entries' is always between 0 - * and size(ring)-1. */ - entries = (producer_tail - consumer_head); - - /* Set the actual entries for dequeue */ - if (unlikely (num > entries)) - { - if (likely (entries > 0)) - { - num = entries; - } - else - { - return 0; - } - } - - /* check the queue can be operate */ - while (unlikely - ((r->cons.tail != r->cons.head) - || (r->conshflag != r->constflag))) - { - common_mem_pause (); - } - - consumer_next = consumer_head + num; - - success = - common_mem_atomic32_cmpset (&r->cons.head, consumer_head, - consumer_next); - } - while (unlikely (success == 0)); - - nsfw_nshmem_ring_obj_copy (r, consumer_head, obj_table, num); - - /* - * If there are other dequeues in progress that preceded us, - * we need to wait for them to complete - */ - while (unlikely (r->cons.tail != consumer_head)) - { - common_mem_pause (); - - /* Set COMMON_RING_PAUSE_REP_COUNT to avoid spin too long waiting - * for other thread finish. It gives pre-emptied thread a chance - * to proceed and finish with ring dequeue operation. */ - /* check the queue can be operate */ - if (++rep == 5) - { - rep = 0; - (void) sched_yield (); - } - } - - r->cons.tail = consumer_next; - - return (int) num; -} - -/*this is a multi thread/process dequeue function, please pay attention to the bellow point -1. while dequeue corrupt, the tail no one added, may multi the try times. -*/ -int -nsfw_nshmem_ring_mc_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - return nsfw_nshmem_ring_mc_dequeuev (ring, box, 1); -} - -/* - this is a single thread/process dequeue function -*/ -int -nsfw_nshmem_ring_sc_dequeuev (struct nsfw_mem_ring *r, void **obj_table, - unsigned int n) -{ - uint32_t consumer_head, producer_tail; - uint32_t consumer_next, entries; - uint32_t inum = n; - consumer_head = r->cons.head; - producer_tail = r->prod.tail; - /* The subtraction is done between two unsigned 32bits value - * (the result is always modulo 32 bits even if we have - * cons_head > prod_tail). So 'entries' is always between 0 - * and size(ring)-1. */ - entries = producer_tail - consumer_head; - - if (unlikely (inum > entries)) - { - if (likely (entries > 0)) - { - inum = entries; - } - else - { - return 0; - } - } - - nsfw_nshmem_dequeue_fork_recov (r); - - consumer_next = consumer_head + inum; - r->cons.head = consumer_next; - - nsfw_nshmem_ring_obj_copy (r, consumer_head, obj_table, inum); - - r->cons.tail = consumer_next; - return (int) inum; -} - -/* - this is enhanced mc_ring_dequeue, support dequeue multi element one time. -*/ -int -nsfw_nshmem_ring_sc_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - return nsfw_nshmem_ring_sc_dequeuev (ring, box, 1); -} - -/*stack just using one thread, for performance using que not support multi thread*/ -int -nsfw_nshmem_ring_singlethread_enqueue (struct nsfw_mem_ring *ring, void *box) -{ - u32 head = 0; - - /*if queue is full, just return 0 */ - if (unlikely (ring->prod.head >= (ring->size + ring->cons.tail))) - { - return 0; - } - - head = ring->prod.head; - ring->ring[head & ring->mask].data_l = (u64) box; - ring->prod.head++; - return 1; -} - -/*stack just using one thread, for performance using que not support multi thread*/ -int -nsfw_nshmem_ring_singlethread_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - return nsfw_nshmem_ring_singlethread_dequeuev (ring, box, 1); -} - -/*stack just using one thread, for performance using que not support multi thread*/ -int -nsfw_nshmem_ring_singlethread_dequeuev (struct nsfw_mem_ring *ring, - void **box, unsigned int n) -{ - u32 tail = 0; - u32 num = 0; - - while (num < n) - { - tail = ring->cons.tail; - - /* if all entries are dequeued return 0 */ - if (unlikely (ring->prod.head == ring->cons.tail)) - { - return num; - } - - box[num] = (void *) ring->ring[tail & ring->mask].data_l; - ring->cons.tail++; - num++; - } - - return num; -} diff --git a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.h b/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.h deleted file mode 100644 index 93a4d4a..0000000 --- a/src/framework/common/mem_mgr/nsfw_nshmem/nsfw_nshmem_ring.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* -* 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 _NSFW_NSHMEM_RING_H_ -#define _NSFW_NSHMEM_RING_H_ - -#include <stdint.h> - -int nsfw_nshmem_ring_mp_enqueue (struct nsfw_mem_ring *ring, void *box); -int nsfw_nshmem_ring_sp_enqueue (struct nsfw_mem_ring *ring, void *box); -int nsfw_nshmem_ring_mc_dequeue (struct nsfw_mem_ring *ring, void **box); -int nsfw_nshmem_ring_mc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n); -int nsfw_nshmem_ring_sc_dequeue (struct nsfw_mem_ring *ring, void **box); -int nsfw_nshmem_ring_sc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n); -int nsfw_nshmem_ring_singlethread_enqueue (struct nsfw_mem_ring *ring, - void *box); -int nsfw_nshmem_ring_singlethread_dequeue (struct nsfw_mem_ring *ring, - void **box); -int nsfw_nshmem_ring_singlethread_dequeuev (struct nsfw_mem_ring *ring, - void **box, unsigned int n); - -#endif /*_NSFW_NSHMEM_RING_H_*/ diff --git a/src/framework/common/mem_mgr/nsfw_res_mgr.c b/src/framework/common/mem_mgr/nsfw_res_mgr.c deleted file mode 100644 index c4d8010..0000000 --- a/src/framework/common/mem_mgr/nsfw_res_mgr.c +++ /dev/null @@ -1,429 +0,0 @@ -/* -* -* 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 * - *----------------------------------------------*/ - -/*==============================================* - * constants or macros define * - *----------------------------------------------*/ - -/*==============================================* - * project-wide global variables * - *----------------------------------------------*/ - -/*==============================================* - * routines' or functions' implementations * - *----------------------------------------------*/ - -#include <stdlib.h> -#include "types.h" -#include "nstack_securec.h" -#include "nsfw_init.h" -#include "common_mem_mbuf.h" - -#include "nstack_log.h" -#include "nsfw_maintain_api.h" - -#include "nsfw_mem_api.h" -#include "nsfw_fd_timer_api.h" -#include "nsfw_ring_data.h" - -#include "common_func.h" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C"{ -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -nsfw_res_mgr_item_cfg g_all_res_can[NSFW_MAX_RES_SCAN_COUNT]; - -#define NSFW_RES_SCAN_TVLAUE_DEF 60 -#define NSFW_RES_SCAN_TVLAUE (g_scan_cfg.scan_tvalue) - -typedef struct _nsfw_res_scan_init_cfg -{ - nsfw_timer_info *scan_timer; - u16 scan_tvalue; -} nsfw_res_scan_init_cfg; -nsfw_res_scan_init_cfg g_scan_cfg; - -u8 -nsfw_res_mgr_reg (nsfw_res_scn_cfg * cfg) -{ - if (NULL == cfg) - { - NSFW_LOGERR ("argv err!"); - return FALSE; - } - - u32 i; - for (i = 0; i < NSFW_MAX_RES_SCAN_COUNT; i++) - { - if ((NULL == g_all_res_can[i].scn_cfg.free_fun) - && - (__sync_bool_compare_and_swap - (&g_all_res_can[i].scn_cfg.free_fun, 0, cfg->free_fun))) - { - g_all_res_can[i].scn_cfg = *cfg; - NSFW_LOGINF ("reg res_mgr fun suc]fun=%p,data=%p", cfg->free_fun, - cfg->data); - return TRUE; - } - } - - NSFW_LOGERR - ("reg]type=%u,per=%u,chk=%u,cyc=%u,total=%u,size=%u,offset=%u,fun=%p,data=%p", - cfg->type, cfg->force_free_percent, cfg->force_free_chk_num, - cfg->num_per_cyc, cfg->total_num, cfg->elm_size, cfg->res_mem_offset, - cfg->res_mem_offset, cfg->free_fun, cfg->data); - return FALSE; -} - -static inline u32 -nsfw_get_alloc_count (u32 head, u32 tail) -{ - if (head >= tail) - { - return head - tail; - } - - return head + (0xFFFFFFFF - tail); -} - -int -nsfw_res_sp_item_chk (void *data, void *argv) -{ - nsfw_res_mgr_item_cfg *res_scn_item = (nsfw_res_mgr_item_cfg *) argv; - nsfw_res_scn_cfg *scn_cfg = &res_scn_item->scn_cfg; - char *elm = (char *) data; - - if (NULL == scn_cfg || NULL == elm) - { - return FALSE; - } - - nsfw_res *res_item = NULL; - res_item = (nsfw_res *) (elm + scn_cfg->res_mem_offset); - if (0 == res_item->chk_count) - { - res_item->data = res_scn_item->cons_head; - } - res_item->chk_count++; - - if (res_item->chk_count < scn_cfg->force_free_chk_num) - { - return FALSE; - } - - if (res_scn_item->free_percent > scn_cfg->force_free_percent) - { - return FALSE; - } - - if (scn_cfg->total_num * scn_cfg->alloc_speed_factor > - nsfw_get_alloc_count (res_scn_item->cons_head, res_item->data)) - { - return FALSE; - } - - if (NULL == scn_cfg->free_fun) - { - return FALSE; - } - - if (TRUE == scn_cfg->free_fun ((void *) elm)) - { - res_scn_item->force_count++; - } - - res_item->chk_count = 0; - return TRUE; -} - -int -nsfw_res_flash_data (nsfw_res_mgr_item_cfg * res_scn_item) -{ - nsfw_res_scn_cfg *scn_cfg = &res_scn_item->scn_cfg; - - u32 cur_head = 0; - u32 cur_tail = 0; - u32 elm_num = 0; - u32 free_count = 0; - - switch (scn_cfg->type) - { - case NSFW_RES_SCAN_MBUF: - { - struct common_mem_ring *ring = - (struct common_mem_ring *) scn_cfg->mgr_ring; - struct common_mem_mempool *mp = - (struct common_mem_mempool *) scn_cfg->data; - if (NULL == ring) - { - ring = mp->pool_data; - if (NULL == ring) - return FALSE; - } - cur_head = ring->prod.head; - cur_tail = ring->cons.head; - elm_num = mp->size; - } - break; - case NSFW_RES_SCAN_SPOOL: - { - struct nsfw_mem_ring *mem_ring = - (struct nsfw_mem_ring *) scn_cfg->mgr_ring; - if (NULL == mem_ring) - { - mem_ring = (struct nsfw_mem_ring *) scn_cfg->data; - if (NULL == mem_ring) - return FALSE; - } - - cur_head = mem_ring->prod.head; - cur_tail = mem_ring->cons.tail; - elm_num = mem_ring->size; - } - break; - case NSFW_RES_SCAN_ARRAY: - { - struct nsfw_mem_ring *mem_ring = - (struct nsfw_mem_ring *) scn_cfg->mgr_ring; - if (NULL == mem_ring) - { - return FALSE; - } - - cur_head = mem_ring->prod.head; - cur_tail = mem_ring->cons.tail; - elm_num = scn_cfg->total_num; - } - break; - default: - return FALSE; - } - - free_count = nsfw_get_alloc_count (cur_head, cur_tail); - - res_scn_item->cons_head = cur_head; - res_scn_item->prod_head = cur_tail; - if (0 != elm_num) - { - res_scn_item->free_percent = free_count * 100 / elm_num; - } - else - { - res_scn_item->free_percent = 100; - } - - scn_cfg->total_num = elm_num; - return TRUE; -} - -void -nsfw_res_scan_mem (nsfw_res_mgr_item_cfg * res_scn_item) -{ - if (NULL == res_scn_item) - { - return; - } - - nsfw_res_scn_cfg *scn_cfg = &res_scn_item->scn_cfg; - if (NULL == scn_cfg->data) - { - return; - } - - u32 start = res_scn_item->last_scn_idx; - u32 end = start + scn_cfg->num_per_cyc; - int res_chk_number = 0; - if (NSFW_RES_SCAN_SPOOL == scn_cfg->type) - { - res_chk_number = - nsfw_mem_sp_iterator (scn_cfg->data, start, end, - nsfw_res_sp_item_chk, (void *) res_scn_item); - } - else - { - res_chk_number = - nsfw_mem_mbuf_iterator (scn_cfg->data, start, end, - nsfw_res_sp_item_chk, (void *) res_scn_item); - } - - if (0 == res_chk_number) - { - res_scn_item->last_scn_idx = 0; - start = res_scn_item->last_scn_idx; - end = start + scn_cfg->num_per_cyc; - if (NSFW_RES_SCAN_SPOOL == scn_cfg->type) - { - res_chk_number = - nsfw_mem_sp_iterator (scn_cfg->data, start, end, - nsfw_res_sp_item_chk, - (void *) res_scn_item); - } - else - { - res_chk_number = - nsfw_mem_mbuf_iterator (scn_cfg->data, start, end, - nsfw_res_sp_item_chk, - (void *) res_scn_item); - } - } - - if (res_chk_number + start < end) - { - res_scn_item->last_scn_idx = 0; - } - else - { - res_scn_item->last_scn_idx += res_chk_number; - } - - return; -} - -void -nsfw_res_scan_array (nsfw_res_mgr_item_cfg * res_scn_item) -{ - if (NULL == res_scn_item) - { - return; - } - - nsfw_res_scn_cfg *scn_cfg = &res_scn_item->scn_cfg; - if (NULL == scn_cfg->data) - { - return; - } - - u32 i; - char *elm = - (char *) scn_cfg->data + (res_scn_item->last_scn_idx * scn_cfg->elm_size); - for (i = res_scn_item->last_scn_idx; i < scn_cfg->total_num; i++) - { - if (i >= res_scn_item->last_scn_idx + scn_cfg->num_per_cyc) - { - break; - } - - if (TRUE == nsfw_res_sp_item_chk (elm, (void *) res_scn_item)) - { - NSFW_LOGINF ("force free item]data=%p,cfg=%p", elm, res_scn_item); - } - - elm += scn_cfg->elm_size; - } - - if (i >= scn_cfg->total_num) - { - res_scn_item->last_scn_idx = 0; - } - else - { - res_scn_item->last_scn_idx = i; - } - - return; -} - -void -nsfw_res_scan_proc (nsfw_res_mgr_item_cfg * res_scn_item) -{ - (void) nsfw_res_flash_data (res_scn_item); - switch (res_scn_item->scn_cfg.type) - { - case NSFW_RES_SCAN_ARRAY: - nsfw_res_scan_array (res_scn_item); - break; - case NSFW_RES_SCAN_SPOOL: - case NSFW_RES_SCAN_MBUF: - nsfw_res_scan_mem (res_scn_item); - break; - default: - break; - } -} - -int -nsfw_res_scan_all (u32 timer_type, void *data) -{ - NSFW_LOGDBG ("scan start!"); - struct timespec time_left = { NSFW_RES_SCAN_TVLAUE, 0 }; - g_scan_cfg.scan_timer = - nsfw_timer_reg_timer (0, NULL, nsfw_res_scan_all, time_left); - - if (g_hbt_switch) - { - return TRUE; - } - - int i; - for (i = 0; i < NSFW_MAX_RES_SCAN_COUNT; i++) - { - /*last fun */ - if (NULL == g_all_res_can[i].scn_cfg.data) - { - break; - } - - nsfw_res_scan_proc (&g_all_res_can[i]); - } - - return TRUE; -} - -static int nsfw_resmgr_module_init (void *param); -static int -nsfw_resmgr_module_init (void *param) -{ - u8 proc_type = (u8) ((long long) param); - NSFW_LOGINF ("res mgr module init]type=%u", proc_type); - g_scan_cfg.scan_tvalue = NSFW_RES_SCAN_TVLAUE_DEF; - switch (proc_type) - { - case NSFW_PROC_MAIN: - { - struct timespec time_left = { NSFW_RES_SCAN_TVLAUE, 0 }; - g_scan_cfg.scan_timer = - nsfw_timer_reg_timer (0, NULL, nsfw_res_scan_all, time_left); - return 0; - } - default: - if (proc_type < NSFW_PROC_MAX) - { - break; - } - return -1; - } - - return 0; -} - -/* *INDENT-OFF* */ -NSFW_MODULE_NAME(NSFW_RES_MGR_MODULE) -NSFW_MODULE_PRIORITY(99) -NSFW_MODULE_INIT(nsfw_resmgr_module_init) -/* *INDENT-ON* */ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.c b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.c deleted file mode 100644 index c29b108..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.c +++ /dev/null @@ -1,987 +0,0 @@ -/* -* -* 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 "nstack_securec.h" -#include "nstack_log.h" -#include "nsfw_ring_fun.h" -#include "nsfw_shmem_ring.h" -#include "nsfw_shmem_mng.h" -#include "common_mem_buf.h" -#include "common_mem_common.h" - -#include "common_func.h" - -/*get the base address of msg data */ -#define NSFW_SHMEM_GET_DATA(pmsg, type) (type *)&((pmsg)->aidata[0]) - -/*if input point is nun, just return null*/ -#define NSFW_POINT_CHK_RET_NULL(p, desc) \ - if (NULL == (p)) \ - { \ - NSCOMM_LOGERR("point check fail] desc_para=%s", desc); \ - return NULL; \ - } - -/*if input point is nun, just return err num*/ -#define NSFW_POINT_CHK_RET_ERR(p, desc) \ - if (NULL == (p)) \ - { \ - NSCOMM_LOGDBG("point check fail] desc_para=%s", desc); \ - return NSFW_MEM_ERR; \ - } - -/*if input point is nun, goto flag*/ -#define NSFW_POINT_CHK_RET_GOTO(p, gotoflag, desc) \ - if (NULL == (p)) \ - { \ - NSCOMM_LOGERR("point check fail] desc_para=%s", desc); \ - goto gotoflag; \ - } - -/*init the msg head*/ -#define NSFW_SHMEM_MSG_HEAD_INIT(pmsg, type, length) { \ - (pmsg)->usmsg_type = (type); \ - (pmsg)->uslength = (length); \ - } - -/*rsp msg head check, and if err goto*/ -#define NSFW_SHMEM_MSGHEAD_CHK_GOTO(pmsg, type, length, gotoflag) { \ - if (((type) != pmsg->usmsg_type) && ((length) != pmsg->uslength)) \ - { \ - NSCOMM_LOGERR("check fail] msgtype=%d, type_para=%d, len=%d", (pmsg->usmsg_type), (type), (length)); \ - goto gotoflag; \ - } \ - } - -/*rsp check the state*/ -#define NSFW_SHMEM_ACKSTATE_CHK_GOTO(expret, ret, expseg, seg, gotoflag) { \ - if (((ret) != (expret)) || ((expseg) != (seg))) \ - { \ - NSCOMM_LOGERR("ackstate check fail]msgack exp=%d, real=%d,eseg=%d, rseg=%d", (expret), (ret), (expseg), (seg)); \ - goto gotoflag; \ - } \ - } - -/*mzone msg init*/ -#define NSFW_SHMEM_MZONE_DATA_INIT(pdata, slength, seg, socketid) { \ - (pdata)->isocket_id = (socketid); \ - (pdata)->length = (slength); \ - (pdata)->usseq = (seg); \ - (pdata)->ireserv = 0; \ - } - -/*mbuf msg init*/ -#define NSFW_SHMEM_MBUF_DATA_INIT(pdata, seg, num, cashsize, priv_size, data_room, flag, socketid) { \ - (pdata)->usseq = (seg); \ - (pdata)->usnum = (num); \ - (pdata)->uscash_size = (cashsize); \ - (pdata)->uspriv_size = (priv_size); \ - (pdata)->usdata_room = (data_room); \ - (pdata)->enmptype = (flag); \ - (pdata)->isocket_id = (socketid); \ - (pdata)->ireserv = 0; \ - } - -/*mpool msg init*/ -#define NSFW_SHMEM_MPOOL_DATA_INIT(pdata, seg, num, eltsize, flag, socketid) { \ - (pdata)->usseq = (seg); \ - (pdata)->usnum = (num); \ - (pdata)->useltsize = (eltsize); \ - (pdata)->enmptype = (flag); \ - (pdata)->isocket_id = (socketid); \ - (pdata)->ireserv = 0; \ - } - -/*mring msg init*/ -#define NSFW_SHMEM_MRING_DATA_INIT(pdata, seg, num, flag, socketid) { \ - (pdata)->usseq = (seg); \ - (pdata)->usnum = (num); \ - (pdata)->enmptype = (flag); \ - (pdata)->isocket_id = (socketid); \ - (pdata)->ireserv = 0; \ - } - -#define NSFW_SHMEM_MSG_FREE(pmsg, prsp_msg) {\ - if (pmsg) \ - { \ - nsfw_mgr_msg_free(pmsg); \ - } \ - if (prsp_msg) \ - { \ - nsfw_mgr_msg_free(prsp_msg); \ - } \ -} - -/* - * create a block memory by send a msg - * - */ -mzone_handle -nsfw_memzone_remote_reserv (const i8 * name, size_t mlen, i32 socket_id) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - - /*msg head point define */ - nsfw_shmem_msg_head *pdata_head = NULL; - - /*msg data point define */ - nsfw_shmem_reserv_req *pdata = NULL; - nsfw_shmem_msg_head *pack_head = NULL; - - /*ack msg define */ - nsfw_shmem_ack *pack_data = NULL; - - mzone_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - - //pmsg = nsfw_mgr_msg_alloc(MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MASTER); - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_NULL (pmsg, "remote reserv pmsg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, release, "remote reserv rspmsg alloc"); - - /*msg head init */ - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_RESERV_REQ_MSG, - sizeof (nsfw_shmem_reserv_req)); - - /*msg data init */ - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_reserv_req); - iretval = STRCPY_S (pdata->aname, sizeof (pdata->aname), name); - if (EOK != iretval) - { - NSCOMM_LOGERR ("reserv mem copy name fail] ret=%d", iretval); - goto release; - } - - /*fill msg data */ - NSFW_SHMEM_MZONE_DATA_INIT (pdata, mlen, (u16) 0, socket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("reserv mem req rsp fail] ret=%u", ucret); - goto release; - } - - /*interrupt msg head */ - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_RESERV_ACK_MSG, - sizeof (nsfw_shmem_ack), release); - - pack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, pack_data->cstate, 0, - pack_data->usseq, release); - - hhandle = (mzone_handle) ADDR_SHTOL (pack_data->pbase_addr); - NSCOMM_LOGDBG ("mem reserve] name=%s, handle=%p, seg=%u", name, hhandle, - pack_data->usseq); -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return hhandle; -} - -/* - *create some memories by send a msg - */ -i32 -nsfw_memzone_remote_reserv_v (nsfw_mem_zone * pmeminfo, - mzone_handle * paddr_array, i32 inum, pid_t pid) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - nsfw_shmem_msg_head *pdata_head = NULL; - nsfw_shmem_reserv_req *pdata = NULL; - nsfw_shmem_reserv_req *ptempdata = NULL; - nsfw_shmem_msg_head *pack_head = NULL; - - nsfw_shmem_ack *pack_data = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - i32 icount = 0; - i32 itindex = 0; - i32 iindex = 0; - u16 ussegbase = 0; - u16 ustempv = 0; - i32 ieltnum = 0; - i32 ieltnum_max = - (NSFW_MGR_MSG_BODY_LEN - - sizeof (nsfw_shmem_msg_head)) / sizeof (nsfw_shmem_reserv_req); - - //pmsg = nsfw_mgr_msg_alloc(MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MASTER); - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_GOTO (pmsg, err, "remote reserv_v msg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, err, "remote reserv_v rspmsg alloc"); - - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - - ptempdata = pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_reserv_req); - - do - { - icount++; - ieltnum++; - - if (((icount % ieltnum_max) == 0) || (icount >= inum)) - { - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_RESERV_REQ_MSG, - ieltnum * sizeof (nsfw_shmem_reserv_req)); - - itindex = icount - 1; - int retVal = - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmeminfo[itindex].stname.aname, pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - } - NSFW_SHMEM_MZONE_DATA_INIT (ptempdata, pmeminfo[itindex].length, - (u16) itindex, - pmeminfo[itindex].isocket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("reserv v mem req rsp fail] ret=%u", ucret); - goto err; - } - - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_RESERV_ACK_MSG, - ieltnum * sizeof (nsfw_shmem_ack), - err); - - pack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - - for (iindex = 0; iindex < ieltnum; iindex++) - { - ustempv = ussegbase + iindex; - - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, - pack_data->cstate, ustempv, - (u16) pack_data->usseq, err); - - paddr_array[ustempv] = ADDR_SHTOL (pack_data->pbase_addr); - NSCOMM_LOGDBG ("remote reserve]index=%u, seg=%u, handle=%p", - ustempv, pack_data->usseq, paddr_array[ustempv]); - pack_data++; - } - - ussegbase = icount; - ieltnum = 0; - ptempdata = pdata; - } - else - { - itindex = icount - 1; - int retVal = - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmeminfo[itindex].stname.aname, pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - } - NSFW_SHMEM_MZONE_DATA_INIT (ptempdata, pmeminfo[itindex].length, - (u16) itindex, - pmeminfo[itindex].isocket_id); - ptempdata++; - } - } - while (icount < inum); - - iretval = NSFW_MEM_OK; - goto free; - -err: - iretval = NSFW_MEM_ERR; -free: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return iretval; -} - -/* - *release a block memory with name by send msg - */ -i32 -nsfw_remote_free (const i8 * name, nsfw_mem_struct_type entype) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - - nsfw_shmem_msg_head *pdata_head = NULL; - - nsfw_shmem_free_req *pdata = NULL; - - nsfw_shmem_msg_head *pack_head = NULL; - nsfw_shmem_ack *pack_data = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_ERR (pmsg, "remote free msg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, terr, "remote free rspmsg alloc"); - - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_RELEASE_REQ_MSG, - sizeof (nsfw_shmem_free_req)); - - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_free_req); - if (EOK != STRCPY_S (pdata->aname, sizeof (pdata->aname), name)) - { - NSCOMM_LOGERR ("STRCPY_S failed]name=%s", name); - } - pdata->usseq = 0; - pdata->ustype = entype; - pdata->ireserv = 0; - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("free mem req rsp fail] ret=%u", ucret); - goto release; - } - - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_RELEASE_ACK_MSG, - sizeof (nsfw_shmem_ack), terr); - - pack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, pack_data->cstate, 0, - pack_data->usseq, terr); - - iretval = NSFW_MEM_OK; - goto release; -terr: - iretval = NSFW_MEM_ERR; -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return iretval; -} - -/* - *create a mbuf pool by send a msg - */ -mpool_handle -nsfw_remote_shmem_mbf_create (const i8 * name, unsigned n, - unsigned cache_size, unsigned priv_size, - unsigned data_room_size, i32 socket_id, - nsfw_mpool_type entype) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - nsfw_shmem_msg_head *pdata_head = NULL; - nsfw_shmem_mbuf_req *pdata = NULL; - nsfw_shmem_msg_head *tpack_head = NULL; - nsfw_shmem_ack *tpack_data = NULL; - mpool_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_NULL (pmsg, "remote mbf create pmsg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, release, "remote mbf create msg alloc"); - - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_MBUF_REQ_MSG, - sizeof (nsfw_shmem_mbuf_req)); - - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_mbuf_req); - iretval = STRCPY_S (pdata->aname, sizeof (pdata->aname), name); - if (EOK != iretval) - { - NSCOMM_LOGERR ("mbf create name cpy fail] ret=%d", iretval); - goto release; - } - - NSFW_SHMEM_MBUF_DATA_INIT (pdata, 0, n, cache_size, priv_size, - data_room_size, (u16) entype, socket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("mbf create mem req rsp fail] ret=%u", ucret); - goto release; - } - - tpack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (tpack_head, NSFW_MBUF_ACK_MSG, - sizeof (nsfw_shmem_ack), release); - - tpack_data = NSFW_SHMEM_GET_DATA (tpack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, tpack_data->cstate, 0, - tpack_data->usseq, release); - - hhandle = ADDR_SHTOL (tpack_data->pbase_addr); - NSCOMM_LOGDBG ("mbf create] name=%s, handle=%p, seg=%u", name, hhandle, - tpack_data->usseq); -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return hhandle; -} - -/* - *create some mbuf pools - */ -i32 -nsfw_remote_shmem_mbf_createv (nsfw_mem_mbfpool * pmbfname, - mpool_handle * phandle_array, i32 inum, - pid_t pid) -{ - /*msg point define */ - nsfw_mgr_msg *mbpmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - nsfw_shmem_msg_head *pdata_head = NULL; - - nsfw_shmem_mbuf_req *pdata = NULL; - nsfw_shmem_mbuf_req *ptempdata = NULL; - - nsfw_shmem_msg_head *pack_head = NULL; - - nsfw_shmem_ack *pack_data = NULL; - mpool_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - i32 icount = 0; - i32 itindex = 0; - i32 iindex = 0; - i32 isegbase = 0; - i32 ieltnum = 0; - i32 ieltnum_max = - (NSFW_MGR_MSG_BODY_LEN - - sizeof (nsfw_shmem_msg_head)) / sizeof (nsfw_shmem_mbuf_req); - - mbpmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_GOTO (mbpmsg, lerr, "remote mbf createv msg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, lerr, "remote mbf createv rspmsg alloc"); - - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, mbpmsg); - - ptempdata = pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_mbuf_req); - - do - { - icount++; - ieltnum++; - - if (((icount % ieltnum_max) == 0) || (icount >= inum)) - { - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_MBUF_REQ_MSG, - ieltnum * sizeof (nsfw_shmem_mbuf_req)); - - /*fill msg data */ - itindex = icount - 1; - if (-1 == - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmbfname[itindex].stname.aname, pid)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - goto lerr; - } - NSFW_SHMEM_MBUF_DATA_INIT (ptempdata, (u16) itindex, - pmbfname[itindex].usnum, - pmbfname[itindex].uscash_size, - pmbfname[itindex].uspriv_size, - pmbfname[itindex].usdata_room, - pmbfname[itindex].enmptype, - pmbfname[itindex].isocket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (mbpmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("mbf createv mem req rsp fail] ret=%d", ucret); - goto lerr; - } - - /*interrupt msg head */ - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_MBUF_ACK_MSG, - ieltnum * sizeof (nsfw_shmem_ack), - lerr); - - pack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - - for (iindex = 0; iindex < ieltnum; iindex++) - { - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, - pack_data->cstate, - (isegbase + iindex), - (u16) pack_data->usseq, lerr); - phandle_array[isegbase + iindex] = - ADDR_SHTOL (pack_data->pbase_addr); - NSCOMM_LOGDBG ("mbf createv] seg=%d, handle=%p", - pack_data->usseq, hhandle); - pack_data++; - } - - isegbase = icount; - ieltnum = 0; - ptempdata = pdata; - } - else - { - itindex = icount - 1; - if (-1 == - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmbfname[itindex].stname.aname, pid)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - goto lerr; - } - NSFW_SHMEM_MBUF_DATA_INIT (ptempdata, (u16) itindex, - pmbfname[itindex].usnum, - pmbfname[itindex].uscash_size, - pmbfname[itindex].uspriv_size, - pmbfname[itindex].usdata_room, - pmbfname[itindex].enmptype, - pmbfname[itindex].isocket_id); - ptempdata++; - } - } - while (icount < inum); - - /*release memory */ - iretval = NSFW_MEM_OK; - goto release; - -lerr: - iretval = NSFW_MEM_ERR; -release: - NSFW_SHMEM_MSG_FREE (mbpmsg, prsp_msg); - return iretval; -} - -/* - *create a simpile pool - */ -mring_handle -nsfw_remote_shmem_mpcreate (const char *name, unsigned int n, - unsigned int elt_size, i32 socket_id, - nsfw_mpool_type entype) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - nsfw_shmem_msg_head *pdata_head = NULL; - nsfw_shmem_sppool_req *pdata = NULL; - nsfw_shmem_msg_head *mppack_head = NULL; - nsfw_shmem_ack *mppack_data = NULL; - mring_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_NULL (pmsg, "remote mbf mpcreate pmsg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, release, "remote mpcreate rspmsg alloc"); - - /*init msg head */ - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_SPPOOL_REQ_MSG, - sizeof (nsfw_shmem_sppool_req)); - - /*fill msg data */ - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_sppool_req); - iretval = STRCPY_S (pdata->aname, sizeof (pdata->aname), name); - if (EOK != iretval) - { - NSCOMM_LOGERR ("mp create copy name fail] ret=%d", iretval); - goto release; - } - - /*fill msg data */ - NSFW_SHMEM_MPOOL_DATA_INIT (pdata, 0, n, elt_size, entype, socket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("mp create rsp fail] ret=%d", ucret); - goto release; - } - - /*get msg head */ - mppack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (mppack_head, NSFW_SPPOOL_ACK_MSG, - sizeof (nsfw_shmem_ack), release); - - mppack_data = NSFW_SHMEM_GET_DATA (mppack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, mppack_data->cstate, 0, - mppack_data->usseq, release); - - hhandle = ADDR_SHTOL (mppack_data->pbase_addr); - NSCOMM_LOGDBG ("mpcreate] name=%s, handle=%p, seg=%d", name, hhandle, - mppack_data->usseq); -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return hhandle; -} - -/* - *create some simpile pools by send a msg - */ -i32 -nsfw_remote_shmem_mpcreatev (nsfw_mem_sppool * pmpinfo, - mring_handle * pringhandle_array, i32 inum, - pid_t pid) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - - /*msg head define */ - nsfw_shmem_msg_head *pdata_head = NULL; - - /*msg data define */ - nsfw_shmem_sppool_req *pdata = NULL; - nsfw_shmem_sppool_req *ptempdata = NULL; - - /*ack msg define */ - nsfw_shmem_msg_head *pack_head = NULL; - - nsfw_shmem_ack *pack_data = NULL; - mring_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - i32 icount = 0; - i32 itindex = 0; - i32 iindex = 0; - i32 isegbase = 0; - i32 ieltnum = 0; - /*the max members that a msg can take */ - i32 ieltnum_max = - (NSFW_MGR_MSG_BODY_LEN - - sizeof (nsfw_shmem_msg_head)) / sizeof (nsfw_shmem_sppool_req); - - /*alloc a msg */ - //pmsg = nsfw_mgr_msg_alloc(MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MASTER); - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_GOTO (pmsg, mperr, "remote mpcreatev pmsg alloc"); - - /*alloc rsp msg */ - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, mperr, "remote mpcreatev rspmsg alloc"); - - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - - ptempdata = pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_sppool_req); - - do - { - icount++; - ieltnum++; - - /*if the element num reach the bigest, or already send all, just deal */ - if (((icount % ieltnum_max) == 0) || (icount >= inum)) - { - /*init msg header */ - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_SPPOOL_REQ_MSG, - ieltnum * sizeof (nsfw_shmem_sppool_req)); - - /*fill the msg data */ - itindex = icount - 1; - - int retVal = - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmpinfo[itindex].stname.aname, pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S fail]ret=%d", retVal); - goto mperr; - } - NSFW_SHMEM_MPOOL_DATA_INIT (ptempdata, itindex, - pmpinfo[itindex].usnum, - pmpinfo[itindex].useltsize, - pmpinfo[itindex].enmptype, - pmpinfo[itindex].isocket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("mpcreatev create fail] ret=%u", ucret); - goto mperr; - } - - /*interrupt mgs head */ - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_SPPOOL_ACK_MSG, - ieltnum * sizeof (nsfw_shmem_ack), - mperr); - - pack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - - for (iindex = 0; iindex < ieltnum; iindex++) - { - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, - pack_data->cstate, - (isegbase + iindex), - (u16) pack_data->usseq, mperr); - pringhandle_array[isegbase + iindex] = - ADDR_SHTOL (pack_data->pbase_addr); - NSCOMM_LOGDBG ("mpcreatev] seg=%u, handle=%p", pack_data->usseq, - hhandle); - pack_data++; - } - - isegbase = icount; - ieltnum = 0; - ptempdata = pdata; - } - else - { - itindex = icount - 1; - int retVal = - SPRINTF_S (ptempdata->aname, sizeof (ptempdata->aname), "%s_%x", - pmpinfo[itindex].stname.aname, pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S fail]ret=%d", retVal); - goto mperr; - } - NSFW_SHMEM_MPOOL_DATA_INIT (ptempdata, itindex, - pmpinfo[itindex].usnum, - pmpinfo[itindex].useltsize, - pmpinfo[itindex].enmptype, - pmpinfo[itindex].isocket_id); - - ptempdata++; - } - } - while (icount < inum); - - /*release the memory */ - iretval = NSFW_MEM_OK; - goto release; - -mperr: - iretval = NSFW_MEM_ERR; -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return iretval; -} - -/* - *create a ring - */ -mring_handle -nsfw_remote_shmem_ringcreate (const char *name, unsigned int n, i32 socket_id, - nsfw_mpool_type entype) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - - /*msg head define */ - nsfw_shmem_msg_head *pdata_head = NULL; - - /*msg data define */ - nsfw_shmem_ring_req *pdata = NULL; - /*ack msg define */ - nsfw_shmem_msg_head *pack_head = NULL; - nsfw_shmem_ack *ppack_data = NULL; - mring_handle hhandle = NULL; - u8 ucret = TRUE; - i32 iretval = NSFW_MEM_OK; - - //pmsg = nsfw_mgr_msg_alloc(MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MASTER); - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_NULL (pmsg, "remote ringcreate pmsg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, release, - "remote ringcreate rspmsg alloc"); - - /*fill msg head */ - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_RING_REQ_MSG, - sizeof (nsfw_shmem_ring_req)); - - /*fill msg data */ - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_ring_req); - iretval = STRCPY_S (pdata->aname, sizeof (pdata->aname), name); - if (EOK != iretval) - { - NSCOMM_LOGERR ("ring create cpy name fail] ret=%d", iretval); - goto release; - } - - /*fill msg data */ - NSFW_SHMEM_MRING_DATA_INIT (pdata, 0, n, entype, socket_id); - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("ring create rsp fail] ret=%d", ucret); - goto release; - } - - /*interrupt mgs head */ - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_RING_ACK_MSG, - sizeof (nsfw_shmem_ack), release); - - ppack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, ppack_data->cstate, 0, - ppack_data->usseq, release); - - hhandle = ADDR_SHTOL (ppack_data->pbase_addr); - NSCOMM_LOGDBG ("ring create] name=%s, handle=%p, seg=%u", name, hhandle, - ppack_data->usseq); -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return hhandle; -} - -/* - *create a mem pool that the members are rings by send a msg - *ieltnum:the num of ring member - *iringnum:the num of ring in simple mem pool - *entype:the default the of ring - */ -i32 -nsfw_remote_shmem_ringcreatev (const char *name, i32 ieltnum, - mring_handle * pringhandle_array, i32 iringnum, - i32 socket_id, nsfw_mpool_type entype) -{ - unsigned int useltsize = 0; - mring_handle nhandle = NULL; - i32 icount = 0; - i32 n = 0; - uint64_t baseaddr = 0; - uint64_t endaddr = 0; - /*the num of ring member must be power of 2 */ - unsigned int usnum = common_mem_align32pow2 (ieltnum + 1); - - useltsize = - sizeof (struct nsfw_mem_ring) + usnum * sizeof (union RingData_U); - nhandle = - nsfw_remote_shmem_mpcreate (name, iringnum, useltsize, socket_id, - NSFW_MRING_SPSC); - NSFW_POINT_CHK_RET_ERR (nhandle, "remote ringcreatev msg alloc"); - - n = - nsfw_shmem_ring_sc_dequeuev (nhandle, (void **) pringhandle_array, - iringnum); - - if (n != iringnum) - { - NSCOMM_LOGERR ("ring dequeue fail] ringnum=%d, retnum=%d", iringnum, n); - return NSFW_MEM_ERR; - } - - nsfw_shmem_ring_baseaddr_query (&baseaddr, &endaddr); - - for (icount = 0; icount < iringnum; icount++) - { - nsfw_mem_ring_init (pringhandle_array[icount], usnum, (void *) baseaddr, - NSFW_SHMEM, entype); - } - - return NSFW_MEM_OK; -} - -/* - *look up a msg by send a msg - */ -void * -nsfw_remote_shmem_lookup (const i8 * name, nsfw_mem_struct_type entype) -{ - /*msg point define */ - nsfw_mgr_msg *pmsg = NULL; - nsfw_mgr_msg *prsp_msg = NULL; - void *addr = NULL; - /*msg head data define */ - nsfw_shmem_msg_head *pdata_head = NULL; - - /*msg data define */ - nsfw_shmem_lookup_req *pdata = NULL; - - /*ack msg define */ - nsfw_shmem_msg_head *pack_head = NULL; - nsfw_shmem_ack *lpack_data = NULL; - u8 ucret = TRUE; - - pmsg = nsfw_mgr_msg_alloc (MGR_MSG_MEM_ALLOC_REQ, NSFW_PROC_MAIN); - NSFW_POINT_CHK_RET_NULL (pmsg, "remote lookup pmsg alloc"); - - prsp_msg = nsfw_mgr_null_rspmsg_alloc (); - NSFW_POINT_CHK_RET_GOTO (prsp_msg, perr, "remote lookup rspmsg alloc"); - - /*msg head init */ - pdata_head = GET_USER_MSG (nsfw_shmem_msg_head, pmsg); - NSFW_SHMEM_MSG_HEAD_INIT (pdata_head, NSFW_MEM_LOOKUP_REQ_MSG, - sizeof (nsfw_shmem_lookup_req)); - - pdata = NSFW_SHMEM_GET_DATA (pdata_head, nsfw_shmem_lookup_req); - if (EOK != STRCPY_S (pdata->aname, sizeof (pdata->aname), name)) - { - NSCOMM_LOGERR ("STRCPY_S failed]name=%s", name); - } - pdata->usseq = 0; - pdata->ustype = entype; - pdata->ireserv = 0; - - ucret = nsfw_mgr_send_req_wait_rsp (pmsg, prsp_msg); - - if (FALSE == ucret) - { - NSCOMM_LOGERR ("mem lookup fail] ret=%u", ucret); - goto release; - } - - /*interrupt mgs head */ - pack_head = GET_USER_MSG (nsfw_shmem_msg_head, prsp_msg); - NSFW_SHMEM_MSGHEAD_CHK_GOTO (pack_head, NSFW_MEM_LOOKUP_ACK_MSG, - sizeof (nsfw_shmem_ack), perr); - - lpack_data = NSFW_SHMEM_GET_DATA (pack_head, nsfw_shmem_ack); - NSFW_SHMEM_ACKSTATE_CHK_GOTO (NSFW_MEM_ALLOC_SUCC, lpack_data->cstate, 0, - lpack_data->usseq, perr); - - addr = ADDR_SHTOL (lpack_data->pbase_addr); - NSCOMM_LOGDBG ("shmem lookup] name=%s, handle=%p, seg=%u", name, addr, - lpack_data->usseq); - goto release; -perr: - addr = NULL; - -release: - NSFW_SHMEM_MSG_FREE (pmsg, prsp_msg); - return addr; -} diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.h b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.h deleted file mode 100644 index 60c4115..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_rshmem_mng.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* -* 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 _NSFW_RSHMEM_MNG_H -#define _NSFW_RSHMEM_MNG_H - -mzone_handle nsfw_memzone_remote_reserv (const i8 * name, size_t mlen, - i32 socket_id); -i32 nsfw_memzone_remote_reserv_v (nsfw_mem_zone * pmeminfo, - mzone_handle * paddr_array, i32 inum, - pid_t pid); -i32 nsfw_remote_free (const i8 * name, nsfw_mem_struct_type entype); -mpool_handle nsfw_remote_shmem_mbf_create (const i8 * name, unsigned int n, - unsigned cache_size, - unsigned priv_size, - unsigned data_room_size, - i32 socket_id, - nsfw_mpool_type entype); -i32 nsfw_remote_shmem_mbf_createv (nsfw_mem_mbfpool * pmbfname, - mpool_handle * phandle_array, i32 inum, - pid_t pid); -mring_handle nsfw_remote_shmem_mpcreate (const char *name, unsigned int n, - unsigned int elt_size, i32 socket_id, - nsfw_mpool_type entype); -i32 nsfw_remote_shmem_mpcreatev (nsfw_mem_sppool * pmpinfo, - mring_handle * pringhandle_array, i32 inum, - pid_t pid); -mring_handle nsfw_remote_shmem_ringcreate (const char *name, unsigned int n, - i32 socket_id, - nsfw_mpool_type entype); -i32 nsfw_remote_shmem_ringcreatev (const char *name, i32 ieltnum, - mring_handle * pringhandle_array, - i32 iringnum, i32 socket_id, - nsfw_mpool_type entype); - -void *nsfw_remote_shmem_lookup (const i8 * name, nsfw_mem_struct_type entype); - -#endif diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.c b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.c deleted file mode 100644 index 2e9c969..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.c +++ /dev/null @@ -1,47 +0,0 @@ -/* -* -* 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_mem_desc.h" -#include "nsfw_shmem_mng.h" -#include "nsfw_shmem_mdesc.h" - -/*the inferaces accessing memory*/ -nsfw_mem_ops g_shmem_ops = { - nsfw_shmem_init, - nsfw_shmem_destroy, - nsfw_shmem_create, - nsfw_shmem_createv, - nsfw_shmem_lookup, - nsfw_shmem_release, - nsfw_shmem_mbfmpcreate, - nsfw_shmem_mbfmpcreatev, - nsfw_shmem_mbfalloc, - nsfw_shmem_mbffree, - nsfw_shmem_mbfmplookup, - nsfw_shmem_mbfmprelease, - nsfw_shmem_spcreate, - nsfw_shmem_spcreatev, - nswf_shmem_sp_ringcreate, - nsfw_shmem_sprelease, - nsfw_shmem_sp_lookup, - nsfw_shmem_ringcreate, - nsfw_shmem_ring_lookup, - nsfw_shmem_ringrelease, - nsfw_shmem_static, - nsfw_shmem_mbuf_recycle, - nsfw_shmem_sp_iterator, - nsfw_shmem_mbuf_iterator -}; diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.h b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.h deleted file mode 100644 index afd9e29..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mdesc.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -* -* 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 _NSFW_SHMEM_MDESC_H_ -#define _NSFW_SHMEM_MDESC_H_ - -extern nsfw_mem_ops g_shmem_ops; - -#endif diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.c b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.c deleted file mode 100644 index 77ffd19..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.c +++ /dev/null @@ -1,814 +0,0 @@ -/* -* -* 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 "nstack_log.h" -#include "nsfw_mem_desc.h" -#include "nsfw_ring_fun.h" -#include "nsfw_shmem_ring.h" -#include "nsfw_shmem_mng.h" -#include "common_mem_mempool.h" -#include "common_mem_memzone.h" -#include "common_mem_buf.h" -#include "common_mem_mbuf.h" -#include "nsfw_rshmem_mng.h" -#include "common_mem_api.h" -#include "common_sys_config.h" -#include "nsfw_maintain_api.h" -#include "common_pal_bitwide_adjust.h" - -#include "common_mem_pal.h" - -#include "common_func.h" - -#define NSFW_SHMEM_PID (get_sys_pid()) -#define NSFW_SHMEM_FLAG (g_shmem_localdata->enflag) - -/* app_mode 1: simple stack with APP*/ -extern u8 app_mode; -u8 app_mode = 0; - -nsfw_mem_localdata *g_shmem_localdata = NULL; - -/*check g_mem_localdata*/ -#define NSFW_INIT_CHK_RET() \ - if (!g_shmem_localdata) \ - { \ - return NSFW_MEM_ERR; \ - } - -#define NSFW_INIT_CHK_RET_NULL() \ - if (!g_shmem_localdata) \ - { \ - return NULL; \ - } - -/* - *share memory mng module init - * - */ -i32 -nsfw_shmem_init (nsfw_mem_para * para) -{ - common_mem_pal_module_info rteinfo = { 0 }; - i32 iret = NSFW_MEM_ERR; - int flag = 0; - if (!para) - { - return NSFW_MEM_ERR; - } - - NSCOMM_LOGINF ("nsfw shmem init begin"); - - LCORE_MASK_SET (rteinfo.ilcoremask, 1); - rteinfo.ucproctype = DMM_PROC_T_SECONDARY; - iret = common_pal_module_init (para, &rteinfo, app_mode); - - if (DMM_MBUF_RET_OK != iret) - { - NSCOMM_LOGERR ("rte init fail] ret=0x%x", iret); - return NSFW_MEM_ERR; - } - - flag = dmm_pal_addr_align (); - if ((0 == flag) && (NSFW_PROC_MAIN == para->enflag)) - { - dmm_addr_print (); - NSCOMM_LOGERR - ("rte init addr is not the same with primary] nstackmain flag=%d", - flag); - return NSFW_MEM_ERR; - } - - g_shmem_localdata = - (nsfw_mem_localdata *) malloc (sizeof (nsfw_mem_localdata)); - - if (NULL == g_shmem_localdata) - { - NSCOMM_LOGERR ("g_shmem_localdata malloc fail"); - return NSFW_MEM_ERR; - } - - iret = - MEMSET_S (g_shmem_localdata, sizeof (nsfw_mem_localdata), 0, - sizeof (nsfw_mem_localdata)); - if (EOK != iret) - { - NSCOMM_LOGERR ("memset fail] g_shmem_localdata=%p ", g_shmem_localdata); - free (g_shmem_localdata); - g_shmem_localdata = NULL; - return NSFW_MEM_ERR; - } - - g_shmem_localdata->enflag = para->enflag; - - NSCOMM_LOGINF ("nsfw shmem init end] enflag=%d", para->enflag); - return NSFW_MEM_OK; - -} - -/* - *module destroy - */ -void -nsfw_shmem_destroy (void) -{ - if (g_shmem_localdata) - { - free (g_shmem_localdata); - g_shmem_localdata = NULL; - } - - return; -} - -/* - * create a shared memory - * nsfw_mem_zone::stname memory name - * nsfw_mem_zone::isize - */ -mzone_handle -nsfw_shmem_create (nsfw_mem_zone * pinfo) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET_NULL ()if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return common_memzone_data_reserve_name (pinfo->stname.aname, - pinfo->length, - pinfo->isocket_id); - } - else - { - /*app must less than NSFW_MEM_APPNAME_LENGTH */ - NSFW_NAME_LENCHECK_RET_NULL (pinfo->stname.aname, "shmem create") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pinfo->stname.aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - return NULL; - } - } - - return nsfw_memzone_remote_reserv ((char *) &aname[0], pinfo->length, - SOCKET_ID_ANY); -} - -/* - *create some memory - *inum must be equal iarray_num - */ -i32 -nsfw_shmem_createv (nsfw_mem_zone * pmeminfo, i32 inum, - mzone_handle * paddr_array, i32 iarray_num) -{ - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_memzone_remote_reserv_v (pmeminfo, paddr_array, iarray_num, - 0); - } - else - { - return nsfw_memzone_remote_reserv_v (pmeminfo, paddr_array, iarray_num, - NSFW_SHMEM_PID); - } - return NSFW_MEM_ERR; -} - -mzone_handle -nsfw_shmem_lookup (nsfw_mem_name * pname) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return common_memzone_data_lookup_name (pname->aname); - } - - if ((NSFW_PROC_NULL == pname->enowner) - || (NSFW_PROC_MAIN == pname->enowner)) - { - int retVal = - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s", pname->aname); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed"); - return NULL; - } - } - else - { - /*app must less than NSFW_MEM_APPNAME_LENGTH */ - NSFW_NAME_LENCHECK_RET_NULL (pname->aname, "shmem lookup") - int retVal = - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", pname->aname, - NSFW_SHMEM_PID); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed"); - return NULL; - } - } - - return nsfw_remote_shmem_lookup (aname, NSFW_MEM_MZONE); -} - -i32 -nsfw_shmem_release (nsfw_mem_name * pname) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - const struct common_mem_memzone *pmzone = NULL; - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - pmzone = common_mem_memzone_lookup (pname->aname); - - if (pmzone) - { - common_mem_memzone_free (pmzone); - } - return NSFW_MEM_OK; - } - else - { - NSFW_NAME_LENCHECK_RET (pname->aname, "shmem free") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pname->aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed"); - return NSFW_MEM_ERR; - } - } - - return nsfw_remote_free (aname, NSFW_MEM_MZONE); -} - -mpool_handle -nsfw_shmem_mbfmpcreate (nsfw_mem_mbfpool * pbufinfo) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return common_mem_pktmbuf_pool_create (pbufinfo->stname.aname, - pbufinfo->usnum, - pbufinfo->uscash_size, - pbufinfo->uspriv_size, - pbufinfo->usdata_room, - pbufinfo->isocket_id); - } - else - { - /*app must less than NSFW_MEM_APPNAME_LENGTH */ - NSFW_NAME_LENCHECK_RET_NULL (pbufinfo->stname.aname, "mbufpool create") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pbufinfo->stname.aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_mbf_create (aname, pbufinfo->usnum, - pbufinfo->uscash_size, - pbufinfo->uspriv_size, - pbufinfo->usdata_room, SOCKET_ID_ANY, - pbufinfo->enmptype); -} - -/* - *create some mbuf pools - */ -i32 -nsfw_shmem_mbfmpcreatev (nsfw_mem_mbfpool * pmbfname, i32 inum, - mpool_handle * phandle_array, i32 iarray_num) -{ - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_remote_shmem_mbf_createv (pmbfname, phandle_array, - iarray_num, 0); - } - else - { - return nsfw_remote_shmem_mbf_createv (pmbfname, phandle_array, - iarray_num, NSFW_SHMEM_PID); - } - - return NSFW_MEM_ERR; -} - -mbuf_handle -nsfw_shmem_mbfalloc (mpool_handle mhandle) -{ - return (mbuf_handle) common_mem_pktmbuf_alloc ((struct common_mem_mempool *) - mhandle); -} - -i32 -nsfw_shmem_mbffree (mbuf_handle mhandle) -{ - common_mem_pktmbuf_free ((struct common_mem_mbuf *) mhandle); - return NSFW_MEM_OK; -} - -i32 -nsfw_shmem_mbfmprelease (nsfw_mem_name * pname) -{ - return NSFW_MEM_OK; -} - -mpool_handle -nsfw_shmem_mbfmplookup (nsfw_mem_name * pmbfname) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return common_mem_mempool_lookup (pmbfname->aname); - } - - if ((NSFW_PROC_NULL == pmbfname->enowner) - || (NSFW_PROC_MAIN == pmbfname->enowner)) - { - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s", - pmbfname->aname)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - else - { - /*app must less than NSFW_MEM_APPNAME_LENGTH */ - NSFW_NAME_LENCHECK_RET_NULL (pmbfname->aname, "shmem lookup") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pmbfname->aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_lookup (aname, NSFW_MEM_MBUF); -} - -mring_handle -nsfw_shmem_spcreate (nsfw_mem_sppool * pmpinfo) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_shmem_pool_create (pmpinfo->stname.aname, pmpinfo->usnum, - pmpinfo->useltsize, pmpinfo->isocket_id, - pmpinfo->enmptype); - } - else - { - NSFW_NAME_LENCHECK_RET_NULL (pmpinfo->stname.aname, "mpool create") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pmpinfo->stname.aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_mpcreate (aname, pmpinfo->usnum, - pmpinfo->useltsize, SOCKET_ID_ANY, - pmpinfo->enmptype); -} - -i32 -nsfw_shmem_spcreatev (nsfw_mem_sppool * pmpinfo, i32 inum, - mring_handle * pringhandle_array, i32 iarray_num) -{ - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_remote_shmem_mpcreatev (pmpinfo, pringhandle_array, inum, - 0); - } - else - { - return nsfw_remote_shmem_mpcreatev (pmpinfo, pringhandle_array, inum, - NSFW_SHMEM_PID); - } - return NSFW_MEM_ERR; -} - -i32 -nsfw_lshmem_ringcreatev (const char *name, i32 ieltnum, - mring_handle * pringhandle_array, i32 iringnum, - i32 socket_id, nsfw_mpool_type entype) -{ - i32 useltsize = 0; - mring_handle nhandle = NULL; - i32 icount = 0; - i32 n = 0; - uint64_t baseaddr = 0; - uint64_t endaddr = 0; - i32 usnum = common_mem_align32pow2 (ieltnum + 1); - - useltsize = - sizeof (struct nsfw_mem_ring) + usnum * sizeof (union RingData_U); - nhandle = - nsfw_shmem_pool_create (name, iringnum, useltsize, socket_id, - NSFW_MRING_SPSC); - if (NULL == (nhandle)) - { - return NSFW_MEM_ERR; - } - - n = - nsfw_shmem_ring_sc_dequeuev (nhandle, (void **) pringhandle_array, - iringnum); - - if (n != iringnum) - { - NSCOMM_LOGERR - ("ring dequeuev failed] ring=%p, dequeue num=%d, expect num=%d", - nhandle, n, iringnum); - return NSFW_MEM_ERR; - } - - nsfw_shmem_ring_baseaddr_query (&baseaddr, &endaddr); - - for (icount = 0; icount < iringnum; icount++) - { - nsfw_mem_ring_init (pringhandle_array[icount], usnum, (void *) baseaddr, - NSFW_SHMEM, entype); - } - - return NSFW_MEM_OK; -} - -i32 -nswf_shmem_sp_ringcreate (nsfw_mem_mring * prpoolinfo, - mring_handle * pringhandle_array, i32 iringnum) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_lshmem_ringcreatev (prpoolinfo->stname.aname, - prpoolinfo->usnum, pringhandle_array, - iringnum, SOCKET_ID_ANY, - prpoolinfo->enmptype); - } - else - { - NSFW_NAME_LENCHECK_RET (prpoolinfo->stname.aname, "ring pool") - int retVal = SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - prpoolinfo->stname.aname, NSFW_SHMEM_PID); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_ringcreatev (aname, prpoolinfo->usnum, - pringhandle_array, iringnum, - SOCKET_ID_ANY, prpoolinfo->enmptype); -} - -i32 -nsfw_shmem_sprelease (nsfw_mem_name * pname) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - void *mz_mem = NULL; - struct nsfw_mem_ring *ring_ptr = NULL; - NSFW_INIT_CHK_RET (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - mz_mem = common_memzone_data_lookup_name (pname->aname); - - if (mz_mem) - { - ring_ptr = - (struct nsfw_mem_ring *) ((char *) mz_mem + - sizeof (struct nsfw_shmem_ring_head)); - nsfw_shmem_pool_free (ring_ptr); - } - return NSFW_MEM_OK; - } - else - { - NSFW_NAME_LENCHECK_RET (pname->aname, "shmem free") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pname->aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_free (aname, NSFW_MEM_SPOOL); -} - -mring_handle -nsfw_shmem_sp_lookup (nsfw_mem_name * pname) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - void *mz_mem = NULL; - struct nsfw_mem_ring *ring_ptr = NULL; - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - mz_mem = common_memzone_data_lookup_name (pname->aname); - - if (mz_mem) - { - ring_ptr = - (struct nsfw_mem_ring *) ((char *) mz_mem + - sizeof (struct nsfw_shmem_ring_head)); - return ring_ptr; - } - return mz_mem; - } - - if ((NSFW_PROC_NULL == pname->enowner) - || (NSFW_PROC_MAIN == pname->enowner)) - { - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s", pname->aname)) - { - NSCOMM_LOGERR ("SPRINTF_S fails]"); - } - } - else - { - /*app's name can not over NSFW_MEM_APPNAME_LENGTH */ - NSFW_NAME_LENCHECK_RET_NULL (pname->aname, "shmem lookup") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pname->aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_lookup (aname, NSFW_MEM_SPOOL); -} - -mring_handle -nsfw_shmem_ringcreate (nsfw_mem_mring * pringinfo) -{ - i8 aname[COMMON_MEM_MEMPOOL_NAMESIZE] = { 0 }; - - NSFW_INIT_CHK_RET_NULL (); - - if (NSFW_PROC_MAIN == NSFW_SHMEM_FLAG) - { - return nsfw_shmem_ring_create (pringinfo->stname.aname, - pringinfo->usnum, pringinfo->isocket_id, - pringinfo->enmptype); - } - else - { - NSFW_NAME_LENCHECK_RET_NULL (pringinfo->stname.aname, "ring create") - if (-1 == - SPRINTF_S (aname, COMMON_MEM_MEMPOOL_NAMESIZE, "%s_%x", - pringinfo->stname.aname, NSFW_SHMEM_PID)) - { - NSCOMM_LOGERR ("SPRINTF_S failed]"); - } - } - - return nsfw_remote_shmem_ringcreate (aname, pringinfo->usnum, SOCKET_ID_ANY, - pringinfo->enmptype); -} - -mring_handle -nsfw_shmem_ring_lookup (nsfw_mem_name * pname) -{ - return nsfw_shmem_lookup (pname); -} - -i32 -nsfw_shmem_ringrelease (nsfw_mem_name * pname) -{ - return nsfw_shmem_release (pname); -} - -size_t -nsfw_shmem_mbufpool_statics (mpool_handle mbufpool) -{ - struct common_mem_mempool *mp = (struct common_mem_mempool *) mbufpool; - return (size_t) mp->size * (mp->header_size + mp->elt_size + - mp->trailer_size) + - (size_t) mp->private_data_size + - (size_t) - common_mem_ring_get_memsize (common_mem_align32pow2 (mp->size + 1)); -} - -size_t -nsfw_shmem_sppool_statics (mring_handle sppool) -{ - struct nsfw_shmem_ring_head *temp = NULL; - size_t lent = 0; - temp = - (struct nsfw_shmem_ring_head *) ((char *) sppool - - sizeof (struct nsfw_shmem_ring_head)); - - while (temp) - { - lent += temp->mem_zone->len; - temp = temp->next; - } - - return lent; -} - -size_t -nsfw_shmem_ring_statics (mring_handle handle) -{ - struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) handle; - return ring->size * sizeof (union RingData_U) + - sizeof (struct nsfw_mem_ring); -} - -ssize_t -nsfw_shmem_static (void *handle, nsfw_mem_struct_type type) -{ - switch (type) - { - case NSFW_MEM_MBUF: - return nsfw_shmem_mbufpool_statics (handle); - case NSFW_MEM_SPOOL: - return nsfw_shmem_sppool_statics (handle); - case NSFW_MEM_RING: - return nsfw_shmem_ring_statics (handle); - default: - break; - } - return -1; -} - -i32 -nsfw_shmem_mbuf_recycle (mpool_handle handle) -{ - return NSFW_MEM_OK; -} - -/***************************************************************************** -* Prototype : nsfw_shmem_sp_iterator -* Description : sp pool iterator -* Input : mpool_handle handle -* u32 start -* u32 end -* nsfw_mem_item_fun fun -* void *argv -* Output : None -* Return Value : i32 -* Calls : -* Called By : -*****************************************************************************/ -i32 -nsfw_shmem_sp_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv) -{ - struct nsfw_mem_ring *perfring_ptr = (struct nsfw_mem_ring *) handle; - if (NULL == perfring_ptr || NULL == fun) - { - return 0; - } - - if (0 == perfring_ptr->eltsize) - { - return 0; - } - - int num = perfring_ptr->size; - if (start >= (u32) num || end <= start) - { - return 0; - } - - struct nsfw_shmem_ring_head *ring_head = - (struct nsfw_shmem_ring_head *) ((char *) handle - - sizeof (struct nsfw_shmem_ring_head)); - void *mz = - (void *) ((char *) perfring_ptr + sizeof (struct nsfw_mem_ring) + - num * sizeof (union RingData_U)); - - if (ring_head->mem_zone->len < - sizeof (struct nsfw_shmem_ring_head) + sizeof (struct nsfw_mem_ring) + - num * sizeof (union RingData_U)) - { - return 0; - } - - u32 mz_len = - ring_head->mem_zone->len - sizeof (struct nsfw_shmem_ring_head) - - sizeof (struct nsfw_mem_ring) - num * sizeof (union RingData_U); - - u32 start_idx = 0; - u32 elm_num = 0; - elm_num = mz_len / perfring_ptr->eltsize; - while (start > start_idx + elm_num) - { - if (NULL == ring_head->next || NULL == ring_head->next->mem_zone - || 0 == elm_num) - { - return 0; - } - - ring_head = - (struct nsfw_shmem_ring_head *) ring_head->next->mem_zone->addr_64; - mz_len = - ring_head->mem_zone->len - sizeof (struct nsfw_shmem_ring_head); - - elm_num = mz_len / perfring_ptr->eltsize; - mz = - (void *) ((char *) ring_head + sizeof (struct nsfw_shmem_ring_head)); - start_idx += elm_num; - } - - u32 cur_idx = start - start_idx; - char *cur_elm = NULL; - int proc_count = 0; - while (cur_idx + start_idx < end && cur_idx + start_idx < (u32) num) - { - if (cur_idx >= elm_num) - { - if (NULL == ring_head->next || NULL == ring_head->next->mem_zone - || 0 == elm_num) - { - break; - } - - ring_head = - (struct nsfw_shmem_ring_head *) ring_head->next-> - mem_zone->addr_64; - mz_len = - ring_head->mem_zone->len - sizeof (struct nsfw_shmem_ring_head); - - elm_num = mz_len / perfring_ptr->eltsize; - mz = - (void *) ((char *) ring_head + - sizeof (struct nsfw_shmem_ring_head)); - start_idx += elm_num; - - cur_idx = 0; - cur_elm = NULL; - continue; - } - - if (NULL == cur_elm) - { - cur_elm = ((char *) mz + cur_idx * perfring_ptr->eltsize); - } - else - { - cur_elm += perfring_ptr->eltsize; - } - - cur_idx++; - proc_count++; - (void) fun (cur_elm, argv); - } - - return proc_count; -} - -i32 -nsfw_shmem_mbuf_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv) -{ - return dmm_pktmbuf_pool_iterator ((struct common_mem_mempool *) handle, - start, end, (dmm_mbuf_item_fun) fun, - argv); -} diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.h b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.h deleted file mode 100644 index d489525..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_mng.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -* -* 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 _NSFW_SHMEM_MNG_H -#define _NSFW_SHMEM_MNG_H - -/* - * mem mgr module init - * para:point to nstack_fwmem_para - */ -i32 nsfw_shmem_init (nsfw_mem_para * para); - -/* - * mem mgr module destory - * - */ -void nsfw_shmem_destroy (void); - -/* - * create a block memory with name - * fw_mem_zone::stname name of memory - * fw_mem_zone::isize memory size - */ -mzone_handle nsfw_shmem_create (nsfw_mem_zone * pinfo); - -/* - *create some blocks memory - */ -i32 nsfw_shmem_createv (nsfw_mem_zone * pmeminfo, i32 inum, - mzone_handle * paddr_array, i32 iarray_num); - -/* - *lookup a memory - */ -mzone_handle nsfw_shmem_lookup (nsfw_mem_name * pname); - -/*release the memory*/ -i32 nsfw_shmem_release (nsfw_mem_name * pname); - -/* - *create mbuf pool - */ -mpool_handle nsfw_shmem_mbfmpcreate (nsfw_mem_mbfpool * pbufinfo); - -/* - *create some mbuf pool - */ -i32 nsfw_shmem_mbfmpcreatev (nsfw_mem_mbfpool * pmbfname, i32 inum, - mpool_handle * phandle_array, i32 iarray_num); - -/* - *alloc a mbuf from mbuf pool - */ -mbuf_handle nsfw_shmem_mbfalloc (mpool_handle mhandle); - -/* - *release a mbuf pool - */ -i32 nsfw_shmem_mbffree (mbuf_handle mhandle); - -/* - *put mbuf back to mbuf pool - */ -i32 nsfw_shmem_mbfmprelease (nsfw_mem_name * pname); - -/*look up mbuf mpool*/ -mpool_handle nsfw_shmem_mbfmplookup (nsfw_mem_name * pmbfname); - -/* - *create simple pool - */ -mring_handle nsfw_shmem_spcreate (nsfw_mem_sppool * pmpinfo); - -/* - *create some simple pools - */ -i32 nsfw_shmem_spcreatev (nsfw_mem_sppool * pmpinfo, i32 inum, - mring_handle * pringhandle_array, i32 iarray_num); - -/* - *create a simple pool that members are rings - */ -i32 nswf_shmem_sp_ringcreate (nsfw_mem_mring * prpoolinfo, - mring_handle * pringhandle_array, i32 iringnum); - -/* - *release a simple pool - */ -i32 nsfw_shmem_sprelease (nsfw_mem_name * pname); - -/* - *look up a simple pool - */ -mring_handle nsfw_shmem_sp_lookup (nsfw_mem_name * pname); - -/* - *create a ring with name - */ -mring_handle nsfw_shmem_ringcreate (nsfw_mem_mring * pringinfo); - -/* - *look up a ring with name - */ -mring_handle nsfw_shmem_ring_lookup (nsfw_mem_name * pname); - -/* - *release ring - */ -i32 nsfw_shmem_ringrelease (nsfw_mem_name * pname); - -ssize_t nsfw_shmem_static (void *handle, nsfw_mem_struct_type type); - -i32 nsfw_shmem_mbuf_recycle (mpool_handle handle); - -i32 nsfw_shmem_sp_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); -i32 nsfw_shmem_mbuf_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); - -#endif diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.c b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.c deleted file mode 100644 index c42c840..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.c +++ /dev/null @@ -1,839 +0,0 @@ -/* -* -* 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 <common_sys_config.h> - -#include "common_mem_pal.h" -#include "common_mem_pal_memconfig.h" -#include "nstack_securec.h" -#include "nsfw_shmem_ring.h" -#include "nsfw_ring_fun.h" -#include "common_mem_buf.h" -#include "common_func.h" - -void -nsfw_shmem_ring_baseaddr_query (uint64_t * rte_lowest_addr, - uint64_t * rte_highest_addr) -{ - struct common_mem_mem_config *pMemCfg = - common_mem_pal_get_configuration ()->mem_config; - struct common_mem_memseg *PMemSegArry = pMemCfg->memseg; - - *rte_lowest_addr = PMemSegArry[0].addr_64; - *rte_highest_addr = PMemSegArry[0].addr_64 + PMemSegArry[0].len; - - int s = 1; - - while (s < COMMON_MEM_MAX_MEMSEG && PMemSegArry[s].len > 0) - { - if (*rte_lowest_addr > PMemSegArry[s].addr_64) - { - *rte_lowest_addr = PMemSegArry[s].addr_64; - } - - if (*rte_highest_addr < PMemSegArry[s].addr_64 + PMemSegArry[s].len) - { - *rte_highest_addr = PMemSegArry[s].addr_64 + PMemSegArry[s].len; - } - - s++; - } - -} - -static unsigned -nsfw_shmem_pool_node_alloc (struct nsfw_mem_ring *perfring_ptr, - unsigned alloc_index, unsigned max_index, - void *mz, size_t mz_len, unsigned elt_size) -{ - size_t alloc_size = 0; - unsigned offset_idx = 0; - NSTCP_LOGINF ("mz(%p), mz_len = 0x%x", mz, mz_len); - - while (alloc_size + elt_size <= mz_len) - { - perfring_ptr->ring[alloc_index + offset_idx].data_s.ver = - alloc_index + offset_idx; - perfring_ptr->ring[alloc_index + offset_idx].data_s.val = - ADDR_LTOSH_EXT (mz) - ((uint64_t) perfring_ptr->Addrbase); - mz = (char *) mz + elt_size; - alloc_size += elt_size; - offset_idx++; - - if (alloc_index + offset_idx == max_index) - { - break; - } - } - - return offset_idx; -} - -void -nsfw_shmem_pool_free (struct nsfw_mem_ring *perfring_ptr) -{ - struct nsfw_shmem_ring_head *ptemp; - - if (NULL == perfring_ptr) - { - return; - } - - struct nsfw_shmem_ring_head *pnode = - (struct nsfw_shmem_ring_head *) ((char *) perfring_ptr - - sizeof (struct nsfw_shmem_ring_head)); - - while (pnode) - { - // phead is involved in phead->mem_zone - ptemp = pnode->next; - common_mem_memzone_free (pnode->mem_zone); - pnode = ptemp; - } -} - -struct nsfw_mem_ring * -nsfw_shmem_pool_create (const char *name, unsigned int n, - unsigned int elt_size, int socket_id, - unsigned char flag) -{ - struct nsfw_mem_ring *perfring_ptr = NULL; - struct common_mem_memzone *mz_mem; - void *mz = NULL; - - /*get pool size, pool size must pow of 2 */ - unsigned int num = common_mem_align32pow2 (n + 1); - - struct nsfw_shmem_ring_head *pcur = NULL; - /*calculate the empty rte_perf_ring Size */ - size_t len = - sizeof (struct nsfw_shmem_ring_head) + sizeof (struct nsfw_mem_ring) + - (size_t) num * sizeof (union RingData_U) + (size_t) num * elt_size; - size_t alloc_len = len; - unsigned int alloc_num = 0; - unsigned int alloc_index = 0; - - size_t mz_len = 0; - - unsigned int mz_index = 1; - char mz_name[128] = { 0 }; - int retVal; - /*we'd better use `strlen(src)` or `sizeof(dst)` to explain copying length of src string. - it's meaningless using `sizeof(dst) - 1` to reserve 1 byte for '\0'. - if copying length equals to or bigger than dst length, just let STRNCPY_S() returns failure. */ - retVal = STRNCPY_S (mz_name, sizeof (mz_name), name, sizeof (mz_name)); - - if (EOK != retVal) - { - NSTCP_LOGERR ("STRNCPY_S failed]ret=%d", retVal); - return NULL; - } - - mz_mem = common_memzone_data_lookup_name (name); - NSTCP_LOGINF ("memzone data look up] n=%u,num=%u,len=%zu", n, num, len); - - if (mz_mem) - { - perfring_ptr = - (struct nsfw_mem_ring *) ((char *) mz_mem + - sizeof (struct nsfw_shmem_ring_head)); - return perfring_ptr; - } - - while (alloc_len > 0) - { - if (NULL != perfring_ptr) - { - retVal = - SPRINTF_S (mz_name, sizeof (mz_name), "%s_%03d", name, mz_index); - - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - nsfw_shmem_pool_free (perfring_ptr); - return NULL; - } - } - - mz_mem = - (struct common_mem_memzone *) common_mem_memzone_reserve (mz_name, - alloc_len, - socket_id, - 0); - - if (mz_mem == NULL) - { - mz_mem = - (struct common_mem_memzone *) common_mem_memzone_reserve (mz_name, - 0, - socket_id, - 0); - } - - if (mz_mem == NULL) - { - nsfw_shmem_pool_free (perfring_ptr); - return NULL; - } - - if (NULL == perfring_ptr - && (mz_mem->len < - sizeof (struct nsfw_shmem_ring_head) + - sizeof (struct nsfw_mem_ring) + - num * sizeof (union RingData_U))) - { - common_mem_memzone_free (mz_mem); - return NULL; - } - - if (NULL == perfring_ptr) - { - pcur = (struct nsfw_shmem_ring_head *) ADDR_SHTOL (mz_mem->addr_64); - pcur->mem_zone = mz_mem; - pcur->next = NULL; - - perfring_ptr = - (struct nsfw_mem_ring *) ((char *) pcur + - sizeof (struct nsfw_shmem_ring_head)); - - mz = - (void *) ((char *) perfring_ptr + sizeof (struct nsfw_mem_ring) + - num * sizeof (union RingData_U)); - mz_len = - mz_mem->len - sizeof (struct nsfw_shmem_ring_head) - - sizeof (struct nsfw_mem_ring) - num * sizeof (union RingData_U); - - uint64_t rte_base_addr; - uint64_t rte_highest_addr; - nsfw_shmem_ring_baseaddr_query (&rte_base_addr, &rte_highest_addr); - nsfw_mem_pool_head_init (perfring_ptr, num, elt_size, - (void *) rte_base_addr, NSFW_SHMEM, - (nsfw_mpool_type) flag); - } - else - { - if (pcur) - { - pcur->next = - (struct nsfw_shmem_ring_head *) ADDR_SHTOL (mz_mem->addr_64); - pcur = pcur->next; - pcur->mem_zone = mz_mem; - pcur->next = NULL; - - if (mz_mem->len < sizeof (struct nsfw_shmem_ring_head)) - { - NSCOMM_LOGERR ("mz_len error %d", mz_mem->len); - nsfw_shmem_pool_free (perfring_ptr); - return NULL; - } - - mz = - (void *) ((char *) pcur + - sizeof (struct nsfw_shmem_ring_head)); - mz_len = mz_mem->len - sizeof (struct nsfw_shmem_ring_head); - } - } - - alloc_num = - nsfw_shmem_pool_node_alloc (perfring_ptr, alloc_index, num, mz, - mz_len, elt_size); - alloc_index += alloc_num; - - if (alloc_index >= num) - { - break; - } - - // second time allocate should not contained all ring head - alloc_len = - (size_t) (num - alloc_index) * elt_size + - sizeof (struct nsfw_shmem_ring_head); - mz_index++; - } - - return perfring_ptr; -} - -/*ring create*/ -struct nsfw_mem_ring * -nsfw_shmem_ring_create (const char *name, unsigned int n, int socket_id, - unsigned char flag) -{ - struct nsfw_mem_ring *perfring_ptr; - struct common_mem_memzone *mz; - uint64_t rte_base_addr; - uint64_t rte_highest_addr; - - unsigned int num = common_mem_align32pow2 (n); - - mz = - (struct common_mem_memzone *) common_mem_memzone_reserve (name, - sizeof (struct - nsfw_mem_ring) - + - num * - sizeof (union - RingData_U), - socket_id, 0); - - if (mz == NULL) - { - return NULL; - } - - perfring_ptr = mz->addr; - - nsfw_shmem_ring_baseaddr_query (&rte_base_addr, &rte_highest_addr); - nsfw_mem_ring_init (perfring_ptr, num, (void *) rte_base_addr, NSFW_SHMEM, - flag); - - return perfring_ptr; -} - -/* -this is a multi thread/process enqueue function, please pay attention to the bellow point -1. while Enqueue corrupt, we may lose one element; because no one to add the Head -*/ -int -nsfw_shmem_ring_mp_enqueue (struct nsfw_mem_ring *ring, void *box) -{ - union RingData_U expectPostVal; - union RingData_U curVal; - unsigned int tmpHead; - unsigned int tmpTail; - unsigned int CurHead = ring->prod.head; - unsigned int mask = ring->mask; - unsigned int size = ring->size; - void *prmBox = NULL; - - prmBox = (void *) ADDR_LTOSH_EXT (box); - - /*do box range check */ - if ((char *) prmBox <= (char *) ring->Addrbase - || (char *) prmBox > (char *) ring->Addrbase + PERFRING_ADDR_RANGE) - { - /*invalid addr of box, can't put in rte_perf_ring, maybe should set a errno here */ - return -1; - } - - do - { - /* - if the ring is Full return directly; this not a exact check, cause we made tail++ after dequeue success. - the thing we could make sure is ring[ring->Tail&mask] already dequeue - */ - tmpTail = ring->cons.tail; - - if (tmpTail + size - CurHead == 0) - { - /* - here we give enqueue a chance to recorrect the Tail, if tail not has Data let tail++ - */ - if (ring->ring[tmpTail & mask].data_s.val == 0) - { - (void) __sync_bool_compare_and_swap (&ring->cons.tail, tmpTail, - tmpTail + 1); - } - else - { - return 0; - } - } - - /* - the old version of ring->ring[CurHead&mask] must CurHead - size, which enqueue set to this pos lasttime - & the val must already dequeue. otherwise this pos can't enqueue; - */ - expectPostVal.data_l = - (((unsigned long long) (CurHead - size)) << VALUE_LEN); - - /* - the new version of ring->ring[CurHead&mask] must CurHead, which enqueue set to this pos this time. - */ - curVal.data_l = - ((((unsigned long long) CurHead) << VALUE_LEN) | - ((char *) prmBox - (char *) ring->Addrbase)); - if (ring->ring[CurHead & mask].data_s.ver == expectPostVal.data_s.ver - && __sync_bool_compare_and_swap (&ring->ring[CurHead & mask].data_l, - expectPostVal.data_l, - curVal.data_l)) - { - /* - enqueue success, add Head Value now - here we using CAS set instead __sync_fetch_and_add(&ring->Head, 1) to assume that, if one process enqueue success && been killed before - add Head, other process can recorrect the Head Value; - one more thing the direction of Tail must been add-direction, so we using the condition (ring->Head - CurHead >0x80000000); - while many thread do enqueue at same time, Head may not correct,exp: - thread A get old head 10, thread A want set head to 11 - thread B get old head 10, thread B want set head to 12 - thread A do CAS && thread B do CAS at same time, thread A do CAS success; - the result of head is 11, but the correct Value should be 12; - - then thread C get old head 11, thread C will set head to 13[cause pos 12 already has value, thread C will skill 12], - the head will be recorrect by thread C. - if no thread C, thread A& B are the last enqueue thread; the head must recorrect by the deque function. - */ - tmpHead = ring->prod.head; - - if (0 == (CurHead & 0x03) && tmpHead - CurHead > 0x80000000) - { - (void) __sync_bool_compare_and_swap (&ring->prod.head, tmpHead, - CurHead + 1); - } - - break; - } - - /* - CurHead++ here; - may be cpu slice is end here; while re-sched CurHead < ring->Tail < ring->Head; to avoid multi try - we using a cmp & CurHead++ instead CurHead++ directly. - if using CurHead++ will amplify the probability of ABA problem - */ - /*CurHead++; */ - tmpHead = ring->prod.head; - CurHead = CurHead - tmpHead < mask - 1 ? CurHead + 1 : tmpHead; - } - while (1); - - return 1; -} - -/* - this is a single thread/process enqueue function - */ -int -nsfw_shmem_ring_sp_enqueue (struct nsfw_mem_ring *ring, void *box) -{ - union RingData_U texpectPostVal; - union RingData_U curVal; - unsigned int tmpTail; - unsigned int CurHead = ring->prod.head; - unsigned int mask = ring->mask; - unsigned int uisize = ring->size; - void *prmBox = NULL; - - prmBox = (void *) ADDR_LTOSH_EXT (box); - - if ((char *) prmBox <= (char *) ring->Addrbase - || (char *) prmBox > (char *) ring->Addrbase + PERFRING_ADDR_RANGE) - { - return -1; - } - - do - { - tmpTail = ring->cons.tail; - if (tmpTail + uisize - CurHead == 0) - { - /* - *here we give enqueue a chance to recorrect the Tail, if tail not has Data let tail++ - */ - if (ring->ring[tmpTail & mask].data_s.val == 0) - { - (void) __sync_bool_compare_and_swap (&ring->cons.tail, tmpTail, - tmpTail + 1); - } - else - { - return 0; - } - } - texpectPostVal.data_l = - (((unsigned long long) (CurHead - uisize)) << VALUE_LEN); - - curVal.data_l = - ((((unsigned long long) CurHead) << VALUE_LEN) | - ((char *) prmBox - (char *) ring->Addrbase)); - - if (ring->ring[CurHead & mask].data_l == texpectPostVal.data_l) - { - ring->ring[CurHead & mask].data_l = curVal.data_l; - ring->prod.head = CurHead + 1; - break; - } - - CurHead++; - } - while (1); - return 1; -} - -/*this is a multi thread/process dequeue function, please pay attention to the bellow point -*/ -int -nsfw_shmem_ring_mc_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - unsigned int CurTail; - unsigned int tmpTail; - unsigned int tmpHead; - unsigned int mask = ring->mask; - union RingData_U curNullVal; - union RingData_U ExcpRingVal; - - CurTail = ring->cons.tail; - do - { - /*if ring is empty return directly */ - tmpHead = ring->prod.head; - - if (CurTail == tmpHead) - { - /* - here we give deque a chance to recorrect the Head, if head has Data let Head++ - */ - if (ring->ring[tmpHead & mask].data_s.val != 0) - { - (void) __sync_bool_compare_and_swap (&ring->prod.head, tmpHead, - tmpHead + 1); - } - else - { - return 0; - } - } - curNullVal.data_l = (((unsigned long long) CurTail) << VALUE_LEN); - ExcpRingVal = ring->ring[CurTail & mask]; - /* - *the version of ring->ring[CurTail&mask] must CurTail&0xFFFFFF - */ - if ((curNullVal.data_s.ver == ExcpRingVal.data_s.ver) - && (ExcpRingVal.data_s.val) - && __sync_bool_compare_and_swap (&ring->ring[CurTail & mask].data_l, - ExcpRingVal.data_l, - curNullVal.data_l)) - { - - *box = - ADDR_SHTOL (((char *) ring->Addrbase + ExcpRingVal.data_s.val)); - - /* - enqueue success, add Tail Value now - here we using CAS set instead __sync_fetch_and_add(&ring->Tail, 1) to assume that, if one process dequeue success && been killed before - add Tail, other process can recorrect the Tail Value; - one more thing the direction of Tail must been add-direction, so we using the condition (rlTail - CurTail >0x80000000); - while multi CAS done the result value of CurTail may not correct, but we don't care, it will be recorrect while next deque done. - - avg CAS cost 200-300 Cycles, so we using cache loop to instead some CAS;[head&tail not exact guide, so no need Do CAS evertime] - here we using 0 == (CurTail&0x11) means we only do CAS while head/tail low bit is 0x11; four times do one CAS. - */ - tmpTail = ring->cons.tail; - - if (0 == (CurTail & 0x03) && tmpTail - CurTail > 0x80000000) - { - (void) __sync_bool_compare_and_swap (&ring->cons.tail, tmpTail, - CurTail + 1); - } - break; - } - - /* - CurTail++ here; - may be cpu slice is end here; while re-sched CurTail < ring->Tail < ring->Head; to avoid multi try - we using a cmp & CurTail++ instead CurTail++ directly. - if using CurTail++ will amplify the probability of ABA problem - */ - /*CurTail++; */ - tmpTail = ring->cons.tail; - CurTail = CurTail - tmpTail < mask - 1 ? CurTail + 1 : tmpTail; - } - while (1); - - return 1; -} - -/* - this is enhanced mc_ring_dequeue, support dequeue multi element one time. -*/ -int -nsfw_shmem_ring_mc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n) -{ - unsigned int uiCurTail; - unsigned int tmpTail; - unsigned int tmpHead; - unsigned int uimask = ring->mask; - union RingData_U curNullVal; - union RingData_U ExcpRingVal; - unsigned int deqNum = 0; - uiCurTail = ring->cons.tail; - do - { - /*if ring is empty return directly */ - tmpHead = ring->prod.head; - if (uiCurTail == tmpHead) - { - /* - here we give deque a chance to recorrect the Head, if head has Data let Head++; - here must done to avoid some msg can't deque. - */ - if (deqNum == 0 && ring->ring[tmpHead & uimask].data_s.val != 0) - { - (void) __sync_bool_compare_and_swap (&ring->prod.head, tmpHead, - tmpHead + 1); - } - else - { - return deqNum; - } - } - - curNullVal.data_l = (((unsigned long long) uiCurTail) << VALUE_LEN); - ExcpRingVal = ring->ring[uiCurTail & uimask]; - - /* - *the version of ring->ring[CurTail&mask] must CurTail&0xFFFFFF - */ - if ((curNullVal.data_s.ver == ExcpRingVal.data_s.ver) - && (ExcpRingVal.data_s.val) - && __sync_bool_compare_and_swap (&ring-> - ring[uiCurTail & uimask].data_l, - ExcpRingVal.data_l, - curNullVal.data_l)) - { - - box[deqNum] = - ADDR_SHTOL (((char *) ring->Addrbase + ExcpRingVal.data_s.val)); - - /* - enqueue success, add Tail Value now - here we using CAS set instead __sync_fetch_and_add(&ring->Tail, 1) to assume that, if one process dequeue success && been killed before - add Tail, other process can recorrect the Tail Value; - one more thing the direction of Tail must been add-direction, so we using the condition (rlTail - CurTail >0x80000000); - - avg CAS cost 200-300 Cycles, so we using cache loop to instead some CAS;[head&tail not exact guide, so no need Do CAS evertime] - here we using 0 == (CurTail&0x11) means we only do CAS while head/tail low bit is 0x11; four times do one CAS. - */ - tmpTail = ring->cons.tail; - - if (0 == (uiCurTail & 0x03) && tmpTail - uiCurTail > 0x80000000) - { - (void) __sync_bool_compare_and_swap (&ring->cons.tail, tmpTail, - uiCurTail + 1); - } - - deqNum++; - } - - /* - CurTail++ here; - may be cpu slice is end here; while re-sched CurTail < ring->Tail < ring->Head; to avoid multi try - we using a cmp & CurTail++ instead CurTail++ directly. - if using CurTail++ will amplify the probability of ABA problem - */ - /*CurTail++; */ - tmpTail = ring->cons.tail; - uiCurTail = uiCurTail - tmpTail < uimask - 1 ? uiCurTail + 1 : tmpTail; - - } - while (n > deqNum); - - return deqNum; -} - -/* - this is enhanced mc_ring_dequeue, support dequeue multi element one time. -*/ -int -nsfw_shmem_ring_sc_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - unsigned int CurTail; - unsigned int mask = ring->mask; - union RingData_U curNullVal; - union RingData_U ExcpRingVal; - unsigned int uitmpHead; - - CurTail = ring->cons.tail; - - do - { - /*if ring is empty return directly */ - uitmpHead = ring->prod.head; - if (CurTail == uitmpHead) - { - /* - here we give deque a chance to recorrect the Head, if head has Data let Head++ - */ - if (ring->ring[uitmpHead & mask].data_s.val != 0) - { - (void) __sync_bool_compare_and_swap (&ring->prod.head, - uitmpHead, uitmpHead + 1); - } - else - { - return 0; - } - } - curNullVal.data_l = (((unsigned long long) CurTail) << VALUE_LEN); - ExcpRingVal = ring->ring[CurTail & mask]; - - if ((curNullVal.data_s.ver == ExcpRingVal.data_s.ver) - && (ExcpRingVal.data_s.val)) - { - ring->ring[CurTail & mask].data_l = curNullVal.data_l; - - *box = - ADDR_SHTOL (((char *) ring->Addrbase + ExcpRingVal.data_s.val)); - - ring->cons.tail = CurTail + 1; - break; - } - - CurTail++; - } - while (1); - - return 1; -} - -/* - this is a single thread/process dequeue function -*/ -int -nsfw_shmem_ring_sc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n) -{ - unsigned int CurTail; - unsigned int tmpHead; - unsigned int mask = ring->mask; - union RingData_U curNullVal; - union RingData_U ExcpRingVal; - unsigned int usdeqNum = 0; - - CurTail = ring->cons.tail; - - do - { - /*if ring is empty return directly */ - tmpHead = ring->prod.head; - if (CurTail == tmpHead) - { - /* - here we give deque a chance to recorrect the Head, if head has Data let Head++; - here must done to avoid some msg can't deque. - */ - if (usdeqNum == 0 && ring->ring[tmpHead & mask].data_s.val != 0) - { - (void) __sync_bool_compare_and_swap (&ring->prod.head, tmpHead, - tmpHead + 1); - } - else - { - return usdeqNum; - } - } - curNullVal.data_l = (((unsigned long long) CurTail) << VALUE_LEN); - ExcpRingVal = ring->ring[CurTail & mask]; - - /* - the version of ring->ring[CurTail&mask] must CurTail&0xFFFFFF - */ - if ((curNullVal.data_s.ver == ExcpRingVal.data_s.ver) - && (ExcpRingVal.data_s.val)) - { - ring->ring[CurTail & mask].data_l = curNullVal.data_l; - - box[usdeqNum] = - ADDR_SHTOL (((char *) ring->Addrbase + ExcpRingVal.data_s.val)); - - ring->cons.tail = CurTail + 1; - usdeqNum++; - } - - CurTail++; - } - while (n > usdeqNum); - - return usdeqNum; -} - -/* nstack just using one thread, for performance using que not support multi thread*/ -int -nsfw_shmem_ring_singlethread_enqueue (struct nsfw_mem_ring *ring, void *box) -{ - u32 head = 0; - void *prmBox = NULL; - - /*if queue is full, just return 0 */ - if (ring->prod.head >= (ring->size + ring->cons.tail)) - { - return 0; - } - - prmBox = (void *) ADDR_LTOSH_EXT (box); - - head = ring->prod.head; - ring->prod.head = head + 1; - ring->ring[head & ring->mask].data_s.ver = head; - ring->ring[head & ring->mask].data_s.val = - (char *) prmBox - (char *) ring->Addrbase; - return 1; -} - -/* nstack just using one thread, for performance using que not support multi thread*/ -int -nsfw_shmem_ring_singlethread_dequeue (struct nsfw_mem_ring *ring, void **box) -{ - u32 tail = 0; - - /* if all entries are dequeued return 0 */ - if (unlikely (ring->prod.head == ring->cons.tail)) - { - return 0; - } - - tail = ring->cons.tail; - *box = - ADDR_SHTOL ((char *) ring->Addrbase + - ring->ring[tail & ring->mask].data_s.val); - ring->ring[tail & ring->mask].data_s.val = 0; - ring->ring[tail & ring->mask].data_s.ver = tail; - ring->cons.tail++; - return 1; -} - -/* nstack just using one thread, for performance using que not support multi thread*/ -int -nsfw_shmem_ring_singlethread_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n) -{ - u32 tail = 0; - u32 num = 0; - - while (num < n) - { - tail = ring->cons.tail; - - /* if all entries are dequeued return 0 */ - if (unlikely (ring->prod.head == ring->cons.tail)) - { - return num; - } - - ring->cons.tail = tail + 1; - - box[num] = - ADDR_SHTOL ((char *) ring->Addrbase + - ring->ring[tail & ring->mask].data_s.val); - - ring->ring[tail & ring->mask].data_s.val = 0; - ring->ring[tail & ring->mask].data_s.ver = tail; - num++; - } - - return num; -} diff --git a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.h b/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.h deleted file mode 100644 index 15cd1dd..0000000 --- a/src/framework/common/mem_mgr/nsfw_shmem/nsfw_shmem_ring.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* -* 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 _NSFW_SHMEM_RING_H_ -#define _NSFW_SHMEM_RING_H_ - -#include <stdint.h> - -#include "common_func.h" - -struct nsfw_shmem_ring_head -{ - struct common_mem_memzone *mem_zone; - struct nsfw_shmem_ring_head *next; - unsigned int uireserv[4]; -}; - -void nsfw_shmem_ring_baseaddr_query (uint64_t * rte_lowest_addr, - uint64_t * rte_highest_addr); -struct nsfw_mem_ring *nsfw_shmem_pool_create (const char *name, - unsigned int n, - unsigned int elt_size, - int socket_id, - unsigned char flag); -struct nsfw_mem_ring *nsfw_shmem_ring_create (const char *name, - unsigned int n, int socket_id, - unsigned char flag); - -void nsfw_shmem_pool_free (struct nsfw_mem_ring *perfring_ptr); - -void nsfw_shmem_ring_reset (struct nsfw_mem_ring *ring, unsigned char flag); -int nsfw_shmem_ring_mp_enqueue (struct nsfw_mem_ring *ring, void *box); -int nsfw_shmem_ring_sp_enqueue (struct nsfw_mem_ring *ring, void *box); -int nsfw_shmem_ring_mc_dequeue (struct nsfw_mem_ring *ring, void **box); -int nsfw_shmem_ring_mc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n); -int nsfw_shmem_ring_sc_dequeue (struct nsfw_mem_ring *ring, void **box); -int nsfw_shmem_ring_sc_dequeuev (struct nsfw_mem_ring *ring, void **box, - unsigned int n); -int nsfw_shmem_ring_singlethread_enqueue (struct nsfw_mem_ring *ring, - void *box); -int nsfw_shmem_ring_singlethread_dequeue (struct nsfw_mem_ring *ring, - void **box); -int nsfw_shmem_ring_singlethread_dequeuev (struct nsfw_mem_ring *ring, - void **box, unsigned int n); - -#endif /*_NSFW_SHMEM_RING_H_*/ diff --git a/src/framework/common/pid_common.c b/src/framework/common/pid_common.c new file mode 100644 index 0000000..16f5c5e --- /dev/null +++ b/src/framework/common/pid_common.c @@ -0,0 +1,167 @@ +/* +* +* 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 <time.h> +#include <errno.h> +#include "nstack_log.h" +#include "nstack_securec.h" +#include "pid_common.h" + +volatile pid_t g_sys_host_pid = SYS_HOST_INITIAL_PID; + +/***************************************************************************** +* Prototype : get_hostpid_from_file +* Description : get host pid by sub namespace pid in docker +* Input : uint32_t pid +* Output : None +* Return Value : uint32_t +* Calls : +* Called By : +*****************************************************************************/ +pid_t sys_get_hostpid_from_file(pid_t pid) +{ + g_sys_host_pid = get_hostpid_from_file(pid); + NSRTP_LOGDBG("ok]cur pid=%d, input pid=%d", g_sys_host_pid, pid); + return g_sys_host_pid; +} + +pid_t get_hostpid_from_file(u32_t pid) +{ + pid_t ret_pid = SYS_HOST_INITIAL_PID; + int i = 0; + ret_pid = get_hostpid_from_file_one_time(pid); + while (0 == ret_pid || ret_pid == SYS_HOST_INITIAL_PID) + { + i++; + if (i > MAX_GET_PID_TIME) + { + NSFW_LOGERR("get pid failed]pid=%u,hostpid=%d", pid, ret_pid); + break; + } + sys_sleep_ns(0, 5000000); + ret_pid = get_hostpid_from_file_one_time(pid); + } + + return ret_pid; +} + +pid_t get_hostpid_from_file_one_time(u32_t pid) +{ + int retVal; + char path[READ_FILE_BUFLEN] = { 0 }; + char buf[READ_FILE_BUFLEN] = { 0 }; + char fmt[READ_FILE_BUFLEN] = { 0 }; + char out[READ_FILE_BUFLEN] = { 0 }; + char task_name[BUF_SIZE_FILEPATH] = { 0 }; + pid_t hostpid = SYS_HOST_INITIAL_PID; //init to an invalid value + /*There are some unsafe function ,need to be replace with safe function */ + get_exec_name_by_pid(pid, task_name, BUF_SIZE_FILEPATH); + + /* adjust the position of HAVE_STACKTRACE and modify to snprintf_s */ + if (0 == task_name[0]) + { + NSRTP_LOGERR("get task_name failed"); + return hostpid; + } + + /*There are some unsafe function ,need to be replace with safe function */ + retVal = sprintf_s(fmt, sizeof(fmt), "%s%s", task_name, " (%s"); + if (-1 == retVal) + { + NSRTP_LOGERR("sprintf_s failed]ret=%d", retVal); + return hostpid; + } + retVal = sprintf_s(path, sizeof(path), "/proc/%u/sched", pid); + if (-1 == retVal) + { + NSRTP_LOGERR("sprintf_s failed]ret=%d", retVal); + return hostpid; + } + FILE *fp = fopen(path, "r"); + if (NULL != fp) + { + if (fgets(buf, READ_FILE_BUFLEN - 1, fp) == NULL) + { + fclose(fp); + return hostpid; + } + fclose(fp); + /* Compiler needs "fmt" to be like "%s%s" to + understand. But we have "fmt" already prepared and used here. It can + be suppressed, not an issue + */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" + /*There are some unsafe function ,need to be replace with safe function */ + retVal = sscanf_s(buf, fmt, out, READ_FILE_BUFLEN); +#pragma GCC diagnostic pop + if (-1 == retVal) + { + NSPOL_LOGERR("sscanf_s failed]ret=%d", retVal); + return hostpid; + } + /*There are some unsafe function ,need to be replace with safe function */ + } + + hostpid = (pid_t) strtol(out, NULL, 0); + if (hostpid == 0) + { + hostpid = 1; + } + + return hostpid; +} + +void get_exec_name_by_pid(pid_t pid, char *task_name, int task_name_len) +{ + int retVal; + char path[READ_FILE_BUFLEN] = { 0 }; + char buf[READ_FILE_BUFLEN] = { 0 }; + /* There are some unsafe function ,need to be replace with safe function */ + retVal = sprintf_s(path, sizeof(path), "/proc/%d/status", pid); + if (-1 == retVal) + { + NSRTP_LOGERR("sprintf_s failed]ret=%d", retVal); + return; + } + FILE *fp = fopen(path, "r"); + if (NULL != fp) + { + if (fgets(buf, READ_FILE_BUFLEN - 1, fp) == NULL) + { + fclose(fp); + return; + } + fclose(fp); + /*There are some unsafe function ,need to be replace with safe function */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-extra-args" + retVal = sscanf_s(buf, "%*s %s", task_name, task_name_len); +#pragma GCC diagnostic pop + if (1 != retVal) + { + NSSOC_LOGERR("sscanf_s failed]ret=%d", retVal); + return; + } + } +} + +pid_t updata_sys_pid() +{ + g_sys_host_pid = SYS_HOST_INITIAL_PID; + return get_sys_pid(); +} diff --git a/src/framework/dfx/nstack_dmm_dfx.c b/src/framework/dfx/nstack_dmm_dfx.c new file mode 100644 index 0000000..3fe1aa4 --- /dev/null +++ b/src/framework/dfx/nstack_dmm_dfx.c @@ -0,0 +1,161 @@ +/* +* +* 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_dmm_dfx.h" +#include "nstack_securec.h" +#include "nstack_module.h" +#include "nstack_log.h" + +nstack_dmm_stack_ops_t *g_nstack_dmm_dfx_ops; + +#define nstack_dfx_calculate_elapse(a, b) ((a)>(b)?((((a)-(b))<0XFFFF)?(a)-(b):0XFFFF): 0) +nstack_fd_dfx_t *dmm_fd_dfx_pool = NULL; + +void nstack_dfx_state_update(u64 fd, int midx, nstack_dmm_type_t type, + void *data) +{ + if (midx < 0 || + !g_nstack_dmm_dfx_ops || + !(g_nstack_dmm_dfx_ops[midx].update_dfx_data)) + { + return; + } + + midx = g_nstack_dmm_dfx_ops[0].type ? 0 : midx; + g_nstack_dmm_dfx_ops[midx].update_dfx_data(fd, type, data); +} + +void nstack_fd_dfx_update_dfx_data(int fd, int protoFd, int midx, int type, + void *info) +{ + u16 data = 0; + if (midx < 0 || fd < 0 || protoFd < 0) + return; + + if (!dmm_fd_dfx_pool || + !g_nstack_dmm_dfx_ops || + !(g_nstack_dmm_dfx_ops[midx].update_dfx_data)) + { + return; + } + + switch (type) + { + case DMM_STAT_LONGEST_SEND_INTERVAL: + if (dmm_fd_dfx_pool[fd].last_send_out_tick) + { + data = + nstack_dfx_calculate_elapse(dmm_fd_dfx_pool + [fd].last_send_in_tick, + dmm_fd_dfx_pool + [fd].last_send_out_tick); + nstack_dfx_state_update((u64) protoFd, midx, + DMM_STAT_LONGEST_SEND_INTERVAL, + &data); + } + break; + case DMM_STAT_LONGEST_SEND_COST: + data = + nstack_dfx_calculate_elapse(dmm_fd_dfx_pool + [fd].last_send_out_tick, + dmm_fd_dfx_pool + [fd].last_send_in_tick); + nstack_dfx_state_update((u64) protoFd, midx, + DMM_STAT_LONGEST_SEND_COST, &data); + break; + case DMM_STAT_LONGEST_RECV_INTERVAL: + if (dmm_fd_dfx_pool[fd].last_recv_out_tick) + { + data = + nstack_dfx_calculate_elapse(dmm_fd_dfx_pool + [fd].last_recv_in_tick, + dmm_fd_dfx_pool + [fd].last_recv_out_tick); + nstack_dfx_state_update((u64) protoFd, midx, + DMM_STAT_LONGEST_RECV_INTERVAL, + &data); + } + break; + case DMM_STAT_LONGEST_RECV_COST: + data = + nstack_dfx_calculate_elapse(dmm_fd_dfx_pool + [fd].last_recv_out_tick, + dmm_fd_dfx_pool + [fd].last_recv_in_tick); + nstack_dfx_state_update((u64) protoFd, midx, + DMM_STAT_LONGEST_RECV_COST, &data); + break; + default: + nstack_dfx_state_update((u64) protoFd, midx, + DMM_STAT_LONGEST_RECV_COST, info); + break; + } +} + +int nstack_dfx_init_ops(nstack_dmm_stack_ops_t * ops) +{ + int i; + + if (!ops) + return -1; + + g_nstack_dmm_dfx_ops = + malloc(sizeof(nstack_dmm_stack_ops_t) * NSTACK_MAX_MODULE_NUM); + if (!g_nstack_dmm_dfx_ops) + { + NSSOC_LOGERR("alloc dfx ops failed"); + return -1; + } + if (EOK != + memset_s(g_nstack_dmm_dfx_ops, + sizeof(nstack_dmm_stack_ops_t) * NSTACK_MAX_MODULE_NUM, 0, + sizeof(nstack_dmm_stack_ops_t) * NSTACK_MAX_MODULE_NUM)) + { + NSSOC_LOGERR("memory set failed"); + return -1; + } + switch (ops[0].type) + { + case 0: //nsocket + for (i = 0; i < NSTACK_MAX_MODULE_NUM; i++) + { + g_nstack_dmm_dfx_ops[i].update_dfx_data = + ops[i].update_dfx_data; + g_nstack_dmm_dfx_ops[i].type = ops[i].type; + } + + /*all stack just use the same time tick (default is used the first one) */ + for (i = 0; i < NSTACK_MAX_MODULE_NUM; i++) + { + if (ops[i].get_stack_tick) + { + g_nstack_dmm_dfx_ops[0].get_stack_tick = + ops[i].get_stack_tick; + break; + } + } + + break; + default: + for (i = 0; i < NSTACK_MAX_MODULE_NUM; i++) + { + g_nstack_dmm_dfx_ops[i] = *ops; + } + break; + } + + return 0; +} diff --git a/src/framework/dfx/nstack_dmm_dfx.h b/src/framework/dfx/nstack_dmm_dfx.h new file mode 100644 index 0000000..ef9d762 --- /dev/null +++ b/src/framework/dfx/nstack_dmm_dfx.h @@ -0,0 +1,69 @@ +/* +* +* 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_DMM_DFX_H__ +#define __NSTACK_DMM_DFX_H__ +#include <time.h> +#include "types.h" +#include "nsfw_dfx_api.h" +#include "nstack_callback_ops.h" + +typedef struct nstack_fd_dfx_s +{ + u64 last_send_out_tick; + u64 last_send_in_tick; + u64 last_recv_out_tick; + u64 last_recv_in_tick; + int send_stat_count; + int recv_stat_count; +} nstack_fd_dfx_t; + +extern nstack_dmm_stack_ops_t *g_nstack_dmm_dfx_ops; + +#define NSTACK_GET_SYS_TICK(data) if(g_nstack_dmm_dfx_ops && g_nstack_dmm_dfx_ops[0].get_stack_tick) g_nstack_dmm_dfx_ops[0].get_stack_tick(data); + +#define NSTACK_FD_DFX_LAST_SEND_TICK_IN(fd, tick) \ +if (dmm_fd_dfx_pool) \ +{ \ + dmm_fd_dfx_pool[fd].last_send_in_tick = tick; \ + dmm_fd_dfx_pool[fd].send_stat_count++; \ + /* todo stat longest send */ \ +} + +#define NSTACK_FD_DFX_LAST_SEND_TICK_OUT(fd, tick) \ +if (dmm_fd_dfx_pool) \ +{ \ + dmm_fd_dfx_pool[fd].last_send_out_tick = tick; \ + /* todo stat longest send */ \ +} + +#define NSTACK_FD_DFX_LAST_RECV_TICK_IN(fd, tick) \ +if (dmm_fd_dfx_pool) \ +{ \ + dmm_fd_dfx_pool[fd].last_recv_in_tick = tick; \ + dmm_fd_dfx_pool[fd].recv_stat_count++; \ + /* todo stat longest send */ \ +} + +#define NSTACK_FD_DFX_LAST_RECV_TICK_OUT(fd, tick) \ +if (dmm_fd_dfx_pool) \ +{ \ + dmm_fd_dfx_pool[fd].last_recv_out_tick = tick; \ + /* todo stat longest send */ \ +} + +extern nstack_fd_dfx_t *dmm_fd_dfx_pool; +#endif diff --git a/src/framework/event/epoll/ephlist.h b/src/framework/event/epoll/ephlist.h new file mode 100644 index 0000000..07861b5 --- /dev/null +++ b/src/framework/event/epoll/ephlist.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 _EPHLIST_H_ +#define _EPHLIST_H_ + +#include <stdio.h> +#include "types.h" +#include "nsfw_mem_api.h" +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +struct ep_hlist_node +{ + struct ep_hlist_node *next, **pprev; +}; + +struct ep_node_list +{ + struct ep_hlist_node *head; + struct ep_hlist_node *tail; +}; + +struct ep_hlist +{ + struct ep_hlist_node node; + struct ep_hlist_node *head; + struct ep_hlist_node *tail; +}; + +#define ep_hlist_entry(ptr, type, member) container_of(ptr, type, member) + +#define EP_HLIST_INIT_NODE(node) {\ + (node)->next = NULL;\ + (node)->pprev = NULL; \ + } + +#define EP_HLIST_INIT(ptr) {\ + EP_HLIST_INIT_NODE(&((ptr)->node)); \ + (ptr)->head = (struct ep_hlist_node*)SHMEM_ADDR_LTOSH_EXT(&((ptr)->node)); \ + (ptr)->tail = (struct ep_hlist_node*)SHMEM_ADDR_LTOSH_EXT(&((ptr)->node)); \ + } + +#define EP_HLIST_PREV(ptr) ((struct ep_hlist_node*)(SHMEM_ADDR_SHTOL((ptr)->pprev))) +/* list check may below zero mod Begin + Modifed to check header, because if app crash before do list->size++, it will lead problem */ +#define EP_HLIST_EMPTY(list) (NULL == ((struct ep_hlist_node*)SHMEM_ADDR_SHTOL((list)->head))->next) +#define EP_HLIST_NODE_LINKED(node) (!(!(node)->pprev)) + +static __inline void ep_hlist_del(struct ep_hlist *list, + struct ep_hlist_node *n); +static __inline void ep_hlist_add_tail(struct ep_hlist *list, + struct ep_hlist_node *node); + +/* + * list , n are local pointer, don't need to cast + */ +static __inline void ep_hlist_del(struct ep_hlist *list, + struct ep_hlist_node *n) +{ + if (!EP_HLIST_NODE_LINKED(n)) + return; + EP_HLIST_PREV(n)->next = n->next; + if (n->next) + { + ((struct ep_hlist_node *) SHMEM_ADDR_SHTOL(n->next))->pprev = + n->pprev; + } + else + { + list->tail = (struct ep_hlist_node *) (n->pprev); + } + EP_HLIST_INIT_NODE(n); +} + +/** + * list, node are local pointer , don't need to case + */ +static __inline void ep_hlist_add_tail(struct ep_hlist *list, + struct ep_hlist_node *node) +{ + struct ep_hlist_node *tail = + (struct ep_hlist_node *) SHMEM_ADDR_SHTOL(list->tail); + EP_HLIST_INIT_NODE(node); + node->pprev = (struct ep_hlist_node **) SHMEM_ADDR_LTOSH_EXT(&tail->next); + tail->next = (struct ep_hlist_node *) SHMEM_ADDR_LTOSH_EXT(node); + list->tail = (struct ep_hlist_node *) SHMEM_ADDR_LTOSH_EXT(node); +} + +/*#########################################################*/ +struct list_node +{ + struct list_node *next; +}; + +struct ep_list +{ + struct list_node node; + struct list_node *head; + //struct list_node *tail; +}; + +#define ep_list_entry(ptr, type, member) container_of(ptr, type, member) + +#define EP_LIST_INIT_NODE(node) {\ + (node)->next = NULL;\ + } + +#define EP_LIST_INIT(ptr) {\ + EP_LIST_INIT_NODE(&((ptr)->node)); \ + (ptr)->head = (struct list_node*)SHMEM_ADDR_LTOSH_EXT(&((ptr)->node)); \ + } + +#define EP_LIST_EMPTY(list) (NULL == ((struct list_node*)SHMEM_ADDR_SHTOL((list)->head))->next) + +static __inline void ep_list_del(struct ep_list *list, struct list_node *n); +static __inline void ep_list_add_tail(struct ep_list *list, + struct list_node *node); + +/* + * list , n are local pointer, don't need to cast + */ +static __inline void ep_list_del(struct ep_list *list, struct list_node *n) +{ + if (NULL == n || NULL == list) + { + return; + } + + struct list_node *p_node; + struct list_node *p_prev = NULL; + p_node = ((struct list_node *) SHMEM_ADDR_SHTOL(list->head)); + while (NULL != p_node && p_node != n) + { + p_prev = p_node; + p_node = ((struct list_node *) SHMEM_ADDR_SHTOL(p_node->next)); + } + + if (p_node != n || p_prev == NULL) + { + return; + } + + p_prev->next = n->next; + + EP_LIST_INIT_NODE(n); + return; +} + +/** + * list, node are local pointer , don't need to case + */ +static __inline void ep_list_add_tail(struct ep_list *list, + struct list_node *node) +{ + /*3th round code security review fix, */ + if (NULL == list || NULL == node) + { + return; + } + + struct list_node *p_node; + struct list_node *p_prev = NULL; + p_node = ((struct list_node *) SHMEM_ADDR_SHTOL(list->head)); + while (NULL != p_node) + { + p_prev = p_node; + p_node = ((struct list_node *) SHMEM_ADDR_SHTOL(p_node->next)); + } + + if (NULL == p_prev) + { + return; + } + + EP_LIST_INIT_NODE(node); + p_prev->next = (struct list_node *) SHMEM_ADDR_LTOSH_EXT(node); + return; +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif /* _HLIST_H_ */ diff --git a/src/framework/common/include/eprb_tree.h b/src/framework/event/epoll/eprb_tree.h index 558ab2d..e23e91c 100644 --- a/src/framework/common/include/eprb_tree.h +++ b/src/framework/event/epoll/eprb_tree.h @@ -20,9 +20,7 @@ #include <stdio.h> #include <stdlib.h> #include "types.h" -#include "common_mem_pal.h" -#include "common_mem_buf.h" -#include "common_pal_bitwide_adjust.h" +#include "nsfw_mem_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ extern "C" { @@ -34,44 +32,44 @@ extern "C" { struct ep_rb_node { - int color; + int color; - struct ep_rb_node *rb_parent; - struct ep_rb_node *rb_right; - struct ep_rb_node *rb_left; + struct ep_rb_node *rb_parent; + struct ep_rb_node *rb_right; + struct ep_rb_node *rb_left; }; /* The alignment might seem pointless, but allegedly CRIS needs it */ struct ep_rb_root { - struct ep_rb_node *rb_node; + struct ep_rb_node *rb_node; }; #define ep_rb_parent(r) ((struct ep_rb_node *)((r)->rb_parent)) -static inline void -ep_rb_set_parent (struct ep_rb_node *rb, struct ep_rb_node *p) +static inline void ep_rb_set_parent(struct ep_rb_node *rb, + struct ep_rb_node *p) { - rb->rb_parent = (struct ep_rb_node *) ADDR_LTOSH_EXT (p); + rb->rb_parent = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(p); } #define ep_rb_entry(ptr, type, member) container_of(ptr, type, member) -extern void ep_rb_insert_color (struct ep_rb_node *, struct ep_rb_root *); -extern void ep_rb_erase (struct ep_rb_node *, struct ep_rb_root *); -struct ep_rb_node *ep_rb_first (const struct ep_rb_root *); +extern void ep_rb_insert_color(struct ep_rb_node *, struct ep_rb_root *); +extern void ep_rb_erase(struct ep_rb_node *, struct ep_rb_root *); +struct ep_rb_node *ep_rb_first(const struct ep_rb_root *); -static inline void -ep_rb_link_node (struct ep_rb_node *node, - struct ep_rb_node *parent, struct ep_rb_node **rb_link) +static inline void ep_rb_link_node(struct ep_rb_node *node, + struct ep_rb_node *parent, + struct ep_rb_node **rb_link) { - node->rb_parent = (struct ep_rb_node *) ADDR_LTOSH_EXT (parent); - node->rb_left = node->rb_right = NULL; + node->rb_parent = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(parent); + node->rb_left = node->rb_right = NULL; - *rb_link = (struct ep_rb_node *) ADDR_LTOSH_EXT (node); - node->color = EP_RB_RED; + *rb_link = (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(node); + node->color = EP_RB_RED; } diff --git a/src/framework/event/epoll/nstack_epoll_api.c b/src/framework/event/epoll/nstack_epoll_api.c new file mode 100644 index 0000000..0db6a16 --- /dev/null +++ b/src/framework/event/epoll/nstack_epoll_api.c @@ -0,0 +1,192 @@ +/* +* +* 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_eventpoll.h" +#include "nsfw_mem_api.h" +#include "nstack_log.h" +#include "nstack_securec.h" +#include "nsfw_recycle_api.h" +#include "nsfw_maintain_api.h" +#include "nstack_epoll_api.h" +#include "nstack_sem.h" +#include "dmm_spinlock.h" +#include "nstack_dmm_dfx.h" + +extern int nstack_adpt_init(int flag); + +i32 nstack_epoll_init(int flag, int ns_sync_mod) +{ + i32 ret; + + nstack_adpt_init(flag); + + ret = ns_sync_sem_module_init(flag, ns_sync_mod); + + return ret; +} + +/* add parameter 'postFlag': + * 0, do not post ep->waitSem + * 1, post ep->waitSem + * Support: sometimes APP wants to get all of events generated by one operation + * Usage: When multi events continuously reportted, caller need to set postFlag as 1 on the last event. + * Note: epif should be local addr. +***/ +void nstack_epoll_event_enqueue(void *epif, int event, int postFlag) +{ + nsep_epollInfo_t *epInfo; + mring_handle ring_hd = NULL; + struct spl_conn_pool *ep_spl = NULL; + u64 rpt_epfd_cnt = 0; + + struct epitem *epi = NULL; + struct eventpoll *ep = NULL; + int enQueRet; + int protoFD; + struct list_node *node = NULL; + int lock_flag = 0; + int retVal = -1; + int new_event = 0; + + if (NULL == epif) + { + return; + } + + epInfo = (nsep_epollInfo_t *) (epif); + protoFD = epInfo->fd; + + NSFW_LOGDBG("]protoFD=%d,event=%d,postFlag=%d", protoFD, event, postFlag); + + /* solve issue: epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ + /* if this epInfo is from new nstackversion that support ep_conn */ + if (1 == epInfo->ep_conn_flag) + { + + lock_flag = + dmm_spin_trylock_with_pid((dmm_spinlock_t *) (&epInfo->epiLock), + 0); + + if (0 != lock_flag) + { + NSFW_LOGINF("not lock]protoFD=%d,event=%d,postFlag=%d,epInfo=%p", + protoFD, event, postFlag, epInfo); + return; + } + } + else + { + dmm_spin_lock_with_pid((dmm_spinlock_t *) (&epInfo->epiLock)); + } + struct list_node *fdEpiHead = + (struct list_node *) SHMEM_ADDR_SHTOL(epInfo->epiList.head); + node = (struct list_node *) SHMEM_ADDR_SHTOL(fdEpiHead->next); + + while (node) + { + rpt_epfd_cnt++; + epi = ep_hlist_entry(node, struct epitem, fllink); + node = (struct list_node *) SHMEM_ADDR_SHTOL(node->next); + + ep = (struct eventpoll *) SHMEM_ADDR_SHTOL(epi->ep); + if (NULL != epi->ep_spl) + { + ep_spl = (struct spl_conn_pool *) SHMEM_ADDR_SHTOL(epi->ep_spl); + ring_hd = (mring_handle) SHMEM_ADDR_SHTOL(ep_spl->ring_hd); + } + + new_event = epi->event.events & event; + if ((!new_event) && EVENT_MUST_INFORM_APP != postFlag) + { + continue; + } + + /* solve issue: epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ + /* if it use ep ring */ + + NSFW_LOGDBG("]protoFD=%d,event=%d,epi->event.events=%u", protoFD, + event, epi->event.events); + + if (NULL != epi->ep_spl) + { + /* if it is fault restart, then need clear epi from queue firstly */ + if (EVENT_MUST_INFORM_APP == postFlag) + { + retVal = nstack_epoll_event_dequeue(epi, 0); + } + + epi->revents |= new_event & (EPOLLERR | EPOLLHUP | EPOLLRDHUP); + NSFW_LOGDBG("spl_count = %d poll_count = %d", + (int) epi->spl_enter_count, epi->app_poll_count); + if (((epi->spl_enter_count == epi->app_poll_count) + && (EVENT_NO_INFORM_APP != postFlag)) + || (EVENT_MUST_INFORM_APP == postFlag)) + { + epi->spl_enter_count++; + enQueRet = nsfw_mem_ring_enqueue(ring_hd, epi); + if (1 != enQueRet) + { + NSFW_LOGERR + ("]ring_hd=%p,spl_enter_count=%u,app_poll_count=%u", + ring_hd, epi->spl_enter_count, epi->app_poll_count); + dmm_spin_unlock((dmm_spinlock_t *) (&epInfo->epiLock)); + return; + } + + if (-1 == retVal) + { + nstack_dfx_state_update((u64) epInfo->rlfd, epInfo->rmidx, DMM_MAIN_REPORT_EVENT_TICK, NULL); //need to transform 'event' as pointer to the calling func //Add epoll report stat + } + NSFW_LOGDBG("protoFD=%d weak up epoll waite renevts = %d", + protoFD, epi->revents); + g_ns_sync_ops.ns_sync_sem_post(&ep->waitSem); /*do not need return value */ + } + + continue; + } + + dmm_spin_lock_with_pid((dmm_spinlock_t *) (&ep->lock)); + epi->revents |= new_event; + NSFW_LOGDBG("]epi->revents=%u,epi->rdllink=%p", epi->revents, + EP_HLIST_NODE_LINKED(&epi->rdllink)); + + if (!EP_HLIST_NODE_LINKED(&epi->rdllink) + && (EVENT_NO_INFORM_APP != postFlag)) + { + ep_hlist_add_tail(&ep->rdlist, &epi->rdllink); + NSFW_LOGDBG("Add to tail]protoFD=%d,event=%d", protoFD, event); + nstack_dfx_state_update((u64) epInfo->rlfd, epInfo->rmidx, + DMM_MAIN_REPORT_EVENT_TICK, NULL); + // SPL_RTI_STAT_MACRO(TYPE_MAIN_REPORT_EVENT_TICK_EPOLL, epInfo->private_data, NULL); //need to transform 'event' as pointer to the calling func //Add epoll report stat + g_ns_sync_ops.ns_sync_sem_post(&ep->waitSem); /*do not need return value */ + } + else + { + NSFW_LOGDBG("No need to add to tail]protoFD=%d,event=%d", + protoFD, event); + } + dmm_spin_unlock((dmm_spinlock_t *) (&ep->lock)); + } + + nstack_dfx_state_update((u64) epInfo->rlfd, epInfo->rmidx, + DMM_MAIN_REPORT_EP_CNT, + (void *) (u64) rpt_epfd_cnt); + dmm_spin_unlock((dmm_spinlock_t *) (&epInfo->epiLock)); + + return; +} diff --git a/src/framework/event/epoll/nstack_epoll_comm.c b/src/framework/event/epoll/nstack_epoll_comm.c new file mode 100644 index 0000000..b90094d --- /dev/null +++ b/src/framework/event/epoll/nstack_epoll_comm.c @@ -0,0 +1,1757 @@ +/* +* +* 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_eventpoll.h" +#include "nsfw_mem_api.h" +#include "nstack_log.h" +#include "nstack_securec.h" +#include "nsfw_recycle_api.h" +#include "nsfw_maintain_api.h" +#include <stdio.h> +#include <stdlib.h> +//#include "nstack.h" +#include "nstack_epoll_api.h" +#include "nstack_share_res.h" +#include "dmm_spinlock.h" + +nsep_epollManager_t g_epollMng = { + .infoSockMap = NULL, + .checkEpollFD = -1 +}; + +extern int nsfw_ps_check_pid_nstack_status(int pid); + +/* after close fd in epfd, epfd still can epoll_wait EPOLLIN event for these fd + NOTE: 1.this func must be called in pinfo->epiLock, or else it is possible that there are multi epi in same ep ring_hd + 2. epi_addr should be local addr. +*/ +int nstack_epoll_event_dequeue(void *epi_addr, int events) +{ + + struct epitem *epi; + struct epitem *tmp_epi = NULL; + int enQueRet = 0, enQueRet_2 = 0; + u32 queue_use_count = 0, tmp_count = 0; + mring_handle mr_hand = NULL; + struct spl_conn_pool *ep_spl = NULL; + struct eventpoll *ep = NULL; + int retVal = -1; + + epi = (struct epitem *) (epi_addr); + if (events & epi->event.events) + return 0; + + if (NULL != epi->ep_spl) + { + ep = (struct eventpoll *) SHMEM_ADDR_SHTOL(epi->ep); + ep_spl = (struct spl_conn_pool *) SHMEM_ADDR_SHTOL(epi->ep_spl); + mr_hand = (mring_handle) SHMEM_ADDR_SHTOL(ep_spl->ring_hd); + /* dont clear epi successfully, it cause app coredump */ + queue_use_count = nsfw_mem_ring_using_count(mr_hand) + 4; /* for perfring, it only add head and tail PERFRING_HEAD_INCRASE_MASK */ + + while (tmp_count < queue_use_count) + { + enQueRet = nsfw_mem_ring_dequeue(mr_hand, (void **) &tmp_epi); + if ((enQueRet > 0) && (epi == tmp_epi)) + { + /* queue success */ + retVal = 0; + epi->spl_enter_count--; + return retVal; + } + else if (enQueRet > 0) + { + enQueRet_2 = nsfw_mem_ring_enqueue(mr_hand, tmp_epi); + if (1 != enQueRet_2) + { + NSPOL_LOGERR("]mr_hand=%p,tmp_epi=%p", mr_hand, tmp_epi); + return retVal; + } + g_ns_sync_ops.ns_sync_sem_post(&ep->waitSem); /*do not need return value */ + } + else + { + /* have finish all dequeue, return call */ + return retVal; + } + tmp_count++; + } + + /* in queue, don't have this epi */ + } + return retVal; +} + +/* epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ +void nsep_recycle_upgrade_resource(void) +{ + /* if app use new version, daemon-stack use old version, then conn_pool resource that + app apply willn't recycle by old daemon-stack version, so when upgrade daemon-stack to new vesion, + it need recycle these resource; + */ + nsep_epollManager_t *manager = nsep_get_manager(); + struct spl_conn_pool *pool = manager->ep_connPoll.pool; + + u32_t pos; + u32_t free_count = 0; + int tmp_pid = 0; + for (pos = 0; pos < NSTACK_MAX_EPOLL_FD_NUM - 1; pos++) + { + if (pool[pos].pid == 0) + { + continue; + } + tmp_pid = pool[pos].pid; + + if (0 == nsfw_ps_check_pid_nstack_status(tmp_pid)) + { + continue; + } + + if (-1 == nsep_free_ep_spl_conn_ring(&pool[pos])) + { + NSFW_LOGWAR("spl_conn_ring]pid=%d,pool=%p,pos=%u,ring_hd=%p", + tmp_pid, &pool[pos], pos, pool[pos].ring_hd); + break; + } + else + { + free_count++; + } + } + if (free_count > 0) + { + NSFW_LOGINF("spl_conn_ring]pid=%d,free_count=%u", tmp_pid, + free_count); + } + return; +} + +/* + * This function will find the epitem of fd in eventpool ep + * This is only used in epoll_ctl add + */ +struct epitem *nsep_find_ep(struct eventpoll *ep, int fd) +{ + struct ep_rb_node *rbp; + struct epitem *epi, *epir = NULL; + u32_t loopCnt = 0; + + for (rbp = SHMEM_ADDR_SHTOL(ep->rbr.rb_node); rbp;) + { + ++loopCnt; + if (loopCnt > NSTACK_MAX_EPITEM_NUM) + break; + + epi = (struct epitem *) ep_rb_entry(rbp, struct epitem, rbn); + + if (fd > epi->fd) + { + rbp = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(rbp->rb_right); + } + else if (fd < epi->fd) + { + rbp = (struct ep_rb_node *) SHMEM_ADDR_SHTOL(rbp->rb_left); + } + else + { + epir = epi; + break; + } + } + + if (loopCnt > NSTACK_MAX_EPITEM_NUM) + { + NSSOC_LOGERR("Loop out of range!!!!"); + } + + return epir; +} + +int nstack_ep_unlink(struct eventpoll *ep, struct epitem *epi) +{ + int error = ENOENT; + + if (ep_rb_parent(&epi->rbn) == (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(&epi->rbn)) /* if (!ep_rb_linked(&epi->rbn)) */ + { + NSSOC_LOGWAR("ep_rb_parent == epi->rbn"); + return error; + } + + epi->event.events = 0; + + ep_rb_erase(&epi->rbn, &ep->rbr); + ep_rb_set_parent(&epi->rbn, &epi->rbn); + + if (EP_HLIST_NODE_LINKED(&epi->rdllink)) + { + ep_hlist_del(&ep->rdlist, &epi->rdllink); + } + + return 0; +} + +/** + * @Function nsep_free_epitem + * @Description free nstack epitem + * @param in data - the epitem to be free + * @return 0 on success, -1 on error + */ +int nsep_free_epitem(struct epitem *data) +{ + + struct epitem *epiEntry = (struct epitem *) data; + struct epitem_pool *pool = &nsep_get_manager()->epitemPool; + epiEntry->pid = 0; + NSSOC_LOGDBG("nsep_free_epitem data:%p", data); + if (res_free(&epiEntry->res_chk)) + { + NSFW_LOGERR("epitem refree!]epitem=%p", epiEntry); + return -1; //3th round code security review fix + } + + /* dont clear epi successfully, it cause app coredump */ + epiEntry->ep = NULL; + epiEntry->epInfo = NULL; + epiEntry->private_data = NULL; + epiEntry->ep_spl = NULL; + epiEntry->revents = 0; + if (nsfw_mem_ring_enqueue(pool->ring, (void *) epiEntry) != 1) + { + NSSOC_LOGERR("Error to free epitem"); + return -1; //3th round code security review fix + } + return 0; +} + +NSTACK_STATIC void nsep_init_epinfo(nsep_epollInfo_t * info) +{ + int iindex = 0; + EP_LIST_INIT(&info->epiList); + DMM_SPINLOCK_MALLOC(info->epiLock, 1); + DMM_SPINLOCK_MALLOC(info->freeLock, 1); + + info->rlfd = -1; + info->rmidx = -1; + info->fd = -1; + info->ep = NULL; + info->fdtype = 0; + info->ep_conn = NULL; /* for epoll d use, when create epoll fd, it will set this to valid pointer */ + info->ep_conn_flag = 1; /* if this */ + info->private_data = NULL; + for (iindex = 0; iindex < NSEP_SMOD_MAX; iindex++) + { + info->protoFD[iindex] = -1; + info->epaddflag[iindex] = 0; + } + if (nsep_for_pidinfo_init(&(info->pidinfo))) + { + NSSOC_LOGERR("pid info init failed]epitem=%p", info); + } +} + +NSTACK_STATIC void nsep_destroy_epinfo(nsep_epollInfo_t * info) +{ + if (NULL == info) + { + return; + } + info->ep_conn = NULL; /* must set to NULL when free , it impact new old nstackverion compatible */ + info->ep_conn_flag = 0; + // TODO: Here we need to free the semaphore + return; +} + +/** + * @Function nstack_eventpoll_allocShareInfo + * @Description alloc nstack share info + * @param out data - the return value alloced + * @return 0 on success, -1 on error + */ +int nsep_alloc_epinfo(nsep_epollInfo_t ** data) +{ + nsep_epollInfo_t *head_info = NULL; + + if (NULL == data) + return -1; + NSSOC_LOGDBG("epinfo alloc begin"); + + nsep_infoPool_t *pool = &nsep_get_manager()->infoPool; + if (0 == nsfw_mem_ring_dequeue(pool->ring, (void *) &head_info) + || NULL == head_info) + { + NSSOC_LOGERR("epinfo ring alloc failed]pool->ring=%p", pool->ring); + return -1; + } + + res_alloc(&head_info->res_chk); + + nsep_init_epinfo(head_info); + if (0 != nsep_add_pid(&head_info->pidinfo, get_sys_pid())) + { + NSSOC_LOGERR("epinfo pid add to headinfo failed]pid=%d,headinfo=%p", + get_sys_pid(), head_info); + } + NSSOC_LOGDBG("epinfo ring:%p alloc epinfo:%p end", pool->ring, head_info); + *data = head_info; + return 0; +} + +/* epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ +NSTACK_STATIC int nsep_lookup_ep_spl_conn(void) +{ + + nsfw_mem_name mem_name; + mzone_handle mz_handle = NULL; + nsep_epollManager_t *manager = nsep_get_manager(); + + int retVal = strcpy_s(mem_name.aname, sizeof(mem_name.aname), + MP_NSTACK_SPL_CONN_RING_NAME); + if (EOK != retVal) + { + NSSOC_LOGERR("strcpy_s failed]"); + return -1; + } + + mem_name.enowner = NSFW_PROC_MAIN; + mem_name.entype = NSFW_SHMEM; + mz_handle = nsfw_mem_zone_lookup(&mem_name); + if (NULL == mz_handle) + { + return -1; + } + + manager->ep_connPoll.ring = mz_handle; + + retVal = + strcpy_s(mem_name.aname, sizeof(mem_name.aname), + MP_NSTACK_SPL_CONN_ARRAY_NAME); + if (EOK != retVal) + { + NSSOC_LOGERR("strcpy_s failed]"); + return -1; + } + + mz_handle = nsfw_mem_zone_lookup(&mem_name); + manager->ep_connPoll.pool = mz_handle; + if (NULL == mz_handle) + { + return -1; + } + + return 0; +} + +/* epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ +int nsep_alloc_ep_spl_conn_ring(struct spl_conn_pool **data) +{ + struct spl_conn_pool *head_info = NULL; + i32 enQueRet = 0; + struct epitem *epi = NULL; + + if (NULL == data) + return -1; + NSSOC_LOGDBG("epinfo alloc begin"); + + struct ep_conn_pool *pool = &nsep_get_manager()->ep_connPoll; + + /* support upgrade, if daemon-stack is old version, then here will fail */ + if (NULL == pool->ring) + { + /* check whether daemon-stack is new version, if it use new version, then use ring epoll */ + if (-1 == nsep_lookup_ep_spl_conn()) + { + return -1; + } + } + + if (0 == nsfw_mem_ring_dequeue(pool->ring, (void *) &head_info) + || NULL == head_info) + { + NSSOC_LOGERR("ep_spl_conn_ring alloc failed]pool->ring=%p", + pool->ring); + return -1; + } + res_alloc(&head_info->res_chk); + head_info->pid = get_sys_pid(); + head_info->revents = 0; + + /* clear the ring_hd before use */ + do + { + enQueRet = + nsfw_mem_ring_dequeue(SHMEM_ADDR_SHTOL(head_info->ring_hd), + (void **) &epi); + /* when free ep_con, it have clean ring_hd, if here find it still have epi in this ring, it indicate that it still use it after ep_conn was freed, + it need check the reason */ + if (enQueRet > 0) + { + NSSOC_LOGERR + ("fine have epi in ep_spl ring]head_info=%p,ring_hd=%p,epi=%p", + head_info, head_info->ring_hd, epi); + } + + } + while (enQueRet > 0); + + NSSOC_LOGDBG("spl_conn_ring]head_info=%p,ring_hd=%p,pid=%d", head_info, + head_info->ring_hd, head_info->pid); + + NSSOC_LOGDBG("epinfo ring:%p alloc epinfo:%p end", pool->ring, head_info); + *data = head_info; + return 0; +} + +int nsep_free_ep_spl_conn_ring(struct spl_conn_pool *data) +{ + struct spl_conn_pool *head_info = data; + struct epitem *epi = NULL; + i32 enQueRet = 0; + unsigned int total_count = 0; + + if (NULL == data) + return -1; + NSSOC_LOGDBG("nsep_free_ep_spl_conn_ring begin"); + + struct ep_conn_pool *pool = &nsep_get_manager()->ep_connPoll; + /* clear the ring_hd before free */ + do + { + enQueRet = + nsfw_mem_ring_dequeue(SHMEM_ADDR_SHTOL(head_info->ring_hd), + (void **) &epi); + if (enQueRet > 0) + { + total_count += enQueRet; + } + } + while (enQueRet > 0); + + head_info->pid = 0; + head_info->revents = 0; + + if (res_free(&head_info->res_chk)) + { + NSFW_LOGERR + ("ep_spl_conn refree!]spl_conn=%p,ring_hd=%p,total_count=%u", + head_info, head_info->ring_hd, total_count); + return -1; // 3th round code security review fix + } + + if (0 == nsfw_mem_ring_enqueue(pool->ring, (void *) head_info)) + { + NSSOC_LOGERR("spl_conn_ring free failed]pool->ring=%p,head_info=%p", + pool->ring, head_info); + return -1; + } + + NSSOC_LOGDBG("spl_conn_ring]head_info=%p,ring_hd=%p,pid=%d", head_info, + head_info->ring_hd, head_info->pid); + + return 0; +} + +/** + * @Function nstack_eventpoll_freeShareInfo + * @Description free nstack share info + * @param in info - the info to be free + * @return 0 on success, -1 on error + */ +int nsep_free_epinfo(nsep_epollInfo_t * info) +{ + + if (NULL == info) + return -1; + + nsep_infoPool_t *pool = &nsep_get_manager()->infoPool; + NSSOC_LOGDBG("nsep_free_epinfo info:%p, pool->ring:%p", info, pool->ring); + nsep_destroy_epinfo(info); + + if (nsep_for_pidinfo_init(&(info->pidinfo))) + { + NSSOC_LOGERR("pid info init failed]epitem=%p", info); + return -1; + } + + if (res_free(&info->res_chk)) + { + NSFW_LOGERR("epinfo refree!]epitem=%p", info); + return -1; // 3th round code security review fix + } + + if (nsfw_mem_ring_enqueue(pool->ring, (void *) info) != 1) + { + NSSOC_LOGERR("Errot to free epinfo"); + return -1; // 3th round code security review fix + } + + return 0; +} + +int nsep_force_epinfo_free(void *data) +{ + nsep_epollInfo_t *info = data; + if (NULL == info) + { + return FALSE; + } + + if (!nsep_is_pid_array_empty(&info->pidinfo)) + { + return FALSE; + } + + res_alloc(&info->res_chk); + (void) nsep_free_epinfo(info); + NSFW_LOGINF("free epinfo]%p", data); + return TRUE; +} + +int nsep_force_epitem_free(void *data) +{ + struct epitem *item = data; + if (NULL == item) + { + return FALSE; + } + + if (0 != item->pid) + { + return FALSE; + } + + res_alloc(&item->res_chk); + (void) nsep_free_epitem(item); + NSFW_LOGINF("free epitem]%p", data); + return TRUE; +} + +int nsep_force_epevent_free(void *data) +{ + struct eventpoll *epevent = data; + if (NULL == epevent) + { + return FALSE; + } + + if (0 != epevent->pid) + { + return FALSE; + } + + res_alloc(&epevent->res_chk); + (void) nsep_free_eventpoll(epevent); + NSFW_LOGINF("free event pool]%p", data); + return TRUE; +} + +int nsep_force_ep_spl_conn_free(void *data) +{ + struct spl_conn_pool *epConnPool = data; + if (NULL == epConnPool) + { + return FALSE; + } + + if (0 != epConnPool->pid) + { + return FALSE; + } + + res_alloc(&epConnPool->res_chk); + (void) nsep_free_ep_spl_conn_ring(epConnPool); + NSFW_LOGINF("free spl conn pool]%p", data); + return TRUE; +} + +NSTACK_STATIC int nsep_init_eventpoll(struct eventpoll *ep, int idx) +{ + int *args; + + args = (int *) ep->waitSem.args; + *args = idx; + if (0 != g_ns_sync_ops.ns_sync_sem_init(&ep->waitSem, 1, 0)) + { + return -1; + } + + DMM_SPINLOCK_MALLOC(ep->lock, 1); + DMM_SPINLOCK_MALLOC(ep->sem, 1); + + EP_HLIST_INIT(&ep->rdlist); + + ep->rbr.rb_node = NULL; + ep->epfd = -1; + //ep->pid = 0; + return 0; +} + +NSTACK_STATIC void nsep_destroy_eventpoll(struct eventpoll *ep) +{ + (void) g_ns_sync_ops.ns_sync_sem_destroy(&ep->waitSem); +} + +/** + * @Function nsep_free_eventpoll + * @Description free nstack eventpoll + * @param in ep - the eventpoll to be free + * @return 0 on success, -1 on error + */ +int nsep_free_eventpoll(struct eventpoll *ep) +{ + + if (!ep) + return -1; + struct eventpoll *epEntry = (struct eventpoll *) ep; + struct eventpoll_pool *pool = &nsep_get_manager()->epollPool; + NSSOC_LOGDBG("nsep_free_eventpoll ep:%p, epollPool:%p", ep, pool); + nsep_destroy_eventpoll(ep); + ep->pid = 0; + NSSOC_LOGDBG("Free eventpool"); + if (res_free(&ep->res_chk)) + { + NSFW_LOGERR("ep refree!]epitem=%p", epEntry); + return -1; // 3th round code security review fix + } + + if (nsfw_mem_ring_enqueue(pool->ring, epEntry) != 1) + { + NSSOC_LOGERR("Errot to free eventpoll"); + return -1; // 3th round code security review fix + } + + return 0; +} + +/** + * @Function nsep_alloc_eventpoll + * @Description alloc nstack eventpoll + * @param out data - the eventpoll alloced + * @return 0 on success, -1 on error + */ +int nsep_alloc_eventpoll(struct eventpoll **data) +{ + struct eventpoll *p_head = NULL; + struct eventpoll_pool *pool = &nsep_get_manager()->epollPool; + int idx; + + NSSOC_LOGDBG("ring:%p alloc eventpool begin", pool->ring); + if (0 == nsfw_mem_ring_dequeue(pool->ring, (void *) &p_head) + || NULL == p_head) + { + NSSOC_LOGERR("ring alloc eventpool failed]ring=%p", pool->ring); + return -1; + } + + NSSOC_LOGDBG("alloc eventpool, pid=%d", get_sys_pid()); + res_alloc(&p_head->res_chk); + p_head->pid = get_sys_pid(); + + idx = + ((unsigned long) p_head - + (unsigned long) (pool->pool)) / sizeof(struct eventpoll); + if (0 != nsep_init_eventpoll((struct eventpoll *) p_head, idx)) + { + NSSOC_LOGERR("p_head init pid alloc failed]p_head=%p,pid=%d", p_head, + get_sys_pid()); + (void) nsep_free_eventpoll((struct eventpoll *) p_head); + return -1; + } + + NSSOC_LOGDBG("ring:%p eventpoll:%p alloc eventpool end", pool->ring, + p_head); + *data = p_head; + + return 0; +} + +NSTACK_STATIC int nsep_init_epitem(struct epitem *epi) +{ + int retVal; + epi->rbn.rb_parent = + (struct ep_rb_node *) SHMEM_ADDR_LTOSH_EXT(&epi->rbn); + EP_HLIST_INIT_NODE(&epi->rdllink); + + epi->ptr_reserve = NULL; + epi->ep_spl = NULL; + epi->ep = NULL; + epi->app_poll_count = 0; + epi->spl_enter_count = 0; + epi->reserve = 0; + + //epi->pid = 0; + /* There are some unsafe function ,need to be replace with safe function */ + retVal = memset_s(&epi->event, sizeof(epi->event), 0, sizeof(epi->event)); + if (EOK != retVal) + { + NSSOC_LOGERR("memset_s failed]ret=%d", retVal); + return -1; + } + + EP_LIST_INIT_NODE(&epi->fllink); + EP_HLIST_INIT_NODE(&epi->txlink); + epi->revents = 0; + epi->fd = -1; + epi->private_data = NULL; + + return 0; +} + +/** + * @Function nsep_alloc_epitem + * @Description alloc nstack epitem + * @param out data - the epitem alloced + * @return 0 on success, -1 on error + */ +int nsep_alloc_epitem(struct epitem **data) +{ + struct epitem *p_head_entry = NULL; + struct epitem_pool *pool = &nsep_get_manager()->epitemPool; + + NSSOC_LOGDBG("epitem alloc begin.."); + + if (0 == nsfw_mem_ring_dequeue(pool->ring, (void *) &p_head_entry) + || NULL == p_head_entry) + { + NSSOC_LOGERR("epitem ring alloc failed]ring=%p", pool->ring); + return -1; + } + + res_alloc(&p_head_entry->res_chk); + p_head_entry->pid = get_sys_pid(); + + if (nsep_init_epitem((struct epitem *) p_head_entry)) + { + (void) nsep_free_epitem((struct epitem *) p_head_entry); + p_head_entry = NULL; + NSSOC_LOGERR("ring epitem init failed]ring=%p,epitem=%p", pool->ring, + p_head_entry); + return -1; + } + + NSSOC_LOGDBG("epitem alloc success..ring:%p head:%p", pool->ring, + p_head_entry); + *data = p_head_entry; + return 0; +} + +typedef int (*nsep_shem_initFn_t) (void *, size_t); + +/***************************************************************************** +* Prototype : sbr_create_mzone +* Description : create mzone +* Input : const char* name +* size_t size +* Output : None +* Return Value : mzone_handle +* Calls : +* Called By : +*****************************************************************************/ +mzone_handle nsep_create_mzone(const char *name, size_t size) +{ + if (!name) + { + NSFW_LOGERR("name is NULL"); + return NULL; + } + + mzone_handle zone; + nsfw_mem_zone param; + + param.isocket_id = -1; + param.lenth = size; + param.stname.entype = NSFW_SHMEM; + + if (strcpy_s(param.stname.aname, NSFW_MEM_NAME_LENTH, name) != 0) + { + NSFW_LOGERR("strcpy_s failed]name=%s", name); + return NULL; + } + + zone = nsfw_mem_zone_create(¶m); + if (!zone) + { + NSFW_LOGERR("nsfw_mem_zone_create failed]name=%s, size:%zu", name, + size); + return NULL; + } + + return zone; +} + +/***************************************************************************** +* Prototype : sbr_create_multi_ring +* Description : create multi ring +* Input : const char* name +* u32 ring_size +* i32 ring_num +* mring_handle* array +* nsfw_mpool_type type +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int nsep_create_multi_ring(const char *name, u32 ring_size, i32 ring_num, + mring_handle * array, nsfw_mpool_type type) +{ + if (!name) + { + NSFW_LOGERR("name is NULL"); + return -1; + } + + if (!array) + { + NSFW_LOGERR("array is NULL"); + return -1; + } + + nsfw_mem_mring param; + + if (EOK != memset_s(¶m, sizeof(param), 0, sizeof(param))) + { + NSSBR_LOGERR("Error to memset]name=%s", name); + return -1; + } + + param.enmptype = type; + param.stname.entype = NSFW_SHMEM; + if (strcpy_s(param.stname.aname, NSFW_MEM_NAME_LENTH, name) != 0) + { + NSSBR_LOGERR("strcpy_s failed]name=%s", name); + return -1; + } + + param.usnum = ring_size - 1; + param.isocket_id = -1; + if (nsfw_mem_sp_ring_create(¶m, array, ring_num) != 0) + { + NSSBR_LOGERR + ("Create ring pool failed]name=%s, ring_num=%d, ring_size=%u", + name, ring_num, ring_size); + return -1; + } + + return 0; +} + +NSTACK_STATIC int nsep_ep_conn_pool_create(void) +{ + u32_t pos; + int ret; + + nsep_epollManager_t *manager = nsep_get_manager(); + + struct spl_conn_pool *conn_pool_array = + (struct spl_conn_pool *) + nsep_create_mzone(MP_NSTACK_SPL_CONN_ARRAY_NAME, + (size_t) sizeof(struct spl_conn_pool) * + NSTACK_MAX_EPOLL_FD_NUM); + + if (!conn_pool_array) + { + NSSBR_LOGERR + ("Create tx_msg_array zone fail]name=%s, num=%u, size=%lu", + MP_NSTACK_SPL_CONN_ARRAY_NAME, NSTACK_MAX_EPOLL_FD_NUM, + (size_t) sizeof(struct spl_conn_pool) * NSTACK_MAX_EPOLL_FD_NUM); + return -1; + } + + MEM_STAT(MP_NSTACK_SPL_CONN_POOL, MP_NSTACK_SPL_CONN_ARRAY_NAME, + NSFW_SHMEM, + (size_t) sizeof(struct spl_conn_pool) * NSTACK_MAX_EPOLL_FD_NUM); + NSSBR_LOGINF + ("Create tx_msg_array zone ok]name=%s, ptr=%p, num=%u, size=%lu", + MP_NSTACK_SPL_CONN_ARRAY_NAME, conn_pool_array, + NSTACK_MAX_EPOLL_FD_NUM, + sizeof(struct spl_conn_pool) * NSTACK_MAX_EPOLL_FD_NUM); + + mring_handle *array = + (mring_handle *) malloc(NSTACK_MAX_EPOLL_FD_NUM * + sizeof(mring_handle)); + if (NULL == array) + { + NSSOC_LOGERR("malloc failed"); + return -1; + } + + ret = + memset_s(array, NSTACK_MAX_EPOLL_FD_NUM * sizeof(mring_handle), 0, + NSTACK_MAX_EPOLL_FD_NUM * sizeof(mring_handle)); + if (EOK != ret) + { + NSSOC_LOGERR("memset_s failed]ret=%d", ret); + free(array); + return -1; + } + if (nsep_create_multi_ring + (MP_NSTACK_SPL_CONN_POOL, NSTACK_MAX_EPOLL_INFO_NUM - 1, + NSTACK_MAX_EPOLL_FD_NUM - 1, (mring_handle *) array, + NSFW_MRING_MPMC) != 0) + { + free(array); + return -1; + } + + for (pos = 0; pos < NSTACK_MAX_EPOLL_FD_NUM - 1; pos++) + { + conn_pool_array[pos].pid = 0; + conn_pool_array[pos].revents = 0; + conn_pool_array[pos].res_chk.alloc_flag = 0; + conn_pool_array[pos].res_chk.chk_count = 0; + conn_pool_array[pos].res_chk.data = 0; + conn_pool_array[pos].res_chk.u8Reserve = 0; + conn_pool_array[pos].ring_hd = array[pos]; + if (-1 == + nsfw_mem_ring_enqueue(manager->ep_connPoll.ring, + &conn_pool_array[pos])) + { + free(array); + NSSOC_LOGERR("init fail to enqueue epitem]pos=%u", pos); + return -1; + } + } + manager->ep_connPoll.pool = &conn_pool_array[0]; + free(array); + + return 0; +} + +NSTACK_STATIC int nsep_ep_pool_init(void *addr, size_t lenth) +{ + u32_t pos; + int ret; + + NSSOC_LOGDBG("Start to init eventpoll pool"); + + /* add return value check */ + ret = memset_s(addr, lenth, 0, lenth); + if (EOK != ret) + { + NSSOC_LOGERR("memset_s failed]ret=%d", ret); + return -1; + } + struct eventpoll *pool = (struct eventpoll *) addr; + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epollPool.pool = pool; + + /* init g_nStackInfo.sockPool->nstack_block_array */ + for (pos = 0; pos < NSTACK_MAX_EPOLL_FD_NUM; pos++) + { + pool[pos].pid = 0; + if (-1 == nsfw_mem_ring_enqueue(manager->epollPool.ring, &pool[pos])) + { + NSSOC_LOGERR("init fail to enqueue epitem]pos=%u", pos); + return -1; + } + } + + ret = nsep_ep_conn_pool_create(); + + if (0 != ret) + { + NSSOC_LOGERR("nsep_ep_conn_pool_create failed]ret=%d", ret); + return -1; + } + + return 0; +} + +NSTACK_STATIC int nsep_epitem_pool_init(void *addr, size_t lenth) +{ + u32_t pos; + int ret; + + NSSOC_LOGDBG("Start to init epitem pool"); + + /* add return value check */ + ret = memset_s(addr, lenth, 0, lenth); + if (EOK != ret) + { + NSSOC_LOGERR("memset_s failed]ret=%d", ret); + return -1; + } + struct epitem *pool = (struct epitem *) addr; + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epitemPool.pool = pool; + + /* init g_nStackInfo.sockPool->nstack_block_array */ + for (pos = 0; pos < NSTACK_MAX_EPITEM_NUM; pos++) + { + pool[pos].pid = 0; + pool[pos].ep_spl = NULL; + pool[pos].ptr_reserve = NULL; + if (-1 == nsfw_mem_ring_enqueue(manager->epitemPool.ring, &pool[pos])) + { + NSSOC_LOGERR("init fail to enqueue epitem]pos=%u", pos); + return -1; + } + } + return 0; +} + +NSTACK_STATIC int nsep_epinfo_pool_init(void *addr, size_t lenth) +{ + u32_t pos; + int ret; + + NSSOC_LOGDBG("shmem info init start"); + + /* add return value check */ + ret = memset_s(addr, lenth, 0, lenth); + if (EOK != ret) + { + NSSOC_LOGERR("memset_s failed]ret=%d", ret); + return -1; + } + nsep_epollInfo_t *pool = (nsep_epollInfo_t *) addr; + nsep_epollManager_t *manager = nsep_get_manager(); + manager->infoPool.pool = pool; + + /* init g_nStackInfo.sockPool->nstack_block_array */ + for (pos = 0; pos < NSTACK_MAX_EPOLL_INFO_NUM; pos++) + { + if (nsep_for_pidinfo_init(&(pool[pos].pidinfo))) + { + NSSOC_LOGERR("pid info init failed]pos=%u", pos); + return -1; + } + + if (-1 == nsfw_mem_ring_enqueue(manager->infoPool.ring, &pool[pos])) + { + NSSOC_LOGERR("init fail to enqueue epInfo]pos=%u", pos); + return -1; + } + } + + NSSOC_LOGDBG("nstack_shmen_info_init success"); + return 0; +} + +NSTACK_STATIC + int nsep_create_shmem(size_t length, char *name, + nsep_shem_initFn_t initFn) +{ + nsfw_mem_zone pmeminfo; + mzone_handle phandle; + int ret; + + pmeminfo.ireserv = 0; + pmeminfo.isocket_id = NSFW_SOCKET_ANY; + pmeminfo.lenth = length; + ret = + strcpy_s(pmeminfo.stname.aname, sizeof(pmeminfo.stname.aname), name); + if (EOK != ret) + { + NSSOC_LOGERR("strcpy_s failed]name=%s,ret=%d", name, ret); + return -1; + } + pmeminfo.stname.entype = NSFW_SHMEM; + + phandle = nsfw_mem_zone_create(&pmeminfo); + if (NULL == phandle) + { + NSSOC_LOGERR("create nstack epoll memory failed]name=%s", name); + return -1; + } + + if (0 != initFn((void *) phandle, length)) + { + NSSOC_LOGERR("Fail to init memory]name=%s", name); + (void) nsfw_mem_zone_release(&pmeminfo.stname); //3th round code security review fix + return -1; + } + + return 0; +} + +NSTACK_STATIC int nsep_create_epinfo_mem() +{ + nsfw_mem_mring pringinfo; + pringinfo.enmptype = NSFW_MRING_MPMC; + pringinfo.isocket_id = NSFW_SOCKET_ANY; + pringinfo.stname.entype = NSFW_SHMEM; + pringinfo.usnum = NSTACK_MAX_EPOLL_INFO_NUM - 1; + + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPINFO_RING_NAME)) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + mring_handle ring_handle = nsfw_mem_ring_create(&pringinfo); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->infoPool.ring = ring_handle; + + return nsep_create_shmem(sizeof(nsep_epollInfo_t) * + NSTACK_MAX_EPOLL_INFO_NUM, + MP_NSTACK_EPOLL_INFO_NAME, + nsep_epinfo_pool_init); +} + +NSTACK_STATIC int nsep_adpt_attach_epinfo_mem() +{ + nsfw_mem_name name; + name.entype = NSFW_SHMEM; + name.enowner = NSFW_PROC_MAIN; + + if (-1 == + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPINFO_RING_NAME)) + { + NSSOC_LOGERR("Error to attach ring]name=%s", name.aname); + return -1; + } + mring_handle ring_handle = nsfw_mem_ring_lookup(&name); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to attach ring]name=%s", name.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->infoPool.ring = ring_handle; + + if (-1 == + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPOLL_INFO_NAME)) + { + NSSOC_LOGERR("sprintf_s failed]"); + return -1; + } + manager->infoPool.pool = nsfw_mem_zone_lookup(&name); + if (NULL == manager->infoPool.pool) + { + NSSOC_LOGERR("Error to attach memzone]name=%s", + MP_NSTACK_EPOLL_INFO_NAME); + return -1; + } + return 0; +} + +NSTACK_STATIC int nsep_create_epitem_mem() +{ + nsfw_mem_mring pringinfo; + pringinfo.enmptype = NSFW_MRING_MPMC; + pringinfo.isocket_id = NSFW_SOCKET_ANY; + pringinfo.stname.entype = NSFW_SHMEM; + pringinfo.usnum = NSTACK_MAX_EPITEM_NUM - 1; + + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPITEM_RING_NAME)) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + mring_handle ring_handle = nsfw_mem_ring_create(&pringinfo); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epitemPool.ring = ring_handle; + + return nsep_create_shmem(sizeof(struct epitem) * NSTACK_MAX_EPITEM_NUM, + MP_NSTACK_EPITEM_POOL, nsep_epitem_pool_init); + +} + +NSTACK_STATIC int nsep_adpt_attach_epitem_mem() +{ + nsfw_mem_name name; + name.entype = NSFW_SHMEM; + name.enowner = NSFW_PROC_MAIN; + + if (-1 == + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPITEM_RING_NAME)) + { + NSSOC_LOGERR("Error to attach epItemMem]name=%s", name.aname); + return -1; + } + + mring_handle ring_handle = nsfw_mem_ring_lookup(&name); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to attach ring]name=%s", name.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epitemPool.ring = ring_handle; + + if (-1 == + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EPITEM_POOL)) + { + NSSOC_LOGERR("sprintf_s failed]"); + return -1; + } + + manager->epitemPool.pool = nsfw_mem_zone_lookup(&name); + if (NULL == manager->epitemPool.pool) + { + NSSOC_LOGERR("Error to attach memzone]name=%s", + MP_NSTACK_EPITEM_POOL); + return -1; + } + return 0; +} + +NSTACK_STATIC int nsep_create_eventpoll_mem() +{ + nsfw_mem_mring pringinfo; + pringinfo.enmptype = NSFW_MRING_MPMC; + pringinfo.isocket_id = NSFW_SOCKET_ANY; + pringinfo.stname.entype = NSFW_SHMEM; + pringinfo.usnum = NSTACK_MAX_EPOLL_FD_NUM - 1; + + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EVENTPOOL_RING_NAME)) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + mring_handle ring_handle = nsfw_mem_ring_create(&pringinfo); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epollPool.ring = ring_handle; + + pringinfo.usnum = NSTACK_MAX_EPOLL_FD_NUM - 1; + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_SPL_CONN_RING_NAME)) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + ring_handle = nsfw_mem_ring_create(&pringinfo); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", pringinfo.stname.aname); + return -1; + } + + manager->ep_connPoll.ring = ring_handle; + + return nsep_create_shmem(sizeof(struct eventpoll) * + NSTACK_MAX_EPOLL_FD_NUM, + MP_NSTACK_EVENTPOLL_POOL, nsep_ep_pool_init); +} + +NSTACK_STATIC int nsep_adpt_attach_eventpoll_mem() +{ + nsfw_mem_name name; + u32 tmp_count = 0; + name.entype = NSFW_SHMEM; + name.enowner = NSFW_PROC_MAIN; + + if (-1 == + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EVENTPOOL_RING_NAME)) + { + NSSOC_LOGERR("Error to attach ring]name=%s", name.aname); + return -1; + } + + mring_handle ring_handle = nsfw_mem_ring_lookup(&name); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", name.aname); + return -1; + } + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epollPool.ring = ring_handle; + + int retVal = sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_EVENTPOLL_POOL); + if (-1 == retVal) + { + NSSOC_LOGERR("sprintf_s faild]ret=%d", retVal); + return -1; + } + manager->epollPool.pool = nsfw_mem_zone_lookup(&name); + if (NULL == manager->epollPool.pool) + { + NSSOC_LOGERR("Error to attach memzone]name=%s", + MP_NSTACK_EVENTPOLL_POOL); + return -1; + } + + retVal = + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_SPL_CONN_RING_NAME); + if (-1 == retVal) + { + NSSOC_LOGERR("sprintf_s faild]ret=%d", retVal); + return -1; + } + + manager->ep_connPoll.ring = nsfw_mem_zone_lookup(&name); + if (NULL == manager->ep_connPoll.ring) + { + + nsfw_mem_mring pringinfo; + pringinfo.enmptype = NSFW_MRING_MPMC; + pringinfo.isocket_id = NSFW_SOCKET_ANY; + pringinfo.stname.entype = NSFW_SHMEM; + pringinfo.usnum = NSTACK_MAX_EPOLL_FD_NUM; + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_SPL_CONN_RING_NAME)) + { + NSSOC_LOGERR("Error to create ring]name=%s", + pringinfo.stname.aname); + return -1; + } + + ring_handle = nsfw_mem_ring_create(&pringinfo); + + if (NULL == ring_handle) + { + NSSOC_LOGERR("Error to create ring]name=%s", + pringinfo.stname.aname); + return -1; + } + + manager->ep_connPoll.ring = ring_handle; + + } + + retVal = + sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", + MP_NSTACK_SPL_CONN_ARRAY_NAME); + if (-1 == retVal) + { + NSSOC_LOGERR("sprintf_s faild]ret=%d", retVal); + return -1; + } + + manager->ep_connPoll.pool = nsfw_mem_zone_lookup(&name); + if (NULL == manager->ep_connPoll.pool) + { + retVal = nsep_ep_conn_pool_create(); + if (0 != retVal) + { + NSSOC_LOGERR("nsep_ep_conn_pool_create failed]ret=%d", retVal); + return -1; + } + } + else + { + /* epoll global lock in daemon-stack cause daemon-stack message handle slowing */ + nsep_recycle_upgrade_resource(); + tmp_count = nsfw_mem_ring_using_count(manager->ep_connPoll.ring); + NSSOC_LOGINF("ep_connPoll.ring]ring=%p,free_num=%u", + manager->ep_connPoll.ring, tmp_count); + } + + return 0; +} + +int nsep_create_memory() +{ + typedef int (*nsep_createMemFunc_t) (void); + nsep_createMemFunc_t createFuncs[] = { nsep_create_epinfo_mem, + nsep_create_epitem_mem, + nsep_create_eventpoll_mem + }; + + int i = 0; + for (i = 0; + i < (int) (sizeof(createFuncs) / sizeof(nsep_createMemFunc_t)); i++) + { + if (-1 == createFuncs[i] ()) + return -1; + } + + return 0; +} + +int nsep_adpt_attach_memory() +{ + typedef int (*nsep_attachMemFunc_t) (void); + nsep_attachMemFunc_t attachFuncs[] = { nsep_adpt_attach_epinfo_mem, + nsep_adpt_attach_epitem_mem, + nsep_adpt_attach_eventpoll_mem + }; + + int i = 0; + for (i = 0; + i < (int) (sizeof(attachFuncs) / sizeof(nsep_attachMemFunc_t)); i++) + { + if (-1 == attachFuncs[i] ()) + { + NSSOC_LOGERR("mem attach fail]idx=%d", i); + return -1; + } + } + + return 0; +} + +int nsep_adpt_reg_res_mgr() +{ + nsep_epollManager_t *manager = nsep_get_manager(); + + nsfw_res_scn_cfg scn_cfg_info = { NSFW_RES_SCAN_ARRAY, 90, 3, 16, + NSTACK_MAX_EPOLL_INFO_NUM / 128, NSTACK_MAX_EPOLL_INFO_NUM, + sizeof(nsep_epollInfo_t), + + offsetof(nsep_epollInfo_t, res_chk), + + manager->infoPool.pool, + manager->infoPool.ring, + nsep_force_epinfo_free + }; + + nsfw_res_scn_cfg scn_cfg_item = { NSFW_RES_SCAN_ARRAY, 90, 3, 16, + NSTACK_MAX_EPITEM_NUM / 128, NSTACK_MAX_EPITEM_NUM, + sizeof(struct epitem), + + offsetof(struct epitem, res_chk), + + manager->epitemPool.pool, + manager->epitemPool.ring, + nsep_force_epitem_free + }; + + nsfw_res_scn_cfg scn_cfg_event = { NSFW_RES_SCAN_ARRAY, 90, 3, 16, + NSTACK_MAX_EPOLL_FD_NUM / 16, NSTACK_MAX_EPOLL_FD_NUM, + sizeof(struct eventpoll), + + offsetof(struct eventpoll, res_chk), + + manager->epollPool.pool, + manager->epollPool.ring, + nsep_force_epevent_free + }; + + /* solve epoll_wait hangup issue, because force free invalid ep_conn */ + nsfw_res_scn_cfg scn_cfg_spl_conn = { NSFW_RES_SCAN_ARRAY, 90, 3, 16, + NSTACK_MAX_EPOLL_FD_NUM / 16, NSTACK_MAX_EPOLL_FD_NUM, + sizeof(struct spl_conn_pool), + + offsetof(struct spl_conn_pool, res_chk), + + manager->ep_connPoll.pool, + manager->ep_connPoll.ring, + nsep_force_ep_spl_conn_free + }; + + (void) nsfw_res_mgr_reg(&scn_cfg_info); + (void) nsfw_res_mgr_reg(&scn_cfg_item); + (void) nsfw_res_mgr_reg(&scn_cfg_event); + (void) nsfw_res_mgr_reg(&scn_cfg_spl_conn); + return 0; +} + +int nsep_epitem_remove(nsep_epollInfo_t * pinfo, u32 pid) +{ + struct list_node *prenode = NULL; + struct list_node *nextnode = NULL; + struct epitem *epi = NULL; + u32_t i = 0; + int icnt = 0; + + (void) dmm_spin_lock_with_pid(&pinfo->epiLock); + /*list head must be not null */ + prenode = (struct list_node *) SHMEM_ADDR_SHTOL(pinfo->epiList.head); + nextnode = (struct list_node *) SHMEM_ADDR_SHTOL(prenode->next); + /* Change "<=" to "<" */ + while ((nextnode) && (i++ < NSTACK_MAX_EPOLL_INFO_NUM)) + { + + epi = ep_list_entry(nextnode, struct epitem, fllink); + if (pid == epi->pid) + { + /*shmem equal to shmem */ + prenode->next = nextnode->next; + nextnode->next = NULL; + /* after close fd in epfd, epfd still can epoll_wait EPOLLIN event for these fd */ + (void) nstack_epoll_event_dequeue(epi, 0); + (void) nsep_free_epitem(epi); + nextnode = SHMEM_ADDR_SHTOL(prenode->next); + icnt++; + continue; + } + prenode = nextnode; + nextnode = SHMEM_ADDR_SHTOL(nextnode->next); + } + dmm_spin_unlock(&pinfo->epiLock); + if (i >= NSTACK_MAX_EPOLL_INFO_NUM) + { + NSSOC_LOGERR("free pinfo:%p pid:%u, error maybe happen", pinfo, pid); + } + /* needn't call:nsep_epctl_triggle(NULL, epInfo, nstack_ep_triggle_inform), because here is called by daemon-stack */ + return icnt; +} + +void nsep_recycle_epfd(void *epinfo, u32 pid) +{ + struct eventpoll *ep = NULL; + struct spl_conn_pool *ep_conn = NULL; + nsep_epollInfo_t *info = (nsep_epollInfo_t *) SHMEM_ADDR_SHTOL(epinfo); + int ret = 0; + int ileftcnt = 0; + if (!epinfo) + { + NSSOC_LOGDBG("input null, pid:%u", pid); + return; + } + (void) dmm_spin_lock_with_pid(&info->freeLock); + ileftcnt = nsep_del_last_pid(&info->pidinfo, pid); + dmm_spin_unlock(&info->freeLock); + /*no pid exist */ + if (-1 == ileftcnt) + { + return; + } + if (NSTACK_EPOL_FD == info->fdtype) + { + NSSOC_LOGDBG("recycle epfd:%d epinfo pid:%u begin...", info->fd, pid); + if (0 == ileftcnt) + { + ep = SHMEM_ADDR_SHTOL(info->ep); + ep_conn = SHMEM_ADDR_SHTOL(info->ep_conn); + info->ep = NULL; + (void) nsep_free_eventpoll(ep); + (void) nsep_free_ep_spl_conn_ring(ep_conn); + info->ep_conn = NULL; + (void) nsep_free_epinfo(info); + } + return; + } + + NSSOC_LOGDBG("recycle fd:%d epinfo pid:%u begin...", info->fd, pid); + + ret = nsep_epitem_remove(info, pid); + if (0 != ret) + { + NSSOC_LOGDBG("info:%p, fd:%d pid:%u, %d items was left", info, + info->fd, pid, ret); + } + + if (0 == ileftcnt) + { + NSSOC_LOGDBG("info:%p, fd:%d pid:%u was finally freed", info, + info->fd, pid); + (void) nsep_free_epinfo(info); + } + return; +} + +int nsep_recyle_ep(u32 pid) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + nsep_epollInfo_t *pool = manager->infoPool.pool; + + u32_t pos; + for (pos = 0; pos < NSTACK_MAX_EPOLL_INFO_NUM; pos++) + { + (void) nsep_recycle_epfd(&pool[pos], pid); + } + return 0; +} + +NSTACK_STATIC int nsep_recyle_epitem(u32 pid) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + struct epitem *pool = manager->epitemPool.pool; + + u32_t pos; + for (pos = 0; pos < NSTACK_MAX_EPITEM_NUM; pos++) + { + if (pool[pos].pid != pid) + continue; + + if (-1 == nsep_free_epitem(&pool[pos])) + return -1; + } + + return 0; +} + +NSTACK_STATIC int nsep_recyle_eventpoll(u32 pid) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + struct eventpoll *pool = manager->epollPool.pool; + + u32_t pos; + for (pos = 0; pos < NSTACK_MAX_EPOLL_INFO_NUM; pos++) + { + if (pool[pos].pid != pid) + continue; + + if (-1 == nsep_free_eventpoll(&pool[pos])) + return -1; + } + + return 0; +} + +NSTACK_STATIC int nsep_recyle_spl_conn_pool(u32 pid) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + struct spl_conn_pool *pool = manager->ep_connPoll.pool; + + u32_t pos; + for (pos = 0; pos < NSTACK_MAX_EPOLL_FD_NUM - 1; pos++) + { + if (pool[pos].pid != pid) + continue; + + if (-1 == nsep_free_ep_spl_conn_ring(&pool[pos])) + { + return -1; + } + } + + return 0; +} + +nsfw_rcc_stat nsep_recycle_resource(u32 exit_pid, void *pdata, u16 rec_type) +{ + NSSOC_LOGINF("pid:%u recycle", exit_pid); + //nsep_recyle_epInfo(exit_pid); + (void) nsep_recyle_epitem(exit_pid); + (void) nsep_recyle_eventpoll(exit_pid); + (void) nsep_recyle_spl_conn_pool(exit_pid); + return NSFW_RCC_CONTINUE; +} + +NSTACK_STATIC + nsfw_rcc_stat nsep_recyle_lock(u32 pid, void *pdata, u16 rec_type) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + nsep_epollInfo_t *pool = manager->infoPool.pool; + u32_t pos; + if (NULL != pool) + { + for (pos = 0; pos < NSTACK_MAX_EPOLL_INFO_NUM; pos++) + { + if (pid == pool[pos].epiLock.lock) + { + pool[pos].epiLock.lock = 0; + NSFW_LOGWAR("epiLock locked]pos=%u,pid=%u", pos, pid); + } + if (pid == pool[pos].freeLock.lock) + { + pool[pos].freeLock.lock = 0; + NSFW_LOGWAR("freelock locked]pos=%u,pid=%u", pos, pid); + } + } + } + + struct eventpoll *ev_pool = manager->epollPool.pool; + if (NULL != ev_pool) + { + for (pos = 0; pos < NSTACK_MAX_EPOLL_FD_NUM; pos++) + { + if (pid == ev_pool[pos].lock.lock) + { + ev_pool[pos].lock.lock = 0; + NSFW_LOGWAR("event_pollLock locked]pos=%u,pid=%u", pos, pid); + } + + if (pid == ev_pool[pos].sem.lock) + { + ev_pool[pos].sem.lock = 0; + NSFW_LOGWAR("event_pollLock sem]pos=%u,pid=%u", pos, pid); + } + } + } + + return NSFW_RCC_CONTINUE; +} + +int nstack_adpt_init(int flag) +{ + int ret; + if (0 == flag) + { + if (nstack_init_share_res() != 0) + { + return -1; + } + + ret = nsep_create_memory(); + } + else + { + if (nstack_attach_share_res() != 0) + { + return -1; + } + + /** + * the share memory for epoll is created and usedy be app, don't clear + * it in fault case. + */ + ret = nsep_adpt_attach_memory(); + } + + if (ret) + { + return ret; + } + void *pret = + nsfw_recycle_reg_obj(NSFW_REC_PRO_LOWEST, NSFW_REC_NSOCKET_EPOLL, + NULL); + if (!pret) + { + NSFW_LOGERR("regist recycle failed"); + return -1; + } + + (void) nsep_adpt_reg_res_mgr(); // not implemented now, no need to check return value + return 0; +} + +REGIST_RECYCLE_OBJ_FUN(NSFW_REC_NSOCKET_EPOLL, nsep_recycle_resource) +REGIST_RECYCLE_LOCK_REL(nsep_recyle_lock, NULL, NSFW_PROC_NULL) diff --git a/src/framework/event/epoll/nstack_eventpoll.c b/src/framework/event/epoll/nstack_eventpoll.c new file mode 100644 index 0000000..60fa8b4 --- /dev/null +++ b/src/framework/event/epoll/nstack_eventpoll.c @@ -0,0 +1,391 @@ +/* +* +* 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_eventpoll.h" +#include "nstack_log.h" +#include "nsfw_recycle_api.h" +#include "nstack_securec.h" +//#include "nstack_module.h" +//#include "nstack_sockops.h" +#include "nsfw_mem_api.h" +//#include "nstack_fd_mng.h" +//#include "nstack.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +static uint32_t g_nstack_epoll_fd_max = 0; +static uint32_t g_nstack_epoll_module_max = 0; + +#define EP_CHECK_SOCK_VALID(_sock) ((_sock) >= 0 && (u32_t)(_sock) < g_nstack_epoll_fd_max) + +void nsep_set_info_sock_map(int sock, nsep_epollInfo_t * info) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + if (NULL == manager->infoSockMap) + return; + + if (sock < 0 || (u32_t) sock >= g_nstack_epoll_fd_max) + return; + + manager->infoSockMap[sock] = info; +} + +nsep_epollInfo_t *nsep_get_info_by_sock(int sock) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + if ((NULL == manager) || (NULL == manager->infoSockMap)) + return NULL; + + if (sock < 0 || (u32_t) sock >= g_nstack_epoll_fd_max) + return NULL; + + return manager->infoSockMap[sock]; +} + +int nsep_alloc_info_with_sock(int nfd) +{ + + nsep_epollInfo_t *epInfo = NULL; + + if (!EP_CHECK_SOCK_VALID(nfd)) + { + return -1; + } + + if (-1 == nsep_alloc_epinfo(&epInfo)) + { + NSSOC_LOGERR("Alloc share info fail,[return]"); + return -1; + } + + epInfo->fd = nfd; + + nsep_set_info_sock_map(nfd, epInfo); + + return 0; +} + +void nsep_set_info_proto_fd(int fd, int modInx, int protoFD) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return; + + if (modInx < 0 || modInx >= g_nstack_epoll_module_max) + return; + + epInfo->protoFD[modInx] = protoFD; +} + +int nsep_get_info_proto_fd(int fd, int modInx) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return -1; + + return epInfo->protoFD[modInx]; +} + +void nsep_set_infomdix(int fd, int rmidx) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return; + + epInfo->rmidx = rmidx; +} + +int nsep_get_info_midx(int fd) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return -1; + + return epInfo->rmidx; +} + +void nsep_set_info_rlfd(int fd, int rlfd) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return; + + epInfo->rlfd = rlfd; +} + +int nsep_get_info_rlfd(int fd) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return -1; + + return epInfo->rlfd; +} + +void nsep_set_info_sleep_time(int fd, u32 sleepTime) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return; + + epInfo->sleepTime = sleepTime; +} + +int nsep_get_info_sleep_time(int fd) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return -1; + + return epInfo->sleepTime; +} + +/* if APP got killed while ep and + fdtype has been assigned but ep_conn not, the daemon-stack will trigger cordump when recycling + APP's ep resource. So we must make sure ep and ep_conn has been assigned before fdtype get NSTACK_EPOL_FD, + and combine them both to single function */ +void nsep_set_info_ep_resource(int fd, struct eventpoll *ep, + struct spl_conn_pool *ep_spl_conn) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return; + + epInfo->ep_conn = (struct spl_conn_pool *) SHMEM_ADDR_LTOSH(ep_spl_conn); + epInfo->ep = (struct eventpoll *) SHMEM_ADDR_LTOSH(ep); + + epInfo->fdtype = NSTACK_EPOL_FD; +} + +struct eventpoll *nsep_get_info_ep(int fd) +{ + nsep_epollInfo_t *epInfo = nsep_get_info_by_sock(fd); + + if (NULL == epInfo) + return NULL; + + return (struct eventpoll *) SHMEM_ADDR_SHTOL(epInfo->ep); +} + +int nsep_free_info_with_sock(int nfd) +{ + if ((u32_t) nfd >= g_nstack_epoll_fd_max || nfd < 0) + return -1; + + nsep_epollInfo_t *info = nsep_get_info_by_sock(nfd); + + if (NULL == info) + return 0; + + nsep_set_info_sock_map(nfd, NULL); + + NSSOC_LOGDBG("nsep_free_info_with_sock info:%p, nfd:%d", info, nfd); + /* If this not just used by linux, it should be freed in stackpool */ + if (-1 == nsep_free_epinfo(info)) + { + NSSOC_LOGERR("Error to free ep info"); + return -1; + } + return 0; +} + +/** + * @Function nsep_init_info_sock_map + * @Description initial map of epoll info and socket + * @param none + * @return 0 on success, -1 on error + */ +int nsep_init_info_sock_map(uint32_t epoll_fd_max, uint32_t module_max) +{ + nsep_epollManager_t *manager = nsep_get_manager(); + /*this function is necessary */ + + g_nstack_epoll_fd_max = epoll_fd_max; + g_nstack_epoll_module_max = module_max; + nsep_epollInfo_t **map = + (nsep_epollInfo_t **) malloc(g_nstack_epoll_fd_max * + sizeof(nsep_epollInfo_t *)); + + if (!map) + { + NSSOC_LOGERR("malloc epInfoPool fail"); + return -1; + } + + u32_t iindex; + for (iindex = 0; iindex < g_nstack_epoll_fd_max; iindex++) + { + map[iindex] = NULL; + } + + manager->infoSockMap = map; + + return 0; +} + +NSTACK_STATIC mzone_handle nsep_ring_lookup(char *name) +{ + if (NULL == name) + { + NSSOC_LOGERR("param error]name=%p", name); + return NULL; + } + + nsfw_mem_name mem_name; + /*modify strncpy to strcpy, because strlen(name) with strncpy is meaningless */ + if (EOK != strcpy_s(mem_name.aname, sizeof(mem_name.aname), name)) + { /*not null here */ + NSSOC_LOGERR("Error to lookup ring by name, strcpy fail]name=%s", + name); + return NULL; + } + mem_name.enowner = NSFW_PROC_MAIN; + mem_name.entype = NSFW_SHMEM; + + return nsfw_mem_ring_lookup(&mem_name); +} + +NSTACK_STATIC mzone_handle nsep_attach_shmem(char *name) +{ + if (NULL == name) + { + NSSOC_LOGERR("param error]name=%p", name); + return NULL; + } + + nsfw_mem_name mem_name; + /*add return value check */ + int retVal = strcpy_s(mem_name.aname, sizeof(mem_name.aname), name); + if (EOK != retVal) + { + NSSOC_LOGERR("strcpy_s failed]"); + return NULL; + } + mem_name.enowner = NSFW_PROC_MAIN; + mem_name.entype = NSFW_SHMEM; + + return nsfw_mem_zone_lookup(&mem_name); +} + +NSTACK_STATIC int nsep_attach_info_mem() +{ + mzone_handle hdl = nsep_attach_shmem(MP_NSTACK_EPOLL_INFO_NAME); + if (NULL == hdl) + return -1; + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->infoPool.pool = (nsep_epollInfo_t *) hdl; + + hdl = nsep_ring_lookup(MP_NSTACK_EPINFO_RING_NAME); + if (NULL == hdl) + { + NSSOC_LOGERR("Fail to loock up epoll info ring]name=%s", + MP_NSTACK_EPINFO_RING_NAME); + return -1; + } + + manager->infoPool.ring = hdl; + + return 0; +} + +NSTACK_STATIC int nsep_attach_epitem_mem() +{ + mzone_handle hdl = nsep_attach_shmem(MP_NSTACK_EPITEM_POOL); + if (NULL == hdl) + return -1; + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epitemPool.pool = (struct epitem *) hdl; + + hdl = nsep_ring_lookup(MP_NSTACK_EPITEM_RING_NAME); + if (NULL == hdl) + { + NSSOC_LOGERR("Fail to loock up epoll info ring]name=%s", + MP_NSTACK_EPITEM_RING_NAME); + return -1; + } + + manager->epitemPool.ring = hdl; + + return 0; +} + +NSTACK_STATIC int nsep_attach_eventpoll_mem() +{ + mzone_handle hdl = nsep_attach_shmem(MP_NSTACK_EVENTPOLL_POOL); + if (NULL == hdl) + return -1; + + nsep_epollManager_t *manager = nsep_get_manager(); + manager->epollPool.pool = (struct eventpoll *) hdl; + + hdl = nsep_ring_lookup(MP_NSTACK_EVENTPOOL_RING_NAME); + if (NULL == hdl) + { + NSSOC_LOGERR("Fail to loock up epoll info ring]name=%s", + MP_NSTACK_EVENTPOOL_RING_NAME); + return -1; + } + + manager->epollPool.ring = hdl; + + hdl = nsep_ring_lookup(MP_NSTACK_SPL_CONN_RING_NAME); + manager->ep_connPoll.ring = hdl; + + hdl = nsep_attach_shmem(MP_NSTACK_SPL_CONN_ARRAY_NAME); + manager->ep_connPoll.pool = hdl; + + return 0; +} + +int nsep_attach_memory() +{ + typedef int (*nsep_attachMemFunc_t) (void); + nsep_attachMemFunc_t attachFuncs[] = { nsep_attach_info_mem, + nsep_attach_epitem_mem, + nsep_attach_eventpoll_mem + }; + + int i = 0; + for (i = 0; + i < (int) (sizeof(attachFuncs) / sizeof(nsep_attachMemFunc_t)); i++) + { + if (-1 == attachFuncs[i] ()) + return -1; + } + + return 0; +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/event/epoll/nstack_eventpoll.h b/src/framework/event/epoll/nstack_eventpoll.h new file mode 100644 index 0000000..42e516a --- /dev/null +++ b/src/framework/event/epoll/nstack_eventpoll.h @@ -0,0 +1,384 @@ +/* +* +* 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_EVENTPOOL_H +#define _NSTACK_EVENTPOOL_H + +#include "ephlist.h" +#include "eprb_tree.h" +#include "types.h" +#include <semaphore.h> +#include <sys/epoll.h> +#include <stdio.h> +#include <stdlib.h> +#include "nstack_securec.h" +#include "nsfw_maintain_api.h" +#include "nstack_log.h" +#include "nsfw_mem_api.h" + +#include "nstack_sem.h" +#include "dmm_spinlock.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#define NSTACK_MAX_EPOLL_INFO_NUM CUR_CFG_SOCKET_NUM +#define NSTACK_MAX_EPITEM_NUM (NSTACK_MAX_EPOLL_INFO_NUM*2) +#define NSTACK_MAX_EPOLL_FD_NUM 1024U + +#define MP_NSTACK_EPOLL_INFO_NAME "nsep_info" +#define MP_NSTACK_EVENTPOLL_POOL "nsep_eventpoll" /* Pool of struct eventpoll */ +#define MP_NSTACK_EPITEM_POOL "nsep_epitem" /* Pool of struct epitem */ +#define MP_NSTACK_SPL_CONN_POOL "nsep_spl_conn_pool" +#define MP_NSTACK_SPL_CONN_ARRAY_NAME "nsep_spl_conn_pool_array" + +#define MP_NSTACK_EPINFO_RING_NAME "nsep_info_ring" +#define MP_NSTACK_EPITEM_RING_NAME "nsep_item_ring" +#define MP_NSTACK_EVENTPOOL_RING_NAME "nsep_event_ring" +#define MP_NSTACK_SPL_CONN_RING_NAME "nsep_spl_conn_ring" + +#define NSTACK_FORK_NUM 32 +#define NSTACK_EPOL_FD 1 + +#define NSEP_SMOD_MAX 8 + +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (NSEP_SMOD_MAX, 8) +/* *INDENT-ON* */ + +typedef struct +{ + u32 pid_used_size; + u32 pid_array[NSTACK_FORK_NUM]; +} nsep_pidinfo; + +struct eventpoll +{ + + /* + * Protect the this structure access + * This is for event add to ready list and poll out + */ + dmm_spinlock_t lock; + + /* + * This semaphore is used to ensure that files are not removed + * while epoll is using them. This is read-held during the event + * processing loop and it is write-held during the file cleanup + * path, the epoll file exit code and the ctl operations. + * When we do epoll_ctl, we write lock + * When we collecting data , we read lock + */ + dmm_spinlock_t sem; + + /* + * This sempaphore is used to block epoll_wait function + */ + ns_sem_type_t waitSem; + + /* List of ready file descriptors */ + struct ep_hlist rdlist; + + /* When poll data out, we need this list to store tmp epitems */ + u8 epoll_wait_pending; + u8 epoll_fork_flag; + u8 reserver_u8[6]; + + u64 epoll_wait_tick; + void *reserve[2]; + + /* RB-Tree root used to store mastered fd structs */ + struct ep_rb_root rbr; + + /* This specifies the file descriptor value of epoll instance, currenlty it is just used for debugging */ + int epfd; + u32 pid; + nsfw_res res_chk; +}; + +/* solve issue: epoll global lock in daemon-stack + cause daemon-stack message handle slowing */ +struct spl_conn_pool +{ + void *ring_hd; + nsfw_res res_chk; + pid_t pid; + u32 revents; + void *ring_reserve; +}; + +struct eventpoll_pool +{ + void *ring; + struct eventpoll *pool; +}; + +struct ep_conn_pool +{ + void *ring; + struct spl_conn_pool *pool; +}; + +typedef struct +{ + int iindex; + int iNext; + int fd; + i32 fdtype; /*0: socket fd, 1: epoll fd */ + i32 rlfd; /* copy of fdInf->rlfd */ + i32 rmidx; /* copy of fdInf->rmidx */ + i32 protoFD[NSEP_SMOD_MAX]; /* copy of fdInf->protoFD */// Here we need to set router infomations dependency + i32 epaddflag[NSEP_SMOD_MAX]; + struct eventpoll *ep; + dmm_spinlock_t epiLock; + dmm_spinlock_t freeLock; + struct ep_list epiList; /* This restore the epitem of this file descriptor */ + u32 sleepTime; //add for NSTACK_SEM_SLEEP + nsep_pidinfo pidinfo; + nsfw_res res_chk; + void *private_data; /*add for degbu, just used to record extern infomation, for example sbr conn */ + union + { + struct spl_conn_pool *ep_conn; + char ep_conn_flag; + }; + i32 reserv[2]; +} nsep_epollInfo_t; + +typedef struct +{ + void *ring; + nsep_epollInfo_t *pool; + char last_reserve[8]; //reserve for update +} nsep_infoPool_t; + +struct epitem +{ + struct ep_rb_node rbn; + + struct ep_hlist_node rdllink; + + struct spl_conn_pool *ep_spl; + void *ptr_reserve; + + volatile char app_poll_count; + volatile char spl_enter_count; + u16 reserve; + + struct eventpoll *ep; + + nsep_epollInfo_t *epInfo; + + struct epoll_event event; + + struct list_node fllink; + struct ep_hlist_node txlink; + + unsigned int revents; + + int fd; + u32 pid; + void *private_data; + nsfw_res res_chk; +}; + +struct epitem_pool +{ + void *ring; + struct epitem *pool; +}; + +typedef struct +{ + struct eventpoll_pool epollPool; + struct epitem_pool epitemPool; + struct ep_conn_pool ep_connPoll; + nsep_infoPool_t infoPool; + nsep_epollInfo_t **infoSockMap; // The map of epInfo and socket + + int checkEpollFD; +} nsep_epollManager_t; +extern nsep_epollManager_t g_epollMng; +#define nsep_get_manager() (&g_epollMng) + +extern int nsep_alloc_eventpoll(struct eventpoll **data); +extern int nsep_free_eventpoll(struct eventpoll *ep); +extern int nsep_alloc_epitem(struct epitem **data); +extern int nsep_free_epitem(struct epitem *data); +extern int nsep_alloc_epinfo(nsep_epollInfo_t ** data); +extern int nsep_free_epinfo(nsep_epollInfo_t * info); +extern int nsep_free_ep_spl_conn_ring(struct spl_conn_pool *data); +extern int nsep_alloc_ep_spl_conn_ring(struct spl_conn_pool **data); +extern int nsep_epitem_remove(nsep_epollInfo_t * pinfo, u32 pid); +extern void nsep_epctl_triggle(struct epitem *epi, nsep_epollInfo_t * info, + int triggle_ops); +extern struct epitem *nsep_find_ep(struct eventpoll *ep, int fd); +extern int nsep_epctl_add(struct eventpoll *ep, + nsep_epollInfo_t * epfd_epInfo, int fd, + struct epoll_event *events); +extern int nsep_epctl_del(struct eventpoll *ep, struct epitem *epi); +extern int nsep_epctl_mod(struct eventpoll *ep, + nsep_epollInfo_t * epInfo, + struct epitem *epi, struct epoll_event *events); +extern int nsep_ep_poll(struct eventpoll *ep, struct epoll_event *events, + int maxevents, struct spl_conn_pool *ep_conn); +extern void nsep_remove_epfd(nsep_epollInfo_t * info); +extern void nsep_close_epfd(struct eventpoll *ep); + +/** + * @Function nsep_init_info_sock_map + * @Description initial map of epoll info and socket + * @param none + * @return 0 on success, -1 on error + */ +extern int nsep_init_info_sock_map(uint32_t epoll_fd_max, + uint32_t module_max); +extern void nsep_set_info_sock_map(int sock, nsep_epollInfo_t * info); +extern nsep_epollInfo_t *nsep_get_info_by_sock(int sock); +extern int nsep_alloc_info_with_sock(int nfd); +extern void nsep_set_info_proto_fd(int fd, int modInx, int protoFD); +extern int nsep_get_info_proto_fd(int fd, int modInx); +extern void nsep_set_infomdix(int fd, int rmidx); +extern int nsep_get_info_midx(int fd); +extern void nsep_set_info_rlfd(int fd, int rlfd); +extern int nsep_get_info_rlfd(int fd); +extern void nsep_set_info_sleep_time(int fd, u32 sleepTime); +extern int nsep_get_info_sleep_time(int fd); +extern void nsep_set_info_ep_resource(int fd, struct eventpoll *ep, + struct spl_conn_pool *ep_spl_conn); +extern struct eventpoll *nsep_get_info_ep(int fd); +extern int nsep_free_info_with_sock(int sock); +extern int nstack_ep_unlink(struct eventpoll *ep, struct epitem *epi); +extern int nstack_epoll_event_dequeue(void *epi_addr, int events); + +/* Attach shared memory */ +extern int nsep_create_memory(); +extern int nsep_attach_memory(); +extern int nsep_ep_fdinfo_release(int sock); +extern int nsep_epoll_close(int sock); +extern void nsep_fork(u32_t ppid); + +static inline i32 nsep_for_pidinfo_init(nsep_pidinfo * pidinfo) +{ + int ret; + ret = memset_s(pidinfo, sizeof(*pidinfo), 0, sizeof(*pidinfo)); + if (EOK != ret) + { + NSSOC_LOGERR("memset_s failed]ret=%d", ret); + return -1; + } + return 0; +} + +static inline int nsep_add_pid(nsep_pidinfo * pidinfo, pid_t pid) +{ + int i; + + for (i = 0; i < NSTACK_FORK_NUM; i++) + { + if ((0 == pidinfo->pid_array[i]) + && (__sync_bool_compare_and_swap(&pidinfo->pid_array[i], 0, pid))) + { + if (pidinfo->pid_used_size < i + 1) + { + pidinfo->pid_used_size = i + 1; + } + return 0; + } + } + return -1; +} + +static inline int nsep_del_pid(nsep_pidinfo * pidinfo, pid_t pid) +{ + int i; + + for (i = 0; i < pidinfo->pid_used_size && i < NSTACK_FORK_NUM; i++) + { + if (pid == pidinfo->pid_array[i]) + { + pidinfo->pid_array[i] = 0; + return 0; + } + } + return -1; +} + +static inline int nsep_del_last_pid(nsep_pidinfo * pidinfo, pid_t pid) +{ + int i; + int count = 0; + int deleted = 0; + for (i = 0; i < pidinfo->pid_used_size && i < NSTACK_FORK_NUM; i++) + { + if (pid == pidinfo->pid_array[i]) + { + pidinfo->pid_array[i] = 0; + deleted = 1; + continue; + } + + if (pidinfo->pid_array[i] != 0) + { + ++count; + } + } + + if (!deleted) + { + return -1; + } + + return count; +} + +static inline int nsep_is_pid_exist(nsep_pidinfo * epinf, pid_t pid) +{ + int i; + + for (i = 0; i < epinf->pid_used_size && i < NSTACK_FORK_NUM; i++) + { + if (pid == epinf->pid_array[i]) + { + return 1; + } + } + return 0; +} + +static inline int nsep_is_pid_array_empty(nsep_pidinfo * epinf) +{ + int i; + for (i = 0; i < epinf->pid_used_size && i < NSTACK_FORK_NUM; i++) + { + if (epinf->pid_array[i] != 0) + { + return 0; + } + } + return 1; +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#endif /* _NSTACK_EVENTPOLL_H */ diff --git a/src/framework/event/epoll/nstack_sem.c b/src/framework/event/epoll/nstack_sem.c new file mode 100644 index 0000000..c457f32 --- /dev/null +++ b/src/framework/event/epoll/nstack_sem.c @@ -0,0 +1,433 @@ +/* +* +* 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 <errno.h> +#include "nstack_securec.h" +#include "types.h" +#include "nsfw_init_api.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mgr_com_api.h" +#include "nsfw_mem_api.h" +#include "nstack_log.h" +#include "nstack_sem.h" +#include "nstack_epoll_api.h" + +i32 ns_semphore_init(ns_sem_type_t * sem, i32 pshared, u32 value); +i32 ns_semphore_sem_timewait(ns_sem_type_t * sem, i32 timeout, u32 sleeptime); +i32 ns_semphore_sem_post(ns_sem_type_t * sem); +i32 ns_semphore_sem_destory(ns_sem_type_t * sem); +i32 ns_sysv_msg_init(ns_sem_type_t * sem, i32 pshared, u32 value); +i32 ns_sysv_msg_timewait(ns_sem_type_t * sem, i32 timeout, u32 sleeptime); /* milliseconds */ +i32 ns_sysv_msg_post(ns_sem_type_t * sem); +i32 ns_sysv_msg_destory(ns_sem_type_t * sem); + +#define NS_SYNC_SEM_SHARED_ARGS_MAX_SIZE 1024 +#define NS_SYNC_SEM_SHARED_MEM_NAME "NSTACK_FW_NS_SYNC_SEM_SHARED" +#define NSFW_SYNC_SEM_MODULE "nsfw_sync_sem" + +typedef struct ns_sync_mem_ifno_s +{ + ns_sync_type_t mode; + char parm[NS_SYNC_SEM_SHARED_ARGS_MAX_SIZE]; +} ns_sync_mem_ifno_t; + +ns_sync_sem_fun_t g_ns_sync_ops = { + NULL, + NULL, + NULL, + NULL +}; + +ns_sync_mem_ifno_t *g_sync_shared_args = NULL; + +int sem_current_time2msec(u64 * msec) +{ +#define SEM_MAX_U64_NUM ((u64)0xffffffffffffffff) + + struct timespec tout; + + if (0 != clock_gettime(CLOCK_MONOTONIC, &tout)) + { + NSSOC_LOGERR("Failed to get time, errno = %d", errno); + } + + if (SEM_MAX_U64_NUM / 1000 < (u64) tout.tv_sec) + { + NSSOC_LOGERR("tout.tv_sec is too large]tout.tv_sec=%ld", tout.tv_sec); + return -1; + } + + u64 sec2msec = 1000 * tout.tv_sec; + u64 nsec2msec = (u64) tout.tv_nsec / 1000000; + if (SEM_MAX_U64_NUM - sec2msec < nsec2msec) + { + NSSOC_LOGERR + ("nsec2msec plus sec2usec is too large]nsec2msec=%llu,usec2msec=%llu", + nsec2msec, sec2msec); + return -1; + } + + *msec = sec2msec + nsec2msec; + + return 0; +} + +/***************************************************************************** +* Prototype : ns_sync_mem_create +* Description : create a share mem with nstack and app +* Input : ns_sync_mem_ifno_t **mem +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +mzone_handle ns_sync_mem_create(size_t size) +{ + nsfw_mem_zone pmeminfo; + mzone_handle phandle; + int ret; + + pmeminfo.ireserv = 0; + pmeminfo.isocket_id = NSFW_SOCKET_ANY; + pmeminfo.lenth = size; + + ret = + strcpy_s(pmeminfo.stname.aname, sizeof(pmeminfo.stname.aname), + NS_SYNC_SEM_SHARED_MEM_NAME); + if (EOK != ret) + { + NSSOC_LOGERR("strcpy_s failed]name=%s,ret=%d", + NS_SYNC_SEM_SHARED_MEM_NAME, ret); + return NULL; + } + pmeminfo.stname.entype = NSFW_SHMEM; + + phandle = nsfw_mem_zone_create(&pmeminfo); + if (NULL == phandle) + { + NSSOC_LOGERR("create nstack sync memory failed]name=%s", + NS_SYNC_SEM_SHARED_MEM_NAME); + return NULL; + } + + return phandle; + +} + +/***************************************************************************** +* Prototype : ns_sync_mem_lookup +* Description : app look up the shared mem ,create by nstack +* Input : ns_sync_mem_ifno_t **mem +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +mzone_handle ns_sync_mem_lookup(char *str) +{ + nsfw_mem_name name; + + name.entype = NSFW_SHMEM; + name.enowner = NSFW_PROC_MAIN; + mzone_handle phandle; + + if (-1 == sprintf_s(name.aname, NSFW_MEM_NAME_LENTH, "%s", str)) + { + NSSOC_LOGERR("Error to attach sync]name=%s", str); + return NULL; + } + + phandle = nsfw_mem_zone_lookup(&name); + if (NULL == phandle) + { + NSSOC_LOGERR("create nstack sync memory failed]name=%s", str); + return NULL; + } + + return phandle; +} + +/***************************************************************************** +* Prototype : ns_sync_func_init +* Description : init function +* Input : u32 mode +* Output : None +* Return Value : NSTACK_STATIC void +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC void ns_sync_func_init(u32 mode) +{ + switch (mode) + { + case NS_SYNC_SYSV_MSG: + g_ns_sync_ops.ns_sync_sem_init = ns_sysv_msg_init; + g_ns_sync_ops.ns_sync_sem_post = ns_sysv_msg_post; + g_ns_sync_ops.ns_sync_sem_timedwait = ns_sysv_msg_timewait; + g_ns_sync_ops.ns_sync_sem_destroy = ns_sysv_msg_destory; + break; + case NS_SYNC_SEM_TRY: + default: + g_ns_sync_ops.ns_sync_sem_init = ns_semphore_init; + g_ns_sync_ops.ns_sync_sem_post = ns_semphore_sem_post; + g_ns_sync_ops.ns_sync_sem_timedwait = ns_semphore_sem_timewait; + g_ns_sync_ops.ns_sync_sem_destroy = ns_semphore_sem_destory; + break; + } + +} + +/***************************************************************************** +* Prototype : ns_sync_sem_module_init +* Description : read config file and shared mem +* Input : void * args +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 ns_sync_sem_module_init(int type, ns_sync_type_t mode) +{ + i32 ret = 0; + + switch (type) + { + + case 0: + g_sync_shared_args = + ns_sync_mem_create(sizeof(ns_sync_mem_ifno_t)); + if (NULL == g_sync_shared_args) + { + NSFW_LOGERR("%s create share mem failed", + NSFW_SYNC_SEM_MODULE); + ret = -1; + break; + } + g_sync_shared_args->mode = mode; + + ns_sync_func_init(g_sync_shared_args->mode); + break; + case 1: + g_sync_shared_args = + ns_sync_mem_lookup(NS_SYNC_SEM_SHARED_MEM_NAME); + if (NULL == g_sync_shared_args) + { + NSFW_LOGERR("%s lookup shared mem failed", + NSFW_SYNC_SEM_MODULE); + ret = -1; + break; + } + + ns_sync_func_init(g_sync_shared_args->mode); + break; + default: + if (type < NSFW_PROC_MAX) + { + NSFW_LOGERR("%s outof type", NSFW_SYNC_SEM_MODULE); + break; + } + ret = -1; + } + + NSFW_LOGDBG("%s init ret = %d", NSFW_SYNC_SEM_MODULE, ret); + return ret; +} + +/****************************************************************/ + +/* semaphore mode functions*/ +i32 ns_semphore_init(ns_sem_type_t * sem, i32 pshared, u32 value) +{ + return sem_init(&sem->semphore, pshared, value); +} + +/***************************************************************************** +* Prototype : ns_semphore_sem_timewait +* Description : semaphore wait +* Input : ns_sem_type_t *sem +* i32 timeout used ms, block if < 0 +* u32 sleeptime if timeout > 0, and sleeptime > 0 used sleep(sleeptime) and try agin +* ns_sem_process_type_t type +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 ns_semphore_sem_timewait(ns_sem_type_t * sem, i32 timeout, u32 sleeptime) +{ +#define FAST_SLEEP_TIME 10000 +#define SLOW_SLEEP_TIME 500000 +#define FAST_RETRY_COUNT 100 + + i32 retVal = 0; + u64 starttime; + u64 endtime; + u32 retry_count = 0; + + /* trywait */ + if (timeout == 0) + { + return sem_trywait(&sem->semphore); + } + + /* block when no event recv */ + if (timeout < 0) + { + return sem_wait(&sem->semphore); + } + + /* for timeout */ + if (sem_current_time2msec(&starttime)) + { + errno = ETIMEDOUT; + return -1; + } + while (1) + { + retVal = sem_trywait(&sem->semphore); + + if (retVal == 0) + { + break; + } + + if (sem_current_time2msec(&endtime)) + { + errno = ETIMEDOUT; + return -1; + } + + if (endtime < starttime || (endtime - starttime) > timeout) + { + errno = ETIMEDOUT; + return -1; + } + + /*app calling setsockopt to set time */ + if (sleeptime > 0) + { + long wait_sec; + long wait_nsec; + wait_sec = sleeptime / 1000000; + wait_nsec = 1000 * (sleeptime % 1000000); + sys_sleep_ns(wait_sec, wait_nsec); //g_sem_sleep_time + } + else if (retry_count < FAST_RETRY_COUNT) + { + sys_sleep_ns(0, FAST_SLEEP_TIME); + retry_count++; + } + else + { + sys_sleep_ns(0, SLOW_SLEEP_TIME); + } + } + + return retVal; + +} + +/* semaphore post */ +i32 ns_semphore_sem_post(ns_sem_type_t * sem) +{ + return sem_post(&sem->semphore); +} + +/*semaphore destory*/ +i32 ns_semphore_sem_destory(ns_sem_type_t * sem) +{ + return sem_destroy(&sem->semphore); +} + +/***************************************************************************** +* Prototype : ns_sysv_msg_init +* Description : init a system V msg +* Input : ns_sem_type_t *sem +* u32 pshared +* u32 value +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 ns_sysv_msg_init(ns_sem_type_t * sem, i32 pshared, u32 value) +{ +#define KEY_START 30000 + + unsigned short semInit = 0; + key_t key; + u32 *args; + + args = (u32 *) sem->args; + value = *args; + key = KEY_START + value; + sem->sysv.key = key; + sem->sysv.sock_id = semget(key, 1, IPC_CREAT | 0660); + sem->sysv.stack_id = -1; + + semctl(sem->sysv.sock_id, 0, SETALL, &semInit); + + return 0; +} + +/* system V timewait */ +i32 ns_sysv_msg_timewait(ns_sem_type_t * sem, i32 timeout, u32 sleeptime) /* milliseconds */ +{ + struct timespec tmout; + struct sembuf operations = { 0, -1, 0 }; + int id; + + id = semget(sem->sysv.key, 1, 0660); + if (-1 == id) + { + errno = EIDRM; + return -1; + } + + if (timeout < 0) + { + return semop(id, &operations, 1); + } + + tmout.tv_sec = timeout / 1000; + tmout.tv_nsec = (timeout % 1000) * 1000 * 1000; + return semtimedop(id, &operations, 1, &tmout); +} + +/* system V post */ +i32 ns_sysv_msg_post(ns_sem_type_t * sem) +{ + struct sembuf operations = { 0, 1, 0 }; + int id; + + id = semget(sem->sysv.key, 1, 0660); + if (-1 == id) + { + errno = EIDRM; + return -1; + } + + return semop(id, &operations, 1); +} + +/* destory system V msg */ +i32 ns_sysv_msg_destory(ns_sem_type_t * sem) +{ + key_t key; + + key = semget(sem->sysv.key, 1, 0660); + return semctl(key, 0, IPC_RMID); +} diff --git a/src/framework/event/epoll/nstack_sem.h b/src/framework/event/epoll/nstack_sem.h new file mode 100644 index 0000000..3f17667 --- /dev/null +++ b/src/framework/event/epoll/nstack_sem.h @@ -0,0 +1,74 @@ +/* +* +* 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_SYNC_H__ +#define __NSTACK_SYNC_H__ + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#include <sys/ipc.h> +#include <sys/sem.h> +#include <semaphore.h> +#include "types.h" +#include "nsfw_mgr_com_api.h" + +#define NS_SEM_ARGS_SIZE 8 + +typedef enum ns_sync_type_e +{ + NS_SYNC_SEM_TRY, + NS_SYNC_SYSV_MSG, + NS_SYNC_UNIX, /*need to do */ + NS_SYNC_MAX +} ns_sync_type_t; + +typedef struct ns_sysv_type_s +{ + key_t key; + i32 sock_id; + i32 stack_id; +} ns_sysv_t; + +typedef struct ns_sem_type_s +{ + sem_t semphore; + ns_sysv_t sysv; + char args[NS_SEM_ARGS_SIZE]; + +} ns_sem_type_t; + +typedef struct ns_sync_sem_fun_s +{ + i32(*ns_sync_sem_init) (ns_sem_type_t * sem, i32 pshared, u32 value); + i32(*ns_sync_sem_timedwait) (ns_sem_type_t * sem, i32 timeout, u32 sleeptime); /* milliseconds */ + i32(*ns_sync_sem_post) (ns_sem_type_t * sem); + i32(*ns_sync_sem_destroy) (ns_sem_type_t * sem); +} ns_sync_sem_fun_t; + +extern ns_sync_sem_fun_t g_ns_sync_ops; +extern i32 ns_sync_sem_module_init(int type, ns_sync_type_t mode); + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif diff --git a/src/framework/hal/hal.c b/src/framework/hal/hal.c index 49b1fb7..c9e31cf 100644 --- a/src/framework/hal/hal.c +++ b/src/framework/hal/hal.c @@ -14,14 +14,14 @@ * limitations under the License. */ -#include "common_sys_config.h" -#include "common_mem_mbuf.h" +#include <errno.h> #include "nstack_log.h" #include "nstack_securec.h" #include "hal.h" -#include "hal_api.h" +#include "nsfw_hal_api.h" #define HAL_ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) + /* *INDENT-OFF* */ static char hal_invalid_char_script[] = {'|', ';', '&', '$', '>', '<', '`', '\\', '\"', '\'', '(', ')', '[', ']', '~', '?', '*' @@ -39,26 +39,25 @@ static int netif_ops_init_flag = 0; netif_inst_t netif_tbl[HAL_MAX_NIC_NUM]; /* *INDENT-ON* */ -void -hal_io_adpt_register (const netif_ops_t * ops) +void hal_io_adpt_register(const netif_ops_t * ops) { - int icnt = 0; - if (netif_ops_init_flag == 0) + int icnt = 0; + if (netif_ops_init_flag == 0) { - (void) MEMSET_S (&netif_ops_table[0], sizeof (netif_ops_table), 0, - sizeof (netif_ops_table)); - netif_ops_init_flag = 1; + (void) memset_s(&netif_ops_table[0], sizeof(netif_ops_table), 0, + sizeof(netif_ops_table)); + netif_ops_init_flag = 1; } - for (icnt = 0; icnt < HAL_DRV_MAX; icnt++) + for (icnt = 0; icnt < HAL_DRV_MAX; icnt++) { - if (netif_ops_table[icnt] == 0) + if (netif_ops_table[icnt] == NULL) { - netif_ops_table[icnt] = ops; - break; + netif_ops_table[icnt] = ops; + break; } } - return; + return; } /***************************************************************************** @@ -73,43 +72,43 @@ hal_io_adpt_register (const netif_ops_t * ops) Calls : Called By : *****************************************************************************/ -int -hal_snprintf (char *buffer, size_t buflen, const char *format, ...) +int hal_snprintf(char *buffer, size_t buflen, const char *format, ...) { - int len; - va_list ap; + int len; + va_list ap; - /* check buffer validity */ - if (NULL == buffer || 0 == buflen) + /* need check buffer validity */ + if (NULL == buffer || 0 == buflen) { - goto einval_error; + goto einval_error; } - if (format == NULL) + if (format == NULL) { - buffer[0] = '\0'; + buffer[0] = '\0'; - goto einval_error; + goto einval_error; } - (void) va_start (ap, format); - len = VSNPRINTF_S (buffer, buflen, buflen - 1, format, ap); + (void) va_start(ap, format); /*no need to init */ + /*There are some unsafe function ,need to be replace with safe function */ + len = vsnprintf_s(buffer, buflen, buflen - 1, format, ap); - if (-1 == len) + if (-1 == len) { - va_end (ap); - goto einval_error; + va_end(ap); + goto einval_error; } - va_end (ap); + va_end(ap); - buffer[buflen - 1] = '\0'; + buffer[buflen - 1] = '\0'; - return len; + return len; -einval_error: - errno = EINVAL; - return -1; + einval_error: + errno = EINVAL; + return -1; } /***************************************************************************** @@ -121,99 +120,100 @@ einval_error: Calls : Called By : *****************************************************************************/ -int -hal_is_script_valid (const char *cmd) +int hal_is_script_valid(const char *cmd) { - unsigned int i; + unsigned int i; - if (cmd) + if (cmd) { - char *cmd_str = (char *) cmd; + char *cmd_str = (char *) cmd; - /* skip space */ - while (*cmd_str == ' ' || *cmd_str == '\t') + /* skip space */ + while (*cmd_str == ' ' || *cmd_str == '\t') { - cmd_str++; + cmd_str++; } - /* cmd can not start with ./ and ../ */ - for (i = 0; i < HAL_ARRAY_SIZE (hal_invalid_str_script_begin); i++) + /* cmd can not start with ./ and ../ */ + for (i = 0; i < HAL_ARRAY_SIZE(hal_invalid_str_script_begin); i++) { - if (strstr (cmd_str, hal_invalid_str_script_begin[i]) == cmd_str) + if (strstr(cmd_str, hal_invalid_str_script_begin[i]) == cmd_str) { - return 0; + return 0; } } - /* cmd can not include | ; $ and so on */ - for (i = 0; i < HAL_ARRAY_SIZE (hal_invalid_char_script); i++) + /* cmd can not include | ; $ and so on */ + for (i = 0; i < HAL_ARRAY_SIZE(hal_invalid_char_script); i++) { - if (strchr (cmd, hal_invalid_char_script[i])) + if (strchr(cmd, hal_invalid_char_script[i])) { - return 0; + return 0; } } - /* cmd can not include && || >> and so on */ - for (i = 0; i < HAL_ARRAY_SIZE (hal_invalid_str_script); i++) + /* cmd can not include && || >> and so on */ + for (i = 0; i < HAL_ARRAY_SIZE(hal_invalid_str_script); i++) { - if (strstr (cmd, hal_invalid_str_script[i])) + if (strstr(cmd, hal_invalid_str_script[i])) { - return 0; + return 0; } } - return 1; + return 1; } - return 0; + return 0; } -/***************************************************************************** - Prototype : hal_run_script - Description : run shell script - Input : const char* cmd - char* result_buf - size_t max_result_len - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -int -hal_run_script (const char *cmd, char *result_buf, size_t max_result_len) +int hal_run_script(const char *cmd, char *result_buf, size_t max_result_len) { - size_t n; - if (!cmd || !result_buf || max_result_len <= 1) + size_t n; + if (!cmd || !result_buf || max_result_len <= 1) { - return -1; + return -1; } - FILE *fd = popen (cmd, "r"); + FILE *fd = popen(cmd, "r"); - if (fd != NULL) + if (fd != NULL) { - n = fread (result_buf, sizeof (char), max_result_len - 1, fd); + n = fread(result_buf, sizeof(char), max_result_len - 1, fd); - if (n == 0) + if (n == 0) { - result_buf[0] = '\0'; + result_buf[0] = '\0'; } - else if ('\n' == result_buf[n - 1]) + else if ('\n' == result_buf[n - 1]) { - result_buf[n - 1] = '\0'; + result_buf[n - 1] = '\0'; } - /* make it null terminated */ - else + /* to make it null terminated */ + else { - result_buf[n] = '\0'; + result_buf[n] = '\0'; } - (void) pclose (fd); - return n; + (void) pclose(fd); + return n; } - return -1; + return -1; +} + +/* whether the nstack config file enable tso feature or not */ +static int config_enable_tso() +{ + /* tso not support for now */ + return 0; +} + +/* whether the nstack config file enable rx offload feature or not */ +static int config_enable_rx_offload() +{ + /* rx_offload enabled by config file */ + return 1; } /***************************************************************************** @@ -226,35 +226,34 @@ hal_run_script (const char *cmd, char *result_buf, size_t max_result_len) Calls : Called By : *****************************************************************************/ -int -hal_init_global (int argc, char **argv) +int hal_init_global(int argc, char **argv) { - int ret; - int netif_type; + int ret; + int netif_type; - ret = - MEMSET_S (netif_tbl, HAL_MAX_NIC_NUM * sizeof (netif_inst_t), 0, - HAL_MAX_NIC_NUM * sizeof (netif_inst_t)); - if (EOK != ret) + ret = + memset_s(netif_tbl, HAL_MAX_NIC_NUM * sizeof(netif_inst_t), 0, + HAL_MAX_NIC_NUM * sizeof(netif_inst_t)); + if (EOK != ret) { - NSHAL_LOGERR ("MEMSET_S failed"); - return -1; + NSHAL_LOGERR("memset_s failed"); + return -1; } - for (netif_type = 0; netif_ops_table[netif_type]; ++netif_type) + for (netif_type = 0; netif_ops_table[netif_type]; ++netif_type) { - if (netif_ops_table[netif_type]->init_global) + if (netif_ops_table[netif_type]->init_global) { - if (netif_ops_table[netif_type]->init_global (argc, argv)) + if (netif_ops_table[netif_type]->init_global(argc, argv)) { - NSHAL_LOGERR ("failed to init global]netif type=%d", - netif_type); - return -1; + NSHAL_LOGERR("failed to init global]netif type=%d", + netif_type); + return -1; } } } - return 0; + return 0; } /***************************************************************************** @@ -266,24 +265,24 @@ hal_init_global (int argc, char **argv) Calls : Called By : *****************************************************************************/ -int -hal_init_local () +int hal_init_local() { - int netif_type; + int netif_type; - for (netif_type = 0; netif_ops_table[netif_type]; ++netif_type) + for (netif_type = 0; netif_ops_table[netif_type]; ++netif_type) { - if (netif_ops_table[netif_type]->init_local) + if (netif_ops_table[netif_type]->init_local) { - if (netif_ops_table[netif_type]->init_local ()) + if (netif_ops_table[netif_type]->init_local()) { - NSHAL_LOGERR ("failed to init local]netif type=%d", netif_type); - return -1; + NSHAL_LOGERR("failed to init local]netif type=%d", + netif_type); + return -1; } } } - return 0; + return 0; } /***************************************************************************** @@ -295,96 +294,113 @@ hal_init_local () Calls : Called By : *****************************************************************************/ -hal_hdl_t -hal_get_invalid_hdl () +hal_hdl_t hal_get_invalid_hdl() { - return hal_invaldi_hdl; + return hal_invaldi_hdl; } -/***************************************************************************** - Prototype : hal_create - Description : create hal object - Input : const char* name - hal_netif_config_t* conf - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -hal_hdl_t -hal_create (const char *name, const char *nic_type, hal_netif_config_t * conf) +hal_hdl_t hal_create(const char *name, const char *nic_type, + hal_netif_config_t * conf) { - int ret = -1; - uint32_t netif_type; - netif_inst_t *inst; + int ret = -1; + uint32_t netif_type; + netif_inst_t *inst; + + /* which features netif support */ + struct hal_netif_hw_feature port_capa; - if ((NULL == name) || (NULL == conf)) + if ((NULL == name) || (NULL == conf)) { - NSHAL_LOGERR ("invalid para]name=%p,conf=%p", name, conf); - return hal_get_invalid_hdl (); + NSHAL_LOGERR("invalid para]name=%p,conf=%p", name, conf); + return hal_get_invalid_hdl(); } - inst = alloc_netif_inst (); + inst = alloc_netif_inst(); - if (NULL == inst) + if (NULL == inst) { - NSHAL_LOGERR ("failed to alloc netif inst]netif name=%s", name); + NSHAL_LOGERR("failed to alloc netif inst]netif name=%s", name); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - /*open */ - for (netif_type = 0; NULL != netif_ops_table[netif_type]; ++netif_type) + /*open */ + for (netif_type = 0; NULL != netif_ops_table[netif_type]; ++netif_type) { - ret = netif_ops_table[netif_type]->open (inst, name, nic_type); + ret = netif_ops_table[netif_type]->open(inst, name, nic_type); - if (0 == ret) + if (0 == ret) { - inst->ops = netif_ops_table[netif_type]; + inst->ops = netif_ops_table[netif_type]; - NSHAL_LOGINF ("netif ops]netif type=%u, netif name=%s", netif_type, - inst->ops->name); + NSHAL_LOGINF("netif ops]netif type=%u, netif name=%s", + netif_type, inst->ops->name); - break; + break; } } - if (ret != 0) + if (ret != 0) { - inst->state = NETIF_STATE_FREE; + inst->state = NETIF_STATE_FREE; - inst->ops = NULL; + inst->ops = NULL; - NSHAL_LOGERR ("open fail]netif name=%s", name); + NSHAL_LOGERR("open fail]netif name=%s", name); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - /*config */ - ret = inst->ops->config (inst, conf); + /* make sure which capabilities nic hardware support */ + ret = inst->ops->capability(inst, &port_capa); + if (ret != 0) + { + inst->state = NETIF_STATE_FREE; + + NSHAL_LOGERR("config fail]netif name=%s", name); + + return hal_get_invalid_hdl(); + } + + /* set port config per port capabilities */ + conf->hw_config.rx_csum_ip_flag = port_capa.rx_csum_ip + && config_enable_rx_offload()? 1 : 0; + conf->hw_config.rx_csum_l4_flag = port_capa.rx_csum_l4 + && config_enable_rx_offload()? 1 : 0; + conf->hw_config.tx_csum_ip_flag = port_capa.tx_csum_ip; + conf->hw_config.tx_csum_l4_flag = port_capa.tx_csum_tcp + && port_capa.tx_csum_udp; + conf->hw_config.tx_tso_flag = port_capa.tx_tso + && config_enable_tso()? 1 : 0; + + /*config */ + ret = inst->ops->config(inst, conf); - if (ret != 0) + if (ret != 0) { - inst->state = NETIF_STATE_FREE; + inst->state = NETIF_STATE_FREE; - NSHAL_LOGERR ("config fail]netif name=%s", name); + NSHAL_LOGERR("config fail]netif name=%s", name); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - /*start */ - ret = inst->ops->start (inst); + /* update netif offload value per config */ + inst->hw_config = conf->hw_config; - if (ret != 0) + /*start */ + ret = inst->ops->start(inst); + + if (ret != 0) { - inst->state = NETIF_STATE_FREE; + inst->state = NETIF_STATE_FREE; - NSHAL_LOGERR ("start fail]netif name=%s", name); + NSHAL_LOGERR("start fail]netif name=%s", name); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - return inst->hdl; + return inst->hdl; } /***************************************************************************** @@ -398,328 +414,229 @@ hal_create (const char *name, const char *nic_type, hal_netif_config_t * conf) Calls : Called By : *****************************************************************************/ -hal_hdl_t -hal_bond (const char *bond_name, uint8_t slave_num, hal_hdl_t slave_hdl[]) +hal_hdl_t hal_bond(const char *bond_name, uint8_t slave_num, + hal_hdl_t slave_hdl[]) { - int i, ret; - netif_inst_t *inst; - netif_inst_t *slave_inst[HAL_MAX_SLAVES_PER_BOND]; + int i, ret; + netif_inst_t *inst; + netif_inst_t *slave_inst[HAL_MAX_SLAVES_PER_BOND]; - if ((0 == slave_num) || (HAL_MAX_SLAVES_PER_BOND < slave_num) - || (NULL == bond_name) || (NULL == slave_hdl)) + if ((0 == slave_num) || (HAL_MAX_SLAVES_PER_BOND < slave_num) + || (NULL == bond_name) || (NULL == slave_hdl)) { - NSHAL_LOGERR ("invalid para]bond_name=%p,slave_num=%u,slave_hdl=%p,", - bond_name, slave_num, slave_hdl); + NSHAL_LOGERR("invalid para]bond_name=%p,slave_num=%u,slave_hdl=%p,", + bond_name, slave_num, slave_hdl); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - for (i = 0; i < slave_num; i++) + for (i = 0; i < slave_num; i++) { - slave_inst[i] = get_netif_inst (slave_hdl[i]); + slave_inst[i] = get_netif_inst(slave_hdl[i]); - if (NULL == slave_inst[i]) + if (NULL == slave_inst[i]) { - NSHAL_LOGERR ("invalid para slave_hdl]index=%d, slave_inst=%d", i, - slave_hdl[i].id); - return hal_get_invalid_hdl (); + NSHAL_LOGERR("invalid para slave_hdl]index=%d, slave_inst=%d", i, + slave_hdl[i].id); + return hal_get_invalid_hdl(); } } - inst = alloc_netif_inst (); + inst = alloc_netif_inst(); - if (NULL == inst) + if (NULL == inst) { - NSHAL_LOGERR ("failed to alloc nic inst]bond_name=%s", bond_name); - return hal_get_invalid_hdl (); + NSHAL_LOGERR("failed to alloc nic inst]bond_name=%s", bond_name); + return hal_get_invalid_hdl(); } - inst->ops = slave_inst[0]->ops; + inst->ops = slave_inst[0]->ops; + inst->hw_config = slave_inst[0]->hw_config; - ret = inst->ops->bond (inst, bond_name, slave_num, slave_inst); + ret = inst->ops->bond(inst, bond_name, slave_num, slave_inst); - if (0 != ret) + if (0 != ret) { - inst->state = NETIF_STATE_FREE; + inst->state = NETIF_STATE_FREE; - inst->ops = NULL; + inst->ops = NULL; - NSHAL_LOGERR ("bond netif fail]bond_name=%s", bond_name); + NSHAL_LOGERR("bond netif fail]bond_name=%s", bond_name); - return hal_get_invalid_hdl (); + return hal_get_invalid_hdl(); } - return inst->hdl; + return inst->hdl; } -/***************************************************************************** - Prototype : hal_close - Description : destroy hal object - Input : hal_hdl_t hdl - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -int -hal_close (hal_hdl_t hdl) +int hal_close(hal_hdl_t hdl) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return -1; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return -1; } - inst->state = NETIF_STATE_FREE; + inst->state = NETIF_STATE_FREE; - return inst->ops->close (inst); + return inst->ops->close(inst); } -/***************************************************************************** - Prototype : hal_stop - Description : stop recv packet - Input : hal_hdl_t hdl - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -int -hal_stop (hal_hdl_t hdl) +int hal_stop(hal_hdl_t hdl) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return -1; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return -1; } - return inst->ops->stop (inst); + return inst->ops->stop(inst); } -/***************************************************************************** - Prototype : hal_get_mtu - Description : get the mtu from nic - Input : hal_hdl_t hdl - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -uint32_t -hal_get_mtu (hal_hdl_t hdl) +uint32_t hal_get_mtu(hal_hdl_t hdl) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return 0; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return 0; } - return inst->ops->mtu (inst); + return inst->ops->mtu(inst); } -/***************************************************************************** - Prototype : hal_get_macaddr - Description : in normal mode, get the mac addr from nic - in bond mode1, get the mac addr from primary nic - Input : hal_hdl_t hdl - void* mac_addr - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -void -hal_get_macaddr (hal_hdl_t hdl, void *mac_addr) +void hal_get_macaddr(hal_hdl_t hdl, void *mac_addr) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return; } - (void) inst->ops->macaddr (inst, mac_addr); + (void) inst->ops->macaddr(inst, mac_addr); } /***************************************************************************** Prototype : hal_get_capability Description : get offload capability from nic Input : hal_hdl_t hdl - hal_netif_capa_t* info + strcuct hal_netif_hw_feature* info Output : None Return Value : Calls : Called By : *****************************************************************************/ -void -hal_get_capability (hal_hdl_t hdl, hal_netif_capa_t * info) +void hal_get_capability(hal_hdl_t hdl, struct hal_netif_hw_feature *info) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return; } - (void) inst->ops->capability (inst, info); + (void) inst->ops->capability(inst, info); } -/***************************************************************************** - Prototype : hal_recv_packet - Description : recv packet from nic - Input : hal_hdl_t hdl - uint16_t queue_id - struct common_mem_mbuf** rx_pkts - uint16_t nb_pkts - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -uint16_t -hal_recv_packet (hal_hdl_t hdl, uint16_t queue_id, - hal_mbuf_t ** rx_pkts, uint16_t nb_pkts) +uint16_t hal_recv_packet(hal_hdl_t hdl, uint16_t queue_id, + void **rx_pkts, uint16_t nb_pkts) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return 0; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return 0; } - return inst->ops->recv (inst, queue_id, rx_pkts, nb_pkts); + return inst->ops->recv(inst, queue_id, rx_pkts, nb_pkts); } -/***************************************************************************** - Prototype : hal_send_packet - Description : send packet to nic - Input : hal_hdl_t hdl - uint16_t queue_id - struct common_mem_mbuf** tx_pkts - uint16_t nb_pkts - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -uint16_t -hal_send_packet (hal_hdl_t hdl, uint16_t queue_id, - hal_mbuf_t ** tx_pkts, uint16_t nb_pkts) +uint16_t hal_send_packet(hal_hdl_t hdl, uint16_t queue_id, + void **tx_pkts, uint16_t nb_pkts) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return 0; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return 0; } - return inst->ops->send (inst, queue_id, tx_pkts, nb_pkts); + return inst->ops->send(inst, queue_id, tx_pkts, nb_pkts); } -/***************************************************************************** - Prototype : hal_link_status - Description : get link status form nic - Input : hal_hdl_t hdl - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -uint32_t -hal_link_status (hal_hdl_t hdl) +uint32_t hal_link_status(hal_hdl_t hdl) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return 0; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return 0; } - return inst->ops->link_status (inst); + return inst->ops->link_status(inst); } -/***************************************************************************** - Prototype : hal_stats - Description : get link statistics form nic - Input : hal_hdl_t hdl - hal_netif_stats_t* stats - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -int -hal_stats (hal_hdl_t hdl, hal_netif_stats_t * stats) +int hal_stats(hal_hdl_t hdl, hal_netif_stats_t * stats) { - netif_inst_t *inst; + netif_inst_t *inst; - if (NULL == stats) + if (NULL == stats) { - NSHAL_LOGERR ("invalid para"); - return -1; + NSHAL_LOGERR("invalid para"); + return -1; } - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return -1; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return -1; } - return inst->ops->stats (inst, stats); + return inst->ops->stats(inst, stats); } -/***************************************************************************** - Prototype : hal_stats_reset - Description : reset link statistics to nic - Input : hal_hdl_t hdl - Output : None - Return Value : - Calls : - Called By : -*****************************************************************************/ -void -hal_stats_reset (hal_hdl_t hdl) +void hal_stats_reset(hal_hdl_t hdl) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return; } - (void) inst->ops->stats_reset (inst); + (void) inst->ops->stats_reset(inst); } /***************************************************************************** @@ -734,28 +651,27 @@ hal_stats_reset (hal_hdl_t hdl) Calls : Called By : *****************************************************************************/ -int -hal_add_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, - void *mc_addr, uint32_t nb_mc_addr) +int hal_add_mcastaddr(hal_hdl_t hdl, void *mc_addr_set, + void *mc_addr, uint32_t nb_mc_addr) { - int ret; - netif_inst_t *inst; + int ret; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return -1; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return -1; } - ret = inst->ops->mcastaddr (inst, mc_addr_set, mc_addr, nb_mc_addr); - /* if set mcast addr failed, we have to manually add the mac addr to nic. */ - if (ret < 0) + ret = inst->ops->mcastaddr(inst, mc_addr_set, mc_addr, nb_mc_addr); + /* if set mcast addr failed, we have to manually add the mac addr to nic. */ + if (ret < 0) { - ret = inst->ops->add_mac (inst, mc_addr); + ret = inst->ops->add_mac(inst, mc_addr); } - return ret; + return ret; } /***************************************************************************** @@ -770,28 +686,27 @@ hal_add_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, Calls : Called By : *****************************************************************************/ -int -hal_del_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, - void *mc_addr, uint32_t nb_mc_addr) +int hal_del_mcastaddr(hal_hdl_t hdl, void *mc_addr_set, + void *mc_addr, uint32_t nb_mc_addr) { - int ret; - netif_inst_t *inst; + int ret; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return -1; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return -1; } - ret = inst->ops->mcastaddr (inst, mc_addr_set, mc_addr, nb_mc_addr); - /* if set mcast addr failed, we have to manually delete the mac addr from nic. */ - if (ret < 0) + ret = inst->ops->mcastaddr(inst, mc_addr_set, mc_addr, nb_mc_addr); + /* if set mcast addr failed, we have to manually delete the mac addr from nic. */ + if (ret < 0) { - ret = inst->ops->rmv_mac (inst, mc_addr); + ret = inst->ops->rmv_mac(inst, mc_addr); } - return ret; + return ret; } /***************************************************************************** @@ -804,20 +719,19 @@ hal_del_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, Calls : Called By : *****************************************************************************/ -void -hal_set_allmulti_mode (hal_hdl_t hdl, uint8_t enable) +void hal_set_allmulti_mode(hal_hdl_t hdl, uint8_t enable) { - netif_inst_t *inst; + netif_inst_t *inst; - inst = get_netif_inst (hdl); + inst = get_netif_inst(hdl); - if (inst == NULL) + if (inst == NULL) { - NSHAL_LOGERR ("netif does not exist]inst=%i", HAL_HDL_TO_ID (hdl)); - return; + NSHAL_LOGERR("netif does not exist]inst=%i", HAL_HDL_TO_ID(hdl)); + return; } - (void) inst->ops->allmcast (inst, enable); + (void) inst->ops->allmcast(inst, enable); } /***************************************************************************** @@ -829,35 +743,154 @@ hal_set_allmulti_mode (hal_hdl_t hdl, uint8_t enable) Calls : Called By : *****************************************************************************/ -uint32_t -hal_is_nic_exist (const char *name) +uint32_t hal_is_nic_exist(const char *name) { - char script_cmmd[HAL_SCRIPT_LENGTH]; - char result_buf[HAL_SCRIPT_LENGTH]; - int len_out; - int retval; + char script_cmmd[HAL_SCRIPT_LENGTH]; + char result_buf[HAL_SCRIPT_LENGTH]; + int len_out; + int retval; - if (!hal_is_script_valid (name)) + if (!hal_is_script_valid(name)) { - NSHAL_LOGERR ("nic name is not valid"); - return 0; + NSHAL_LOGERR("nic name is not valid"); + return 0; } - retval = - hal_snprintf (script_cmmd, sizeof (script_cmmd), - "sudo ifconfig -a | grep -w \"%s[ :]\"", name); - if (-1 == retval) + // no need to use sudo, as inquire has no need of high permission + retval = + hal_snprintf(script_cmmd, sizeof(script_cmmd), + "ifconfig -a | grep \"%s[ :]\"", name); + /* check return value */ + if (-1 == retval) { - NSHAL_LOGERR ("rte_snprintf failed]retval=%d", retval); - return 0; + NSHAL_LOGERR("hal_snprintf failed]retval=%d", retval); + return 0; } - len_out = hal_run_script (script_cmmd, result_buf, sizeof (result_buf) - 1); - /* buffer not initialized, should take length as decision */ - if (0 != len_out) + len_out = hal_run_script(script_cmmd, result_buf, sizeof(result_buf) - 1); + /* buffer not initialized, should take length as decision */ + if (0 >= len_out) + { + NSHAL_LOGERR("hal_run_script fail]len_out=%d", len_out); + return 0; + } + + return 1; +} + +int hal_check_rss(hal_hdl_t hdl, uint32_t saddr, uint32_t daddr, + uint16_t sport, uint16_t dport, uint16_t * thread_index) +{ + if (!thread_index) + { + NSHAL_LOGERR("thread_index is null"); + return -1; + } + + netif_inst_t *inst; + inst = get_netif_inst(hdl); + if (inst == NULL) + { + NSHAL_LOGERR("inst is null]inst=%d", HAL_HDL_TO_ID(hdl)); + return -1; + } + + return inst->ops->check_rss(inst, saddr, daddr, sport, dport, + thread_index); +} + +/***************************************************************************** +* Prototype : hal_bond_switch +* Description : bond switch API of hal layer +* Input : +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int hal_bond_switch(const char *bond_name) +{ + netif_inst_t *inst = get_netif_inst_by_name(bond_name); + if (!inst) + { + NSHAL_LOGERR("fail to get netif]name=%s", bond_name); + return -1; + } + + return inst->ops->port_switch(inst); +} + +/***************************************************************************** +* Prototype : hal_get_bond_primary +* Description : get bond primary API of hal layer +* Input : +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int hal_get_bond_primary(const char *bond_name) +{ + netif_inst_t *inst = get_netif_inst_by_name(bond_name); + if (!inst) + { + NSHAL_LOGERR("fail to get netif]name=%s", bond_name); + return -1; + } + + int primary_id = inst->ops->get_bond_primary(inst); + if (primary_id < 0) + { + NSHAL_LOGERR("get_bond_primary id fail]name=%s", bond_name); + return -1; + } + + int i; + for (i = 0; i < HAL_MAX_SLAVES_PER_BOND; i++) + { + if (primary_id == inst->data.dpdk_if.slave_port[i]) + { + return i; //found it! + } + } + + NSHAL_LOGERR + ("not found primary_id from slave_port array]primary_id=%d,slave[0]=%u,slave[1]=%u", + primary_id, inst->data.dpdk_if.slave_port[0], + inst->data.dpdk_if.slave_port[1]); + return -1; +} + +int hal_check_rss6(hal_hdl_t hdl, uint32_t saddr[4], uint32_t daddr[4], + uint16_t sport, uint16_t dport, uint16_t * thread_index) +{ + if (!thread_index) + { + NSHAL_LOGERR("thread_index is null"); + return -1; + } + + netif_inst_t *inst; + inst = get_netif_inst(hdl); + if (inst == NULL) + { + NSHAL_LOGERR("inst is null]inst=%d", HAL_HDL_TO_ID(hdl)); + return -1; + } + + return inst->ops->check_rss6(inst, saddr, daddr, sport, dport, + thread_index); +} + +struct hal_netif_hw_config *hal_get_netif_hw_config(hal_hdl_t hdl) +{ + netif_inst_t *inst; + inst = get_netif_inst(hdl); + if (inst == NULL) { - return 1; + NSHAL_LOGERR("inst is null]inst=%d", HAL_HDL_TO_ID(hdl)); + return NULL; } - return 0; + return &inst->hw_config; } diff --git a/src/framework/hal/hal.h b/src/framework/hal/hal.h index 5a8f51e..9d41bc2 100644 --- a/src/framework/hal/hal.h +++ b/src/framework/hal/hal.h @@ -18,8 +18,7 @@ #define _HAL_H_ #include <stdint.h> -#include "hal_api.h" -#include "nstack_log.h" +#include "nsfw_hal_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -29,150 +28,86 @@ extern "C" { #define HAL_DRV_MAX 32 -#define HAL_IO_REGISTER(name, ops) \ - static __attribute__((__constructor__)) void __hal_register##name(void) \ - {\ - hal_io_adpt_register(ops); \ - } \ - - #define HAL_MAX_PCI_ADDR_LEN 16 -#define HAL_MAX_DRIVER_NAME_LEN 128 - -#define HAL_MAX_PATH_LEN 4096 //max path length on linux is 4096 - #define HAL_SCRIPT_LENGTH 256 #define HAL_HDL_TO_ID(hdl) (hdl.id) -/* IO using DPDK interface */ -typedef struct dpdk_if -{ - uint8_t port_id; /**< DPDK port identifier */ - uint8_t slave_num; - uint8_t slave_port[HAL_MAX_SLAVES_PER_BOND]; - - uint32_t hw_vlan_filter:1; - uint32_t hw_vlan_strip:1; - uint32_t rsv30:30; - - uint32_t rx_queue_num; - uint32_t rx_ring_size[HAL_ETH_MAX_QUEUE_NUM]; - hal_mempool_t *rx_pool[HAL_ETH_MAX_QUEUE_NUM]; - - uint32_t tx_queue_num; - uint32_t tx_ring_size[HAL_ETH_MAX_QUEUE_NUM]; - - char pci_addr[HAL_MAX_PCI_ADDR_LEN]; - char nic_name[HAL_MAX_NIC_NAME_LEN]; - char nic_type[HAL_MAX_NIC_NAME_LEN]; - char driver_name[HAL_MAX_DRIVER_NAME_LEN]; -} dpdk_if_t; +extern netif_inst_t netif_tbl[HAL_MAX_NIC_NUM]; -typedef struct netif_inst +static inline netif_inst_t *alloc_netif_inst() { - enum - { - NETIF_STATE_FREE = 0, - NETIF_STATE_ACTIVE - } state; + int i; + netif_inst_t *inst; - hal_hdl_t hdl; + for (i = 0; i < HAL_MAX_NIC_NUM; ++i) + { + inst = &netif_tbl[i]; - const struct netif_ops *ops; /**< Implementation specific methods */ + if (NETIF_STATE_FREE == inst->state) + { + inst->state = NETIF_STATE_ACTIVE; - union - { - dpdk_if_t dpdk_if; /**< using DPDK for IO */ - } data; + inst->hdl.id = i; -} netif_inst_t; + return inst; + } + } -typedef struct netif_ops -{ - const char *name; - int (*init_global) (int argc, char **argv); - int (*init_local) (void); - int (*open) (netif_inst_t * inst, const char *name, const char *type); - int (*close) (netif_inst_t * inst); - int (*start) (netif_inst_t * inst); - int (*stop) (netif_inst_t * inst); - int (*bond) (netif_inst_t * inst, const char *bond_name, - uint8_t slave_num, netif_inst_t * slave[]); - uint32_t (*mtu) (netif_inst_t * inst); - int (*macaddr) (netif_inst_t * inst, void *mac_addr); - int (*capability) (netif_inst_t * inst, hal_netif_capa_t * info); - uint16_t (*recv) (netif_inst_t * inst, uint16_t queue_id, - hal_mbuf_t ** rx_pkts, uint16_t nb_pkts); - uint16_t (*send) (netif_inst_t * inst, uint16_t queue_id, - hal_mbuf_t ** tx_pkts, uint16_t nb_pkts); - uint32_t (*link_status) (netif_inst_t * inst); - int (*stats) (netif_inst_t * inst, hal_netif_stats_t * stats); - int (*stats_reset) (netif_inst_t * inst); - int (*config) (netif_inst_t * inst, hal_netif_config_t * conf); - int (*mcastaddr) (netif_inst_t * inst, void *mc_addr_set, - void *mc_addr, uint32_t nb_mc_addr); - int (*add_mac) (netif_inst_t * inst, void *mc_addr); - int (*rmv_mac) (netif_inst_t * inst, void *mc_addr); - int (*allmcast) (netif_inst_t * inst, uint8_t enable); -} netif_ops_t; + return NULL; -extern netif_inst_t netif_tbl[HAL_MAX_NIC_NUM]; +} -static inline netif_inst_t * -alloc_netif_inst () +static inline netif_inst_t *get_netif_inst(hal_hdl_t hdl) { - int i; - netif_inst_t *inst; + netif_inst_t *inst; - for (i = 0; i < HAL_MAX_NIC_NUM; ++i) + if (unlikely(!hal_is_valid(hdl))) { - inst = &netif_tbl[i]; + NSHAL_LOGERR("inst id is not valid]inst=%i, HAL_MAX_NIC_NUM=%d", + HAL_HDL_TO_ID(hdl), HAL_MAX_NIC_NUM); - if (NETIF_STATE_FREE == inst->state) - { - inst->state = NETIF_STATE_ACTIVE; + return NULL; + } - inst->hdl.id = i; + inst = &netif_tbl[HAL_HDL_TO_ID(hdl)]; - return inst; - } - } + if (unlikely((NETIF_STATE_ACTIVE != inst->state) || (NULL == inst->ops))) + { + NSHAL_LOGERR("netif is not active]inst=%i", HAL_HDL_TO_ID(hdl)); - return NULL; + return NULL; + } + return inst; } -static inline netif_inst_t * -get_netif_inst (hal_hdl_t hdl) +static inline netif_inst_t *get_netif_inst_by_name(const char *name) { - netif_inst_t *inst; + int i; + netif_inst_t *inst; - if (unlikely (!hal_is_valid (hdl))) + if (!name) { - NSHAL_LOGERR ("inst id is not valid]inst=%i, HAL_MAX_NIC_NUM=%d", - HAL_HDL_TO_ID (hdl), HAL_MAX_NIC_NUM); - - return NULL; + return NULL; } - inst = &netif_tbl[HAL_HDL_TO_ID (hdl)]; - - if (unlikely ((NETIF_STATE_ACTIVE != inst->state) || (NULL == inst->ops))) + for (i = 0; i < HAL_MAX_NIC_NUM; ++i) { - NSHAL_LOGERR ("netif is not active]inst=%i", HAL_HDL_TO_ID (hdl)); + inst = &netif_tbl[i]; - return NULL; + if (NETIF_STATE_ACTIVE == inst->state + && 0 == strncmp(name, inst->data.dpdk_if.nic_name, + HAL_MAX_NIC_NAME_LEN)) + { + return inst; + } } - return inst; -} + return NULL; -int hal_snprintf (char *buffer, size_t buflen, const char *format, ...); -int hal_is_script_valid (const char *cmd); -int hal_run_script (const char *cmd, char *result_buf, size_t max_result_len); -void hal_io_adpt_register (const netif_ops_t * ops); +} #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/common/include/compile_config.h b/src/framework/include/common/compile_config.h index 2ec5373..2ec5373 100644 --- a/src/framework/common/include/compile_config.h +++ b/src/framework/include/common/compile_config.h diff --git a/src/framework/common/include/compiling_check.h b/src/framework/include/common/compiling_check.h index e4a7538..41858b9 100644 --- a/src/framework/common/include/compiling_check.h +++ b/src/framework/include/common/compiling_check.h @@ -18,14 +18,16 @@ #define COMPILING_CHECK_H /* protect the value of macro whose value impacts the version - * compatibility, can't be changed!!! */ -#define COMPAT_PROTECT(name, value) \ -static inline char value_of_##name##_equal_to() \ -{ \ - char __dummy1[(name) - (value)]; \ - char __dummy2[(value) - (name)]; \ - return __dummy1[-1] + __dummy2[-1]; \ -} + * compatibility, can't be changed!!! */ + +#define COMPAT_PROTECT_RETURN(name, value) \ + \ + static inline char value_of_##name##_equal_to() \ + { \ + char __dummy1[(name) - (value)]; \ + char __dummy2[(value) - (name)]; \ + return __dummy1[-1] + __dummy2[-1]; \ + } /* check whether struct size is equal to a special value */ #define SIZE_OF_TYPE_EQUAL_TO(type, size) \ @@ -37,7 +39,7 @@ static inline char size_of_##type##_equal_to_##size() \ } /* check whether struct size is not equal to a special value */ -#define SIZE_OF_TYPE_UNEQUAL_TO(type, size) \ +#define SIZE_OF_TYPE_UNEQUAL_TO_RETURN(type, size) \ static inline char size_of_##type##_unequal_to_##size() \ { \ char __dummy1[0==(10/(sizeof(type)-size))]; \ @@ -45,7 +47,7 @@ static inline char size_of_##type##_unequal_to_##size() \ } /* check whether struct size is not larger than a special value */ -#define SIZE_OF_TYPE_NOT_LARGER_THAN(type, size) \ +#define SIZE_OF_TYPE_NOT_LARGER_THAN_RETURN(type, size) \ static inline char size_of_##type##_not_larger_than_##size() \ { \ char __dummy1[size - sizeof(type)]; \ @@ -54,7 +56,7 @@ static inline char size_of_##type##_not_larger_than_##size() \ /* check whether struct size + sizeof(void*) is not larger than a special value */ /* reserve 8 bytes for 64 bits pointers */ -#define SIZE_OF_TYPE_PLUS8_NOT_LARGER_THAN(type, size) \ +#define SIZE_OF_TYPE_PLUS8_NOT_LARGER_THAN_RETURN(type, size) \ static inline char size_of_##type##_not_larger_than_##size() \ { \ char __dummy1[size - sizeof(type) - sizeof(void*)]; \ @@ -62,7 +64,7 @@ static inline char size_of_##type##_not_larger_than_##size() \ } /* check whether struct size is not smaller than a special value */ -#define SIZE_OF_TYPE_NOT_SMALLER_THAN(type, size) \ +#define SIZE_OF_TYPE_NOT_SMALLER_THAN_RETURN(type, size) \ static inline char size_of_##type##_not_smaller_than_##size() \ { \ char __dummy1[sizeof(type) - size]; \ @@ -71,13 +73,13 @@ static inline char size_of_##type##_not_smaller_than_##size() \ /* check whether struct size is smaller than a special value */ #define SIZE_OF_TYPE_SMALLER_THAN(type, size) \ - SIZE_OF_TYPE_NOT_LARGER_THAN(type, size) \ - SIZE_OF_TYPE_UNEQUAL_TO(type, size) + SIZE_OF_TYPE_NOT_LARGER_THAN_RETURN(type, size) \ + SIZE_OF_TYPE_UNEQUAL_TO_RETURN(type, size) /* check whether struct size is larger than a special value */ #define SIZE_OF_TYPE_LARGER_THAN(type, size) \ - SIZE_OF_TYPE_NOT_SMALLER_THAN(type, size) \ - SIZE_OF_TYPE_UNEQUAL_TO(type, size) + SIZE_OF_TYPE_NOT_SMALLER_THAN_RETURN(type, size) \ + SIZE_OF_TYPE_UNEQUAL_TO_RETURN(type, size) /* check whether struct size is smaller than a special value, version 2 */ #define SIZE_OF_TYPE_SMALLER_THAN2(type, size) \ diff --git a/src/framework/common/include/dmm_fs.h b/src/framework/include/common/dmm_fs.h index 8fd9cd0..3a63550 100644 --- a/src/framework/common/include/dmm_fs.h +++ b/src/framework/include/common/dmm_fs.h @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_FS_H_ #define _DMM_FS_H_ - #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> -static size_t -dmm_file_size (int fd) +static inline size_t dmm_file_size(int fd) { - struct stat st; - if (fstat (fd, &st) < 0) - return 0; - return st.st_size; + struct stat st; + if (fstat(fd, &st) < 0) + return 0; + return (size_t) st.st_size; } #endif /* _DMM_FS_H_ */ diff --git a/src/framework/include/common/generic/dmm_atomic.h b/src/framework/include/common/generic/dmm_atomic.h new file mode 100644 index 0000000..0778e4a --- /dev/null +++ b/src/framework/include/common/generic/dmm_atomic.h @@ -0,0 +1,184 @@ +/* +* +* 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 _DMM_ATOMIC_H_ +#define _DMM_ATOMIC_H_ + +/* atomic 32 bit operation */ + +typedef struct +{ + volatile int cnt; +} dmm_atomic_t; + +inline static void dmm_atomic_set(dmm_atomic_t * a, int n) +{ + a->cnt = n; +} + +inline static int dmm_atomic_get(dmm_atomic_t * a) +{ + return a->cnt; +} + +inline static int dmm_atomic_add(dmm_atomic_t * a, int n) +{ + return __sync_fetch_and_add(&a->cnt, n); +} + +inline static int dmm_atomic_inc(dmm_atomic_t * a) +{ + return dmm_atomic_add(a, 1); +} + +inline static int dmm_atomic_sub(dmm_atomic_t * a, int n) +{ + return __sync_fetch_and_sub(&a->cnt, n); +} + +inline static int dmm_atomic_dec(dmm_atomic_t * a) +{ + return dmm_atomic_sub(a, 1); +} + +inline static int dmm_atomic_and(dmm_atomic_t * a, int n) +{ + return __sync_fetch_and_and(&a->cnt, n); +} + +inline static int dmm_atomic_or(dmm_atomic_t * a, int n) +{ + return __sync_fetch_and_or(&a->cnt, n); +} + +inline static int dmm_atomic_xor(dmm_atomic_t * a, int n) +{ + return __sync_fetch_and_xor(&a->cnt, n); +} + +inline static int dmm_atomic_swap(dmm_atomic_t * a, int o, int n) +{ + return __sync_bool_compare_and_swap(&a->cnt, o, n); +} + +inline static int dmm_atomic_add_return(dmm_atomic_t * a, int n) +{ + return __sync_add_and_fetch(&a->cnt, n); +} + +inline static int dmm_atomic_sub_return(dmm_atomic_t * a, int n) +{ + return __sync_sub_and_fetch(&a->cnt, n); +} + +inline static int dmm_atomic_and_return(dmm_atomic_t * a, int n) +{ + return __sync_and_and_fetch(&a->cnt, n); +} + +inline static int dmm_atomic_or_return(dmm_atomic_t * a, int n) +{ + return __sync_or_and_fetch(&a->cnt, n); +} + +inline static int dmm_atomic_xor_return(dmm_atomic_t * a, int n) +{ + return __sync_xor_and_fetch(&a->cnt, n); +} + +/* atomit 64bit operation */ + +typedef struct +{ + volatile long long int cnt; +} dmm_atomic64_t; + +inline static long long int dmm_atomic64_get(dmm_atomic64_t * a) +{ + return a->cnt; +} + +inline static void dmm_atomic64_set(dmm_atomic64_t * a, int n) +{ + a->cnt = n; +} + +inline static long long int dmm_atomic64_add(dmm_atomic64_t * a, int n) +{ + return __sync_fetch_and_add(&a->cnt, n); +} + +inline static int dmm_atomic64_inc(dmm_atomic64_t * a) +{ + return dmm_atomic64_add(a, 1); +} + +inline static long long int dmm_atomic64_sub(dmm_atomic64_t * a, int n) +{ + return __sync_fetch_and_sub(&a->cnt, n); +} + +inline static int dmm_atomic64_dec(dmm_atomic64_t * a) +{ + return dmm_atomic64_sub(a, 1); +} + +inline static long long int dmm_atomic64_and(dmm_atomic64_t * a, int n) +{ + return __sync_fetch_and_and(&a->cnt, n); +} + +inline static long long int dmm_atomic64_or(dmm_atomic64_t * a, int n) +{ + return __sync_fetch_and_or(&a->cnt, n); +} + +inline static long long int dmm_atomic64_xor(dmm_atomic64_t * a, int n) +{ + return __sync_fetch_and_xor(&a->cnt, n); +} + +inline static long long int dmm_atomic64_swap(dmm_atomic_t * a, int o, int n) +{ + return __sync_bool_compare_and_swap(&a->cnt, o, n); +} + +inline static long long int dmm_atomic64_add_return(dmm_atomic64_t * a, int n) +{ + return __sync_add_and_fetch(&a->cnt, n); +} + +inline static long long int dmm_atomic64_sub_return(dmm_atomic64_t * a, int n) +{ + return __sync_sub_and_fetch(&a->cnt, n); +} + +inline static long long int dmm_atomic64_and_return(dmm_atomic64_t * a, int n) +{ + return __sync_and_and_fetch(&a->cnt, n); +} + +inline static long long int dmm_atomic64_or_return(dmm_atomic64_t * a, int n) +{ + return __sync_or_and_fetch(&a->cnt, n); +} + +inline static long long int dmm_atomic64_xor_return(dmm_atomic64_t * a, int n) +{ + return __sync_xor_and_fetch(&a->cnt, n); +} + +#endif /* #ifndef _DMM_ATOMIC_H_ */ diff --git a/src/framework/common/include/generic/dmm_barrier.h b/src/framework/include/common/generic/dmm_barrier.h index b70fe85..5076702 100644 --- a/src/framework/common/include/generic/dmm_barrier.h +++ b/src/framework/include/common/generic/dmm_barrier.h @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_BARRIER_H_ #define _DMM_BARRIER_H_ -inline static void -dmm_barrier (void) +inline static void dmm_barrier(void) { - __sync_synchronize (); + __sync_synchronize(); } #endif /* #ifndef _DMM_BARRIER_H_ */ diff --git a/src/framework/include/common/generic/dmm_common.h b/src/framework/include/common/generic/dmm_common.h new file mode 100644 index 0000000..344f47e --- /dev/null +++ b/src/framework/include/common/generic/dmm_common.h @@ -0,0 +1,68 @@ +/* +* +* 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 _DMM_COMMON_H_ +#define _DMM_COMMON_H_ + +#include "dmm_config.h" + +#ifndef likely +#define likely(x) __builtin_expect(!!(x), 1) +#endif +#ifndef unlikely +#define unlikely(x) __builtin_expect(!!(x), 0) +#endif + +#define _dmm_packed __attribute__((__packed__)) +#define _dmm_aliened(a) __attribute__((__aligned__(a))) +#define _dmm_cache_aligned _dmm_aliened(DMM_CACHE_LINE_SIZE) + +#define DMM_ALIGN(x, a) (((x) + ((a) - 1)) / (a) * (a)) +#define dmm_align(x, a) ({ \ + typeof(x) _a = (a); \ + ((x) + (_a - 1)) / _a * _a; \ +}) + +#ifndef offsetof +#define offsetof(type, member) ((size_t)((type *)0)->member) +#endif + +inline static unsigned int dmm_align32pow2(unsigned int v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + + return v + 1; +} + +inline static unsigned long long dmm_align64pow2(unsigned long long v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v |= v >> 32; + + return v + 1; +} + +#endif diff --git a/src/framework/include/dmm_config.h b/src/framework/include/common/generic/dmm_config.h index 43a06ab..657ecd8 100644 --- a/src/framework/include/dmm_config.h +++ b/src/framework/include/common/generic/dmm_config.h @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_CONFIG_H_ #define _DMM_CONFIG_H_ @@ -21,23 +22,31 @@ #endif #ifndef DMM_MAIN_SHARE_TYPE -#define DMM_MAIN_SHARE_TYPE DMM_SHARE_FSHM /* 1 */ +#define DMM_MAIN_SHARE_TYPE DMM_SHARE_FSHM #endif #ifndef DMM_MAIN_SHARE_SIZE #define DMM_MAIN_SHARE_SIZE 1024 /* Megabyte */ #endif +#ifndef DMM_MAIN_SHARE_BASE +#define DMM_MAIN_SHARE_BASE 0x700080000000 /* fixed base address */ +#endif + #ifndef DMM_SHARE_TYPE -#define DMM_SHARE_TYPE DMM_SHARE_FSHM /* 1 */ +#define DMM_SHARE_TYPE DMM_SHARE_FSHM #endif #ifndef DMM_SHARE_SIZE -#define DMM_SHARE_SIZE 16 /* Megabyte */ +#define DMM_SHARE_SIZE 8 /* Megabyte */ #endif #ifndef DMM_HUGE_DIR -#define DMM_HUGE_DIR "/mnt/dmm-huge" +#define DMM_HUGE_DIR "/mnt/nstackhuge" +#endif + +#ifndef DMM_CACHE_LINE_SIZE +#define DMM_CACHE_LINE_SIZE 64 #endif #endif /* _DMM_CONFIG_H_ */ diff --git a/src/framework/common/include/generic/dmm_pause.h b/src/framework/include/common/generic/dmm_pause.h index 56c60f0..65b60db 100644 --- a/src/framework/common/include/generic/dmm_pause.h +++ b/src/framework/include/common/generic/dmm_pause.h @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_PAUSE_H_ #define _DMM_PAUSE_H_ #include <emmintrin.h> -inline static void -dmm_pause (void) +inline static void dmm_pause(void) { - _mm_pause (); + _mm_pause(); } #define DMM_PAUSE_WHILE(cond) do { dmm_pause(); } while (!!(cond)) diff --git a/src/framework/common/include/generic/dmm_rwlock.h b/src/framework/include/common/generic/dmm_rwlock.h index 93570f1..2b9ec8b 100644 --- a/src/framework/common/include/generic/dmm_rwlock.h +++ b/src/framework/include/common/generic/dmm_rwlock.h @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_RWLOCK_H_ #define _DMM_RWLOCK_H_ @@ -20,57 +21,52 @@ typedef struct { - volatile int lock; + volatile int lock; } dmm_rwlock_t; #define DMM_RWLOCK_INIT { 0 } -inline static void -dmm_rwlock_init (dmm_rwlock_t * rwlock) +inline static void dmm_rwlock_init(dmm_rwlock_t * rwlock) { - rwlock->lock = 0; + rwlock->lock = 0; } -inline static void -dmm_read_lock (dmm_rwlock_t * rwlock) +inline static void dmm_read_lock(dmm_rwlock_t * rwlock) { - int val; + int val; - do + do { - if ((val = rwlock->lock) < 0) + if ((val = rwlock->lock) < 0) { - dmm_pause (); - continue; + dmm_pause(); + continue; } } - while (!__sync_bool_compare_and_swap (&rwlock->lock, val, val + 1)); + while (!__sync_bool_compare_and_swap(&rwlock->lock, val, val + 1)); } -inline static void -dmm_read_unlock (dmm_rwlock_t * rwlock) +inline static void dmm_read_unlock(dmm_rwlock_t * rwlock) { - __sync_sub_and_fetch (&rwlock->lock, 1); + __sync_sub_and_fetch(&rwlock->lock, 1); } -inline static void -dmm_write_lock (dmm_rwlock_t * rwlock) +inline static void dmm_write_lock(dmm_rwlock_t * rwlock) { - do + do { - if (rwlock->lock != 0) + if (rwlock->lock != 0) { - dmm_pause (); - continue; + dmm_pause(); + continue; } } - while (!__sync_bool_compare_and_swap (&rwlock->lock, 0, -1)); + while (!__sync_bool_compare_and_swap(&rwlock->lock, 0, -1)); } -inline static void -dmm_write_unlock (dmm_rwlock_t * rwlock) +inline static void dmm_write_unlock(dmm_rwlock_t * rwlock) { - rwlock->lock = 0; + rwlock->lock = 0; } #endif /* #ifndef _DMM_RWLOCK_H_ */ diff --git a/src/framework/include/common/generic/dmm_spinlock.h b/src/framework/include/common/generic/dmm_spinlock.h new file mode 100644 index 0000000..5723ecf --- /dev/null +++ b/src/framework/include/common/generic/dmm_spinlock.h @@ -0,0 +1,119 @@ +/* +* +* 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 _DMM_SPINLOCK_H_ +#define _DMM_SPINLOCK_H_ + +#include "dmm_pause.h" +#include "pid_common.h" +#include "nsfw_branch_prediction.h" +#include "nstack_log.h" + +#define DMM_SPINLOCK_MALLOC(sys_sem,count) \ +{ \ + dmm_spin_init(&(sys_sem)); \ + /*not problem*/\ + if (!(count)) \ + /*not problem*/\ + { \ + dmm_spin_lock(&(sys_sem)); \ + } \ +} + +typedef struct +{ + volatile int lock; +} dmm_spinlock_t; + +inline static void dmm_spin_init(dmm_spinlock_t * spinlock) +{ + spinlock->lock = 0; +} + +static inline int dmm_spin_trylock_with(dmm_spinlock_t * spinlock, int value) +{ + return __sync_bool_compare_and_swap(&spinlock->lock, 0, value); +} + +static inline void dmm_spin_lock_with(dmm_spinlock_t * spinlock, int value) +{ + while (!dmm_spin_trylock_with(spinlock, value)) + { + DMM_PAUSE_WHILE(spinlock->lock); + } +} + +inline static void dmm_spin_lock(dmm_spinlock_t * spinlock) +{ + dmm_spin_lock_with(spinlock, 1); +} + +inline static int dmm_spin_trylock(dmm_spinlock_t * spinlock) +{ + return dmm_spin_trylock_with(spinlock, 1); +} + +//replace sys_sem_s_signal +inline static void dmm_spin_unlock(dmm_spinlock_t * spinlock) +{ + __sync_lock_release(&spinlock->lock); +} + +//replace sys_arch_trylock_with_pid +static inline int dmm_spin_trylock_with_pid(dmm_spinlock_t * sem, int t_us) +{ + if (unlikely(SYS_HOST_INITIAL_PID == g_sys_host_pid)) + (void) sys_get_hostpid_from_file(getpid()); + + if (dmm_spin_trylock_with(sem, g_sys_host_pid)) + { + return 0; + } + + while (t_us > 0) + { + --t_us; + sys_sleep_ns(0, 1000); + if (dmm_spin_trylock_with(sem, g_sys_host_pid)) + { + return 0; + } + } + + return -1; +} + +//replace sys_arch_sem_trywait_s_v2 +static inline int dmm_spinlock_trylock(dmm_spinlock_t * sl) +{ + int lockval = 1; + + asm volatile ("xchg %[locked], %[lockval]":[locked] "=m"(sl->lock), + [lockval] "=q"(lockval):"[lockval]"(lockval):"memory"); + + return lockval == 0; +} + +static inline u32_t dmm_spin_lock_with_pid(dmm_spinlock_t * sem) +{ + if (SYS_HOST_INITIAL_PID == g_sys_host_pid) + { + (void) sys_get_hostpid_from_file(getpid()); + } + dmm_spin_lock_with(sem, g_sys_host_pid); + return 0; +} +#endif /* #ifndef _DMM_SPINLOCK_H_ */ diff --git a/src/framework/common/include/list.h b/src/framework/include/common/list.h index 01860bc..06b558b 100644 --- a/src/framework/common/include/list.h +++ b/src/framework/include/common/list.h @@ -32,15 +32,15 @@ extern "C" { struct list_head { - union - { - struct list_head *next; - }; - - union - { - struct list_head *prev; - }; + union + { + struct list_head *next; + }; + + union + { + struct list_head *prev; + }; }; struct hlist_node @@ -48,32 +48,30 @@ struct hlist_node /** * @pprev: point the previous node's next pointer */ - union - { - struct hlist_node *next; - }; - - union - { - struct hlist_node **pprev; - }; + union + { + struct hlist_node *next; + }; + + union + { + struct hlist_node **pprev; + }; }; struct hlist_head { - struct hlist_node *first; + struct hlist_node *first; }; #define list_entry(ptr, type, member) \ - container_of(ptr, type, member) + container_of(ptr, type, member) #define list_for_each_entry_type(tpos, typeof_tpos,pos, head, member) \ for (pos = ((head)->next); \ pos && pos != (head) && ({tpos = list_entry(pos, typeof_tpos, member); 1;}); \ pos = ((pos)->next)) -#define LINT_LIST() - #define list_for_each_entry(tpos, pos, head, member) \ for (pos = ((head)->next); \ pos && pos != (head) && ({tpos = list_entry(pos, typeof(*tpos), member); 1;}); \ @@ -93,28 +91,28 @@ struct hlist_head /* * @head: the list to test. */ -inline void list_add (struct list_head *newp, struct list_head *head); -inline void list_link (struct list_head *newhead, struct list_head *head); -inline void list_add_tail (struct list_head *newp, struct list_head *head); -inline int list_empty (const struct list_head *head); -inline void list_del (struct list_head *entry); -inline struct list_head *list_get_first (struct list_head *head); -inline void hlist_del_init (struct hlist_node *n); +inline void list_add(struct list_head *newp, struct list_head *head); +inline void list_link(struct list_head *newhead, struct list_head *head); +inline void list_add_tail(struct list_head *newp, struct list_head *head); +inline int list_empty(const struct list_head *head); +inline void list_del(struct list_head *entry); +inline struct list_head *list_get_first(struct list_head *head); +inline void hlist_del_init(struct hlist_node *n); struct hlist_tail { - struct hlist_node *end; + struct hlist_node *end; }; struct hlist_ctl { - struct hlist_head head; - struct hlist_tail tail; + struct hlist_head head; + struct hlist_tail tail; }; #define INIT_HLIST_CTRL(ptr) {(ptr)->head.first = NULL; (ptr)->tail.end = NULL;} -inline int hlist_empty (const struct hlist_head *h); -inline void hlist_add_head (struct hlist_node *n, struct hlist_head *h); +inline int hlist_empty(const struct hlist_head *h); +inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h); #define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL) #define INIT_HLIST_NODE(ptr) {(ptr)->next = NULL; (ptr)->pprev = NULL;} @@ -145,7 +143,7 @@ inline void hlist_add_head (struct hlist_node *n, struct hlist_head *h); pos && ({tpos = hlist_entry(pos, typeof_tpos, member); 1;}); \ pos = pos->next) -inline void hlist_del_init (struct hlist_node *n); +inline void hlist_del_init(struct hlist_node *n); /** * next must be != NULL @@ -154,7 +152,7 @@ inline void hlist_del_init (struct hlist_node *n); * @n: new node * @next: node in the hlist */ -inline void hlist_add_before (struct hlist_node *n, struct hlist_node *next); +inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next); /** * next must be != NULL @@ -163,14 +161,14 @@ inline void hlist_add_before (struct hlist_node *n, struct hlist_node *next); * @n: node in the hlist * @next: new node */ -inline void hlist_add_after (struct hlist_node *n, struct hlist_node *next); +inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next); /* add after the head */ -inline void hlist_add_head (struct hlist_node *n, struct hlist_head *h); +inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h); -inline int hlist_unhashed (const struct hlist_node *h); +inline int hlist_unhashed(const struct hlist_node *h); -inline int hlist_empty (const struct hlist_head *h); +inline int hlist_empty(const struct hlist_head *h); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/common/pid_common.h b/src/framework/include/common/pid_common.h new file mode 100644 index 0000000..a8f5572 --- /dev/null +++ b/src/framework/include/common/pid_common.h @@ -0,0 +1,82 @@ +/* +* +* 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 _PIA_COMMON_H_ +#define _PIA_COMMON_H_ + +#include <sys/types.h> +#include <stdint.h> +#include <unistd.h> + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#ifndef u32_t +typedef uint32_t u32_t; +#endif + +#define SYS_HOST_INITIAL_PID 1 + +#define READ_FILE_BUFLEN 512 +#define BUF_SIZE_FILEPATH 256 + +#define MAX_GET_PID_TIME 10 + +extern volatile pid_t g_sys_host_pid; + +pid_t sys_get_hostpid_from_file(pid_t pid); +pid_t get_hostpid_from_file(u32_t pid); +pid_t get_hostpid_from_file_one_time(u32_t pid); +void get_exec_name_by_pid(pid_t pid, char *task_name, int task_name_len); +pid_t updata_sys_pid(); + +static inline pid_t get_sys_pid() +{ + if (SYS_HOST_INITIAL_PID == g_sys_host_pid) + (void) sys_get_hostpid_from_file(getpid()); + return g_sys_host_pid; +} + +#ifndef u64 +typedef unsigned long long u64; +#endif + +typedef struct nsfw_app_info +{ + int nsocket_fd; + int sbr_fd; + + int hostpid; + int pid; + int ppid; + int tid; + u64 extend_member_bit; +} nsfw_app_info_t; + +#define _dmm_packed __attribute__((__packed__)) +#define _dmm_aliened(a) __attribute__((__aligned__(a))) +#define _dmm_cache_aligned _dmm_aliened(DMM_CACHE_LINE_SIZE) + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif diff --git a/src/framework/common/include/pidinfo.h b/src/framework/include/common/pidinfo.h index 7438756..d97fa1d 100644 --- a/src/framework/common/include/pidinfo.h +++ b/src/framework/include/common/pidinfo.h @@ -26,18 +26,19 @@ extern "C" { #endif #define NSFW_MAX_FORK_NUM 32 + typedef struct { - u32 used_size; - u32 apid[NSFW_MAX_FORK_NUM]; + u32 used_size; + u32 apid[NSFW_MAX_FORK_NUM]; } nsfw_pidinfo; -inline i32 nsfw_pidinfo_init (nsfw_pidinfo * pidinfo); -inline int nsfw_add_pid (nsfw_pidinfo * pidinfo, u32 pid); -inline int nsfw_del_pid (nsfw_pidinfo * pidinfo, u32 pid); -inline int nsfw_del_last_pid (nsfw_pidinfo * pidinfo, u32 pid); -inline int nsfw_pid_exist (nsfw_pidinfo * pidinfo, u32 pid); -inline int nsfw_pidinfo_empty (nsfw_pidinfo * pidinfo); +inline i32 nsfw_pidinfo_init(nsfw_pidinfo * pidinfo); +inline int nsfw_add_pid(nsfw_pidinfo * pidinfo, u32 pid); +inline int nsfw_del_pid(nsfw_pidinfo * pidinfo, u32 pid); +inline int nsfw_del_last_pid(nsfw_pidinfo * pidinfo, u32 pid); +inline int nsfw_pid_exist(nsfw_pidinfo * pidinfo, u32 pid); +inline int nsfw_pidinfo_empty(nsfw_pidinfo * pidinfo); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/dmm_ring.h b/src/framework/include/dmm_ring.h new file mode 100644 index 0000000..003f0ac --- /dev/null +++ b/src/framework/include/dmm_ring.h @@ -0,0 +1,100 @@ +/* +* +* 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 _DMM_RING_H_ +#define _DMM_RING_H_ + +#include <stdint.h> + +#include "dmm_atomic.h" +#include "dmm_pause.h" +#include "dmm_barrier.h" +#include "dmm_common.h" +#include "types.h" + +#define DMM_RING_MAX_NUM 0x7FFFFFFE /* 2,147,483,646 */ + +#define DMM_RING_INIT_SP 0x0001 +#define DMM_RING_INIT_SC 0x0002 +#define DMM_RING_INIT_MPMC 0 +#define DMM_RING_INIT_SPSC (DMM_RING_INIT_SP | DMM_RING_INIT_SC) + +struct dmm_ring +{ + u8 memtype; //share, no share + u8 ringflag; //scmp, scsp, mcsp,mcmp + int size; //size of ring + size_t eltsize; //for sppool, it is the size of per buf, if is ring, eltsize is zero. + uint32_t flag; + + volatile int prod_head; + volatile int prod_tail; + int is_sp; + int _prod_pad; + + volatile int cons_head; + volatile int cons_tail; + int is_sc; + int _cons_pad; +} _dmm_cache_aligned; + +void dmm_ring_dump(struct dmm_ring *ring, int list); +int dmm_ring_init(struct dmm_ring *ring, int num, size_t eltsize, int flag, + unsigned char memtype); +int dmm_pool_init(struct dmm_ring *pool, size_t elt_size, int num, int flag, + unsigned char memtype); +int dmm_mem_enqueue(void *ring, void *p); +int dmm_mem_dequeue(void *ring, void **p); + +inline static size_t dmm_ring_bufsize(int num) +{ + size_t size = sizeof(struct dmm_ring); + + size += (sizeof(void *) * (num + 1)); + + return dmm_align(size, DMM_CACHE_LINE_SIZE); +} + +inline static size_t dmm_pool_arraysize(int num, size_t elt_size) +{ + const size_t size = elt_size * num; + return dmm_align(size, DMM_CACHE_LINE_SIZE); +} + +inline static size_t dmm_pool_bufsize(int num, size_t elt_size) +{ + return dmm_ring_bufsize(num) + dmm_pool_arraysize(num, elt_size); +} + +inline static int dmm_ring_count(struct dmm_ring *ring) +{ + const int count = ring->prod_tail - ring->cons_head; + + if (count >= 0) + return count; + return count + ring->size; +} + +inline static int dmm_ring_free_count(struct dmm_ring *ring) +{ + const int count = ring->cons_tail - ring->prod_head; + + if (count >= 0) + return count; + return count + ring->size; +} + +#endif diff --git a/src/framework/include/hal_api.h b/src/framework/include/hal_api.h deleted file mode 100644 index a5d7725..0000000 --- a/src/framework/include/hal_api.h +++ /dev/null @@ -1,148 +0,0 @@ -/* -* -* 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 _HAL_API_H_ -#define _HAL_API_H_ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ -#endif - -typedef void hal_mempool_t; -typedef void hal_mbuf_t; - -#define HAL_ETH_MAX_QUEUE_NUM 4 - -#define HAL_ETH_QUEUE_STAT_CNTRS 16 - -#define HAL_MAX_NIC_NUM 4096 -COMPAT_PROTECT (HAL_MAX_NIC_NUM, 4096); - -#define HAL_MAX_SLAVES_PER_BOND 2 - -#define HAL_MAX_NIC_NAME_LEN 256 - -/** - * TX offload capabilities of a device. - */ -#define HAL_ETH_TX_OFFLOAD_IPV4_CKSUM 0x00000002 -#define HAL_ETH_TX_OFFLOAD_UDP_CKSUM 0x00000004 -#define HAL_ETH_TX_OFFLOAD_TCP_CKSUM 0x00000008 - -/** - * Hal Instance Handler - */ -typedef struct hal_hdl -{ - int id; -} hal_hdl_t; - -/** - * Ethernet device capability - */ -typedef struct hal_netif_capa -{ - uint32_t tx_offload_capa; /**< Device TX offload capabilities. */ -} hal_netif_capa_t; - -/** - * A structure used to retrieve statistics for an Ethernet port. - */ -typedef struct hal_netif_stats -{ - uint64_t ipackets; /**< Total no.of packets that are successfully received . */ - uint64_t opackets; /**< Total no.of packets that are successfully transmitted .*/ - uint64_t ibytes; /**< Total no.of bytes that are successfully received . */ - uint64_t obytes; /**< Total no.of bytes that are successfully transmitted . */ - uint64_t imissed; /**< Total no.of RX packets that are dropped by the HW. */ - uint64_t ierrors; /**< Total no.of packets that are received as erroneous. */ - uint64_t oerrors; /**< Total no.of failed transmitted packets. */ - uint64_t rx_nombuf; /**< Total no.of RX mbuf allocation failures. */ - - uint64_t q_ipackets[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total no.of queue RX packets. */ - uint64_t q_opackets[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total no.of queue TX packets. */ - uint64_t q_ibytes[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total no.of successfully received queue bytes. */ - uint64_t q_obytes[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total no.of successfully transmitted queue bytes. */ - uint64_t q_errors[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total no.of queue packets received that are dropped. */ -} hal_netif_stats_t; - -/** - * Ethernet device config - */ -typedef struct hal_netif_config -{ - struct - { - uint32_t hw_vlan_filter:1; - uint32_t hw_vlan_strip:1; - uint32_t rsv30:30; - } bit; - - struct - { - uint32_t queue_num; - uint32_t ring_size[HAL_ETH_MAX_QUEUE_NUM]; - hal_mempool_t *ring_pool[HAL_ETH_MAX_QUEUE_NUM]; - } rx; - - struct - { - uint32_t queue_num; - uint32_t ring_size[HAL_ETH_MAX_QUEUE_NUM]; - } tx; - -} hal_netif_config_t; - -int hal_init_global (int argc, char **argv); -int hal_init_local (); -hal_hdl_t hal_create (const char *name, const char *nic_type, - hal_netif_config_t * conf); -hal_hdl_t hal_bond (const char *bond_name, uint8_t slave_num, - hal_hdl_t slave_hdl[]); - -#define hal_is_valid(hdl) ((hdl.id >= 0) && (hdl.id < HAL_MAX_NIC_NUM)) - -#define hal_is_equal(hdl_left, hdl_right) (hdl_left.id == hdl_right.id) - -int hal_close (hal_hdl_t hdl); -int hal_stop (hal_hdl_t hdl); -uint32_t hal_get_mtu (hal_hdl_t hdl); -void hal_get_macaddr (hal_hdl_t hdl, void *mac_addr); -void hal_get_capability (hal_hdl_t hdl, hal_netif_capa_t * info); -uint16_t hal_recv_packet (hal_hdl_t hdl, uint16_t queue_id, - hal_mbuf_t ** rx_pkts, uint16_t nb_pkts); -uint16_t hal_send_packet (hal_hdl_t hdl, uint16_t queue_id, - hal_mbuf_t ** tx_pkts, uint16_t nb_pkts); -uint32_t hal_link_status (hal_hdl_t hdl); -int hal_stats (hal_hdl_t hdl, hal_netif_stats_t * stats); -void hal_stats_reset (hal_hdl_t hdl); -int hal_add_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, - void *mc_addr, uint32_t nb_mc_addr); -int hal_del_mcastaddr (hal_hdl_t hdl, void *mc_addr_set, - void *mc_addr, uint32_t nb_mc_addr); -void hal_set_allmulti_mode (hal_hdl_t hdl, uint8_t enable); -uint32_t hal_is_nic_exist (const char *name); -hal_hdl_t hal_get_invalid_hdl (); - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif - -#endif diff --git a/src/framework/include/nsfw_alarm_api.h b/src/framework/include/nsfw_alarm_api.h new file mode 100644 index 0000000..54cbde2 --- /dev/null +++ b/src/framework/include/nsfw_alarm_api.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 _NSFW_ALARM_API_H_ +#define _NSFW_ALARM_API_H_ + +//#include <sys/types.h> + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#define ALARM_RESEND_TIMER_LENGTH 10 + +#define ALARM_ID_BASE_VALUE 27000 + +/* 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_1, + ALARM_EVENT_NSTACK_MAIN_ABNORMAL_RESTART_FAIL, /* daemon-stack exit, nStackMaster can't successfully restart */ + ALARM_EVENT_NSTACK_NO_USE_2, + ALARM_EVENT_NSTACK_MAIN_EXIT_CAUSE_FD_FAIL, /* daemon-stack exit cause fd report err event */ + ALARM_EVENT_NSTACK_HOTFIX_ALM_ID = 1006, /* used for hotfix activate */ + ALARM_EVENT_MAX +} enum_alarm_id; + +typedef enum _alarm_flag +{ + ALARM_PRODUCT, + ALARM_CLEAN, + ALARM_HOTFIX, + ALARM_MAX +} alarm_flag; + +#define ALARM_ID_NOT_VALID(alarmId) (((alarmId) <= ALARM_EVENT_BASE) || ((alarmId) >= ALARM_EVENT_MAX)) + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif diff --git a/src/framework/include/nsfw_base_linux_api.h b/src/framework/include/nsfw_base_linux_api.h new file mode 100644 index 0000000..bfa98b8 --- /dev/null +++ b/src/framework/include/nsfw_base_linux_api.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 _NSFW_BASE_LINUX_API_H_ +#define _NSFW_BASE_LINUX_API_H_ + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/epoll.h> +#include <unistd.h> +#include <netdb.h> + +int nsfw_base_socket(int, int, int); +int nsfw_base_bind(int, const struct sockaddr *, socklen_t); +int nsfw_base_listen(int, int); +int nsfw_base_shutdown(int, int); +int nsfw_base_getsockname(int, struct sockaddr *, socklen_t *); +int nsfw_base_getpeername(int, struct sockaddr *, socklen_t *); +int nsfw_base_getaddrinfo(const char *, const char *, + const struct addrinfo *, struct addrinfo **); +int nsfw_base_getsockopt(int, int, int, void *, socklen_t *); +int nsfw_base_setsockopt(int, int, int, const void *, socklen_t); +int nsfw_base_accept(int, struct sockaddr *, socklen_t *); +int nsfw_base_accept4(int, struct sockaddr *, socklen_t *, int flags); +int nsfw_base_connect(int, const struct sockaddr *, socklen_t); +ssize_t nsfw_base_recv(int, void *, size_t, int); +ssize_t nsfw_base_send(int, const void *, size_t, int); +ssize_t nsfw_base_read(int, void *, size_t); +ssize_t nsfw_base_write(int, const void *, size_t); +ssize_t nsfw_base_writev(int, const struct iovec *, int); +ssize_t nsfw_base_readv(int, const struct iovec *, int); +ssize_t nsfw_base_sendto(int, const void *, size_t, int, + const struct sockaddr *, socklen_t); +ssize_t nsfw_base_recvfrom(int, void *, size_t, int, struct sockaddr *, + socklen_t *); +ssize_t nsfw_base_sendmsg(int, const struct msghdr *, int flags); +ssize_t nsfw_base_recvmsg(int, struct msghdr *, int flags); +int nsfw_base_close(int); +int nsfw_base_select(int, fd_set *, fd_set *, fd_set *, struct timeval *); +int nsfw_base_ioctl(int, unsigned long, unsigned long); +int nsfw_base_fcntl(int, int, unsigned long); +int nsfw_base_epoll_create(int); +int nsfw_base_epoll_create1(int); +int nsfw_base_epoll_ctl(int, int, int, struct epoll_event *); +int nsfw_base_epoll_wait(int, struct epoll_event *, int, int); +pid_t nsfw_base_fork(void); + +#endif diff --git a/src/framework/common/base/include/common/common_mem_pal_memconfig.h b/src/framework/include/nsfw_branch_prediction.h index 65b6e04..0bfae52 100644 --- a/src/framework/common/base/include/common/common_mem_pal_memconfig.h +++ b/src/framework/include/nsfw_branch_prediction.h @@ -14,13 +14,15 @@ * limitations under the License. */ -#ifndef _COMMON_MEM_PAL_MEMCONFIG_H_ -#define _COMMON_MEM_PAL_MEMCONFIG_H_ +#ifndef _NSFW_BRANCH_PREDICTION_H_ +#define _NSFW_BRANCH_PREDICTION_H_ -#ifdef HAL_LIB -#else -#include "rte_eal_memconfig.h" +#ifndef likely +#define likely(x) __builtin_expect(!!(x), 1) +#endif +#ifndef unlikely +#define unlikely(x) __builtin_expect(!!(x), 0) #endif #endif diff --git a/src/framework/common/base/include/common/common_mem_common.h b/src/framework/include/nsfw_common_defs.h index 1e4cf56..187f8c0 100644 --- a/src/framework/common/base/include/common/common_mem_common.h +++ b/src/framework/include/nsfw_common_defs.h @@ -14,12 +14,23 @@ * limitations under the License. */ -#ifndef _COMMON_MEM_COMMON_H_ -#define _COMMON_MEM_COMMON_H_ +#ifndef _NSFW_COMMON_DEFS_H_ +#define _NSFW_COMMON_DEFS_H_ -#ifdef HAL_LIB -#else -#include "rte_common.h" +#ifndef NSTACK_MAX_MODULE_NUM +#define NSTACK_MAX_MODULE_NUM 8 #endif +#ifndef NSTACK_LIB_LOAD_DYN +#define NSTACK_LIB_LOAD_DYN 0 #endif + +#ifndef NSTACK_LIB_LOAD_STATIC +#define NSTACK_LIB_LOAD_STATIC 1 +#endif + +#ifndef NSTACK_MODULE_NAME_MAX +#define NSTACK_MODULE_NAME_MAX 64 +#endif + +#endif // _NSFW_COMMON_DEFS_H_ diff --git a/src/framework/include/nsfw_dfx_api.h b/src/framework/include/nsfw_dfx_api.h new file mode 100644 index 0000000..99a5ab7 --- /dev/null +++ b/src/framework/include/nsfw_dfx_api.h @@ -0,0 +1,74 @@ +/* +* +* 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_DMM_DFX_API_H__ +#define __NSTACK_DMM_DFX_API_H__ +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> /* See NOTES */ +#include <sys/socket.h> +#include<netinet/in.h> +#include <sys/epoll.h> +#include "types.h" + +struct stat_epfd_info +{ + u64 epoll_wait_tick; + i32 epfd; + pid_t hhpid; + u8 epoll_fork_flag; + u8 reserve_8[3]; + u32 ep_sleepTime; +}; + +typedef struct stat_epitem_info +{ + struct epoll_event event; + int is_linked; +} stat_epitem_info_t; + +typedef struct __ns_udp_route_info +{ + struct sockaddr_in iaddr; + int selectmod; +} ns_udp_route_Inf; + +typedef enum nstack_dmm_type_e +{ + DMM_STAT_LONGEST_SEND_INTERVAL = 0, + DMM_STAT_LONGEST_SEND_COST, + DMM_STAT_LONGEST_RECV_INTERVAL, + DMM_STAT_LONGEST_RECV_COST, + DMM_STAT_ROUTE_INFO, + DMM_APP_EPOLL_WAIT_EVENT, + DMM_APP_EPOLL_WAIT_FAIL, + DMM_APP_EPOLL_WAIT_GET_TICK, + DMM_APP_EPOLL_ADD_TICK, + DMM_APP_EPOLL_MOD_TICK, + DMM_APP_EPOLL_WAIT_CALL_TICK, + DMM_APP_EPOLL_DEL_TICK, + DMM_APP_SELECT_FAIL, + DMM_MAIN_REPORT_EVENT_TICK, + DMM_MAIN_REPORT_EP_CNT, + + DMM_DFX_MAX = 64 +} nstack_dmm_type_t; + +void nstack_dfx_state_update(u64 fd, int midx, nstack_dmm_type_t type, + void *data); +void nstack_fd_dfx_update_dfx_data(int fd, int protoFd, int midx, int type, + void *info); +#endif diff --git a/src/framework/include/nsfw_fd_timer_api.h b/src/framework/include/nsfw_fd_timer_api.h index 0b42fe0..3cef663 100644 --- a/src/framework/include/nsfw_fd_timer_api.h +++ b/src/framework/include/nsfw_fd_timer_api.h @@ -19,6 +19,7 @@ #include "list.h" #include <time.h> +#include "dmm_spinlock.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -30,30 +31,32 @@ extern "C"{ typedef struct _nsfw_timer_init_cfg { - u32 timer_info_size; - void *timer_info_pool; - struct list_head timer_head; - struct list_head exp_timer_head; + u32 timer_info_size; + void *timer_info_pool; + struct list_head timer_head; + struct list_head exp_timer_head; + dmm_spinlock_t timer_lock; /* it can start timer after only finish all timer reg, or else it have multi-thread issue */ + struct itimerspec ts; } nsfw_timer_init_cfg; typedef int (*nsfw_timer_proc_fun) (u32 timer_type, void *argv); typedef struct _nsfw_timer_info { - struct list_head node; - nsfw_timer_proc_fun fun; - void *argv; - struct timespec time_left; - u32 timer_type; - u8 alloc_flag; + struct list_head node; + nsfw_timer_proc_fun fun; + void *argv; + struct timespec time_left; + u32 timer_type; + u8 alloc_flag; } nsfw_timer_info; -extern nsfw_timer_info *nsfw_timer_reg_timer (u32 timer_type, void *data, - nsfw_timer_proc_fun fun, - struct timespec time_left); -extern void nsfw_timer_rmv_timer (nsfw_timer_info * tm_info); +extern nsfw_timer_info *nsfw_timer_reg_timer(u32 timer_type, void *data, + nsfw_timer_proc_fun fun, + struct timespec time_left); +extern void nsfw_timer_rmv_timer(nsfw_timer_info * tm_info); extern u8 g_hbt_switch; -extern int nsfw_timer_module_init (void *param); +extern int nsfw_timer_module_init(void *param); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/nsfw_hal_api.h b/src/framework/include/nsfw_hal_api.h new file mode 100644 index 0000000..4669d44 --- /dev/null +++ b/src/framework/include/nsfw_hal_api.h @@ -0,0 +1,275 @@ +/* +* +* 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 _HAL_API_H_ +#define _HAL_API_H_ + +#include "nsfw_branch_prediction.h" +#include "nsfw_maintain_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#define HAL_IO_REGISTER(name, ops) \ + static __attribute__((__constructor__)) void __hal_register_##name(void) \ + {\ + hal_io_adpt_register(ops); \ + } \ + +#define HAL_ETH_MAX_QUEUE_NUM MAX_THREAD_NUM + +#define HAL_ETH_QUEUE_STAT_CNTRS 16 + +#define HAL_MAX_NIC_NUM 4096 +COMPAT_PROTECT_RETURN(HAL_MAX_NIC_NUM, 4096); + +#define HAL_MAX_SLAVES_PER_BOND 2 + +#define HAL_MAX_NIC_NAME_LEN 256 + +#define HAL_MAX_PCI_ADDR_LEN 16 + +#define HAL_SCRIPT_LENGTH 256 + +#define HAL_MAX_DRIVER_NAME_LEN 128 + +#define HAL_MAX_PATH_LEN 4096 //max path length on linux is 4096 + +/** + * TX offload capabilities of a device. + */ +#define HAL_ETH_TX_OFFLOAD_IPV4_CKSUM 0x00000002 +#define HAL_ETH_TX_OFFLOAD_UDP_CKSUM 0x00000004 +#define HAL_ETH_TX_OFFLOAD_TCP_CKSUM 0x00000008 + +/** + * Hal Instance Handler + */ +typedef struct hal_hdl +{ + int id; +} hal_hdl_t; + +/** + * Ethernet device capability + */ +struct hal_netif_hw_feature +{ + uint8_t rx_csum_ip; + uint8_t rx_csum_l4; + uint8_t rx_lro; + uint8_t tx_csum_ip; + uint8_t tx_csum_udp; + uint8_t tx_csum_tcp; + uint8_t tx_tso; +}; + +struct lwip_pci_zone +{ + char pci_addr[HAL_MAX_PCI_ADDR_LEN]; + char nic_name[HAL_MAX_NIC_NAME_LEN]; +}; + +typedef struct hal_netif_stats +{ + uint64_t ipackets; /**< Number of successfully received packets. */ + uint64_t opackets; /**< Number of successfully transmitted packets.*/ + uint64_t ibytes; /**< Number of successfully received bytes. */ + uint64_t obytes; /**< Number of successfully transmitted bytes. */ + uint64_t imissed; /**< Total of RX packets dropped by the HW. */ + uint64_t ierrors; /**< Number of erroneous received packets. */ + uint64_t oerrors; /**< Number of failed transmitted packets. */ + uint64_t rx_nombuf; /**< Number of RX mbuf allocation failures. */ + + uint64_t q_ipackets[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total number of queue RX packets. */ + uint64_t q_opackets[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total number of queue TX packets. */ + uint64_t q_ibytes[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total number of successfully received queue bytes. */ + uint64_t q_obytes[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total number of successfully transmitted queue bytes. */ + uint64_t q_errors[HAL_ETH_QUEUE_STAT_CNTRS]; /**< Total number of queue packets received that are dropped. */ +} hal_netif_stats_t; + +struct hal_netif_hw_config +{ + uint32_t rx_csum_ip_flag:1, + rx_csum_l4_flag:1, + rx_lro_flag:1, tx_csum_ip_flag:1, tx_csum_l4_flag:1, tx_tso_flag:1; +}; +extern struct hal_netif_hw_config spl_hal_port_hw_config[HAL_MAX_NIC_NUM]; +/** + * Ethernet device config + */ +typedef struct hal_netif_config +{ + struct hal_netif_hw_config hw_config; + struct + { + uint32_t hw_vlan_filter:1; + uint32_t hw_vlan_strip:1; + uint32_t rsv30:30; + } bit; + + struct + { + uint32_t queue_num; + uint32_t ring_size[HAL_ETH_MAX_QUEUE_NUM]; + void *ring_pool[HAL_ETH_MAX_QUEUE_NUM]; + } rx; + + struct + { + uint32_t queue_num; + uint32_t ring_size[HAL_ETH_MAX_QUEUE_NUM]; + } tx; + + uint8_t is_slave; +} hal_netif_config_t; + +/* IO using DPDK interface */ +typedef struct dpdk_if +{ + uint8_t port_id; /**< DPDK port identifier */ + uint8_t is_slave; + uint8_t slave_num; + uint8_t slave_port[HAL_MAX_SLAVES_PER_BOND]; + + uint32_t hw_vlan_filter:1; + uint32_t hw_vlan_strip:1; + uint32_t rsv30:30; + + uint32_t rx_queue_num; + uint32_t rx_ring_size[HAL_ETH_MAX_QUEUE_NUM]; + void *rx_pool[HAL_ETH_MAX_QUEUE_NUM]; + + uint32_t tx_queue_num; + uint32_t tx_ring_size[HAL_ETH_MAX_QUEUE_NUM]; + + char pci_addr[HAL_MAX_PCI_ADDR_LEN]; + char nic_name[HAL_MAX_NIC_NAME_LEN]; + char nic_type[HAL_MAX_NIC_NAME_LEN]; + char driver_name[HAL_MAX_DRIVER_NAME_LEN]; +} dpdk_if_t; + +typedef struct netif_inst +{ + enum + { + NETIF_STATE_FREE = 0, + NETIF_STATE_ACTIVE + } state; + + hal_hdl_t hdl; + struct hal_netif_hw_config hw_config; + const struct netif_ops *ops; /**< Implementation specific methods */ + + union + { + dpdk_if_t dpdk_if; /**< using DPDK for IO */ + } data; + +} netif_inst_t; + +typedef struct netif_ops +{ + const char *name; + int (*init_global) (int argc, char **argv); + int (*init_local) (void); + int (*open) (netif_inst_t * inst, const char *name, const char *type); + int (*close) (netif_inst_t * inst); + int (*start) (netif_inst_t * inst); + int (*stop) (netif_inst_t * inst); + int (*bond) (netif_inst_t * inst, const char *bond_name, + uint8_t slave_num, netif_inst_t * slave[]); + uint32_t(*mtu) (netif_inst_t * inst); + int (*macaddr) (netif_inst_t * inst, void *mac_addr); + int (*capability) (netif_inst_t * inst, + struct hal_netif_hw_feature * info); + uint16_t(*recv) (netif_inst_t * inst, uint16_t queue_id, + void **rx_pkts, uint16_t nb_pkts); + uint16_t(*send) (netif_inst_t * inst, uint16_t queue_id, + void **tx_pkts, uint16_t nb_pkts); + uint32_t(*link_status) (netif_inst_t * inst); + int (*stats) (netif_inst_t * inst, hal_netif_stats_t * stats); + int (*stats_reset) (netif_inst_t * inst); + int (*config) (netif_inst_t * inst, hal_netif_config_t * conf); + int (*mcastaddr) (netif_inst_t * inst, void *mc_addr_set, + void *mc_addr, uint32_t nb_mc_addr); + int (*add_mac) (netif_inst_t * inst, void *mc_addr); + int (*rmv_mac) (netif_inst_t * inst, void *mc_addr); + int (*allmcast) (netif_inst_t * inst, uint8_t enable); + int (*port_switch) (netif_inst_t * inst); + int (*get_bond_primary) (netif_inst_t * inst); + int (*check_rss) (netif_inst_t * inst, uint32_t saddr, uint32_t daddr, + uint16_t sport, uint16_t dport, + uint16_t * thread_index); + int (*check_rss6) (netif_inst_t * inst, uint32_t saddr[4], + uint32_t daddr[4], uint16_t sport, uint16_t dport, + uint16_t * thread_index); +} netif_ops_t; + +int hal_init_global(int argc, char **argv); +int hal_init_local(); +hal_hdl_t hal_create(const char *name, const char *nic_type, + hal_netif_config_t * conf); +hal_hdl_t hal_bond(const char *bond_name, uint8_t slave_num, + hal_hdl_t slave_hdl[]); + +#define hal_is_valid(hdl) ((hdl.id >= 0) && (hdl.id < HAL_MAX_NIC_NUM)) + +#define hal_is_equal(hdl_left, hdl_right) (hdl_left.id == hdl_right.id) + +int hal_close(hal_hdl_t hdl); +int hal_stop(hal_hdl_t hdl); +uint32_t hal_get_mtu(hal_hdl_t hdl); +void hal_get_macaddr(hal_hdl_t hdl, void *mac_addr); +void hal_get_capability(hal_hdl_t hdl, struct hal_netif_hw_feature *info); +uint16_t hal_recv_packet(hal_hdl_t hdl, uint16_t queue_id, void **rx_pkts, + uint16_t nb_pkts); +uint16_t hal_send_packet(hal_hdl_t hdl, uint16_t queue_id, void **tx_pkts, + uint16_t nb_pkts); +uint32_t hal_link_status(hal_hdl_t hdl); +int hal_stats(hal_hdl_t hdl, hal_netif_stats_t * stats); +void hal_stats_reset(hal_hdl_t hdl); +int hal_add_mcastaddr(hal_hdl_t hdl, void *mc_addr_set, + void *mc_addr, uint32_t nb_mc_addr); +int hal_del_mcastaddr(hal_hdl_t hdl, void *mc_addr_set, + void *mc_addr, uint32_t nb_mc_addr); +void hal_set_allmulti_mode(hal_hdl_t hdl, uint8_t enable); +uint32_t hal_is_nic_exist(const char *name); +hal_hdl_t hal_get_invalid_hdl(); +int hal_bond_switch(const char *bond_name); +int hal_get_bond_primary(const char *bond_name); +int hal_snprintf(char *buffer, size_t buflen, const char *format, ...); +int hal_run_script(const char *cmd, char *result_buf, size_t max_result_len); +int hal_is_script_valid(const char *cmd); +void hal_io_adpt_register(const netif_ops_t * ops); + +int hal_check_rss(hal_hdl_t hdl, uint32_t saddr, uint32_t daddr, + uint16_t sport, uint16_t dport, uint16_t * thread_index); +int hal_check_rss6(hal_hdl_t hdl, uint32_t saddr[4], uint32_t daddr[4], + uint16_t sport, uint16_t dport, uint16_t * thread_index); + +struct hal_netif_hw_config *hal_get_netif_hw_config(hal_hdl_t hdl); + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif diff --git a/src/framework/include/nsfw_init.h b/src/framework/include/nsfw_init_api.h index 0237060..924865b 100644 --- a/src/framework/include/nsfw_init.h +++ b/src/framework/include/nsfw_init_api.h @@ -16,6 +16,7 @@ #ifndef _FW_INIT_H #define _FW_INIT_H +#include <pthread.h> #ifdef __cplusplus /* *INDENT-OFF* */ @@ -30,20 +31,79 @@ extern "C"{ #define NSFW_INIT_MODULE_PRIORITY_BASE 1 #define NSFW_INIT_MODULE_PRIORITY(x) (NSFW_INIT_MODULE_PRIORITY_BASE + x) +#define NSFW_MAX_STRING_LENGTH 128 + +typedef int (*nsfw_module_init_fn) (void *); + +typedef struct _nsfw_module_depends +{ + char name[NSFW_MAX_STRING_LENGTH]; + int isReady; + struct _nsfw_module_depends *next; /* It is a list, not just only one */ +} nsfw_module_depends_t; + +extern nsfw_module_depends_t *nsfw_module_create_depends(char *name); + +typedef enum +{ + NSFW_INST_STAT_CHECKING, /* Not check yet */ + NSFW_INST_STAT_DEPENDING, /* Blocked, waiting for other module instances */ + NSFW_INST_STAT_DONE, /* Check done */ + NSFW_INST_STAT_FAIL /* Check Fail */ +} nsfw_module_instance_stat_t; + +typedef struct _nsfw_module_instance +{ + nsfw_module_init_fn fnInit; + char name[NSFW_MAX_STRING_LENGTH]; + char fatherName[NSFW_MAX_STRING_LENGTH]; + int priority; + nsfw_module_depends_t *depends; + nsfw_module_instance_stat_t stat; + void *param; + struct _nsfw_module_instance *next; + struct _nsfw_module_instance *child; + struct _nsfw_module_instance *father; +} nsfw_module_instance_t; + +static nsfw_module_instance_t *nsfwLocalInitInst __attribute__ ((unused)) = + NULL; + +extern nsfw_module_instance_t *nsfw_module_create_instance(); +extern nsfw_module_instance_t *nsfw_module_get_module_by_name(char *); +extern void nsfw_module_add_instance(nsfw_module_instance_t * inst); +extern void nsfw_module_del_instance(nsfw_module_instance_t * inst); +extern void nsfw_module_set_instance_name(nsfw_module_instance_t * inst, + char *name); +extern void nsfw_module_set_instance_father(nsfw_module_instance_t * inst, + char *father); +extern void nsfw_module_set_instance_priority(nsfw_module_instance_t * inst, + int priority); +extern void nsfw_module_set_instance_initfn(nsfw_module_instance_t * inst, + nsfw_module_init_fn fn); +extern void nsfw_module_set_instance_depends(nsfw_module_instance_t * inst, + char *name); + #define NSFW_SET_INSTANCE_VALUE(_attr, _inst, _value) \ nsfw_module_set_instance_##_attr(_inst, _value) -#define NSFW_INIT_CREATE_LOCAL_INSTANCE() \ +#define NSFW_INIT_CRAETE_LOCAL_INSTANCE() \ if (!nsfwLocalInitInst) {\ nsfwLocalInitInst = nsfw_module_create_instance(); \ - nsfw_module_add_instance(nsfwLocalInitInst);\ + if (nsfwLocalInitInst) \ + { \ + nsfw_module_add_instance(nsfwLocalInitInst);\ + } \ } #define _NSFW_MODULE_ATTRIBUTE_DEFINE_SURFIX(_attr, _value, _priority, _surfix) \ + \ + \ static __attribute__((__constructor__(_priority))) void nsfw_module_attribute_##_attr##_surfix(void){\ - NSFW_INIT_CREATE_LOCAL_INSTANCE(); \ + NSFW_INIT_CRAETE_LOCAL_INSTANCE(); \ NSFW_SET_INSTANCE_VALUE(_attr, nsfwLocalInitInst, _value);\ } \ + \ #define NSFW_MODULE_ATTRIBUTE_DEFINE_SURFIX(_attr, _value, _priority, _surfix) \ _NSFW_MODULE_ATTRIBUTE_DEFINE_SURFIX(_attr, _value, _priority, _surfix) @@ -69,75 +129,26 @@ extern "C"{ #define NSFW_MODULE_INIT(_initfn) \ NSFW_MODULE_ATTRIBUTE_DEFINE(initfn, _initfn, NSFW_INIT_PRIORITY_INITFN) -#define NSFW_MAX_STRING_LENGTH 128 - -#define NSFW_DEPENDS_SIZE 8 -typedef struct _nsfw_module_depends -{ - char name[NSFW_MAX_STRING_LENGTH]; - int isReady; - struct _nsfw_module_depends *next; /* It is a list, not just only one */ -} nsfw_module_depends_t; - -typedef enum -{ - NSFW_INST_STAT_CHECKING, /* Not check yet */ - NSFW_INST_STAT_DEPENDING, /* Blocked, waiting for other module instances */ - NSFW_INST_STAT_DONE, /* Check done */ - NSFW_INST_STAT_FAIL /* Check Fail */ -} nsfw_module_instance_stat_t; - -typedef int (*nsfw_module_init_fn) (void *); - -typedef struct _nsfw_module_instance -{ - nsfw_module_init_fn fnInit; - char name[NSFW_MAX_STRING_LENGTH]; - char fatherName[NSFW_MAX_STRING_LENGTH]; - int priority; - nsfw_module_depends_t *depends; - nsfw_module_instance_stat_t stat; - void *param; - struct _nsfw_module_instance *next; - struct _nsfw_module_instance *child; - struct _nsfw_module_instance *father; -} nsfw_module_instance_t; - -static nsfw_module_instance_t *nsfwLocalInitInst __attribute__ ((unused)) = - (void *) 0; - -extern nsfw_module_instance_t *nsfw_module_create_instance (); -extern nsfw_module_instance_t *nsfw_module_getModuleByName (char *); -extern void nsfw_module_add_instance (nsfw_module_instance_t * inst); -extern void nsfw_module_del_instance (nsfw_module_instance_t * inst); -extern void nsfw_module_set_instance_name (nsfw_module_instance_t * inst, - char *name); -extern void nsfw_module_set_instance_father (nsfw_module_instance_t * inst, - char *father); -extern void nsfw_module_set_instance_priority (nsfw_module_instance_t * - inst, int priority); -extern void nsfw_module_set_instance_initfn (nsfw_module_instance_t * inst, - nsfw_module_init_fn fn); -extern void nsfw_module_set_instance_depends (nsfw_module_instance_t * inst, - char *name); - /** * @Function nstack_framework_init - * @Description This function will do framework initial work, it will invoke all initial functions - * registered using macro NSFW_MODULE_INIT before + * @Description This function will do framework initial work, it will involk all initial functions + * registed using macro NSFW_MODULE_INIT before * @param none * @return 0 on success, -1 on error */ -extern int nstack_framework_init (void); +extern int nstack_framework_init(void); /** - * @Function nstack_framework_setModuleParam + * @Function nstack_framework_set_module_param * @Description This function set parameter of module initial function parameter * @param module - name of module * @param param - parameter to set * @return 0 on success, -1 on error */ -extern int nstack_framework_setModuleParam (char *module, void *param); +extern int nstack_framework_set_module_param(char *module, void *param); + +extern int get_fw_init_err(); +extern void set_fw_init_err(int); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/nsfw_maintain_api.h b/src/framework/include/nsfw_maintain_api.h index bf0d45e..a05719f 100644 --- a/src/framework/include/nsfw_maintain_api.h +++ b/src/framework/include/nsfw_maintain_api.h @@ -20,6 +20,7 @@ #include "types.h" #include "nsfw_mgr_com_api.h" #include "compiling_check.h" +#include <time.h> #ifdef __cplusplus /* *INDENT-OFF* */ @@ -36,83 +37,156 @@ extern "C"{ #define MEM_STAT(module, mem_name, mem_type, mem_size)\ nsfw_mem_stat(module, mem_name, mem_type, mem_size) -extern void nsfw_mem_stat (char *module, char *mem_name, u8 mem_type, - u32 mem_size); -extern void nsfw_mem_stat_print (); +extern void nsfw_mem_stat(char *module, char *mem_name, u8 mem_type, + u64 mem_size); +extern void nsfw_mem_stat_print(); /*##############################################*/ /*################SRV_CTRL######################*/ typedef enum _nsfw_srv_ctrl_state { - NSFW_SRV_CTRL_RESUME = 1, - NSFW_SRV_CTRL_SUSPEND = 2 + NSFW_SRV_CTRL_RESUME = 1, + NSFW_SRV_CTRL_SUSPEND = 2 } nsfw_srv_ctrl_state; typedef struct _nsfw_srv_ctrl_msg { - nsfw_srv_ctrl_state srv_state; - u16 rsp_code; + nsfw_srv_ctrl_state srv_state; + u16 rsp_code; } nsfw_srv_ctrl_msg; -extern u8 nsfw_srv_ctrl_send (nsfw_srv_ctrl_state state, u8 rsp_flag); +extern u8 nsfw_srv_ctrl_send(nsfw_srv_ctrl_state state, u8 rsp_flag); /*#############################################*/ /*#################RES_MGR######################*/ -#define NSFW_RES_MGR_MODULE "nsfw_res_mgr" +#define SPL_RES_MGR_MODULE "spl_res_mgr" typedef enum _nsfw_res_scan_type { - NSFW_RES_SCAN_ARRAY = 0, - NSFW_RES_SCAN_SPOOL, - NSFW_RES_SCAN_MBUF, - NSFW_RES_SCAN_MAX + NSFW_RES_SCAN_ARRAY = 0, + NSFW_RES_SCAN_SPOOL, + NSFW_RES_SCAN_MBUF, + NSFW_RES_SCAN_MAX } nsfw_res_scan_type; typedef int (*nsfw_res_free_fun) (void *pdata); typedef struct _nsfw_res_scn_cfg { - u8 type; /*nsfw_res_scan_type */ - u8 force_free_percent; /*if the resource free percent below this value, begin to force free the element */ - u16 force_free_chk_num; /*if the check count beyone this value, call free fun release this element */ - u16 alloc_speed_factor; /*alloc fast with higher value */ + u8 type; /*nsfw_res_scan_type */ + u8 force_free_percent; /*if the resource free percent below this vlaue, begin to force free the element */ + u16 force_free_chk_num; /*if the check count beyone this vlaue, call free fun release this element */ + u16 alloc_speed_factor; /*alloc fast with higher value */ - u32 num_per_cyc; /*define the element number in one scan cycle process and increase chk_count of every element */ - u32 total_num; /*total number of elements */ - u32 elm_size; /*element size */ - u32 res_mem_offset; /*the nsfw_res offset from the element start */ + u32 num_per_cyc; /*define the element number in one scan cycle process and increase chk_count of every element */ + u32 total_num; /*total number of elements */ + u32 elm_size; /*element size */ + u32 res_mem_offset; /*the nsfw_res offset from the element start */ - void *data; /*the array addr or spool addr */ - void *mgr_ring; + void *data; /*the array addr or spool addr */ + void *mgr_ring; - nsfw_res_free_fun free_fun; + nsfw_res_free_fun free_fun; } nsfw_res_scn_cfg; typedef struct _nsfw_res_mgr_item_cfg { - nsfw_res_scn_cfg scn_cfg; - u32 cons_head; - u32 prod_head; - u32 free_percent; - u32 last_scn_idx; - u64 force_count; + nsfw_res_scn_cfg scn_cfg; + u32 cons_head; + u32 prod_head; + u32 free_percent; + u32 last_scn_idx; + u64 force_count; } nsfw_res_mgr_item_cfg; #define NSFW_MAX_RES_SCAN_COUNT 256 -extern u8 nsfw_res_mgr_reg (nsfw_res_scn_cfg * cfg); -extern i32 nsfw_proc_start_with_lock (u8 proc_type); +extern u8 nsfw_res_mgr_reg(nsfw_res_scn_cfg * cfg); +extern i32 nsfw_proc_start_with_lock(u8 proc_type); +extern i32 nstack_record_pid_check_memory(u8 proc_type); + /*#############################################*/ +/*#################VER_MGR######################*/ +#define NSFW_VER_MGR_MODULE "nsfw_ver_mgr" + +typedef enum _nsfw_ver_mgr_state +{ + NSFW_VER_NULL = 0, + NSFW_VER_UPG = 1, + NSFW_VER_RBK = 2, + NSFW_VER_QRY = 3, + NSFW_VER_READY_TO_RESTART = 4 +} nsfw_ver_mgr_state; + +typedef enum _nsfw_ver_mgr_err +{ + NSFW_OK = 0, + NSFW_STATE_IN_UPG = 100, + NSFW_INTER_FALIED = 120, + NSFW_POOL_NULL = 121, + +} nsfw_ver_mgr_err; + +#define NSTACK_MAX_VERSION_LEN 40 +#define NSTACK_MAX_MODULE_LEN 20 +#define NSTACK_MAX_BUILDTIME_LEN 32 + +typedef struct _nsfw_ver_mgr_msg +{ + nsfw_ver_mgr_state ver_state; + u16 rsp_code; + char src_ver[NSTACK_MAX_VERSION_LEN]; + char dst_ver[NSTACK_MAX_VERSION_LEN]; + char module_name[NSTACK_MAX_MODULE_LEN]; + char build_time[NSTACK_MAX_BUILDTIME_LEN]; +} nsfw_ver_mgr_msg; +extern u8 nsfw_ver_mgr_rsq(u16 rsp_code, u32 src_pid); + +typedef struct _nsfw_ver_info +{ + char version[NSTACK_MAX_VERSION_LEN]; + char module_name[NSTACK_MAX_MODULE_LEN]; + char build_time[NSTACK_MAX_BUILDTIME_LEN]; +} nsfw_ver_info; + +typedef enum _nsfw_run_type +{ + NSFW_RUN_NULL = 0, + NSFW_RUN_FIRST = 1, + NSFW_RUN_NORMAL_RESTART, + NSFW_RUN_RESTART, + NSFW_RUN_STOP, + NSFW_RUN_FREQUENTLY +} nsfw_run_type; + +typedef enum _nsfw_init_state +{ + NSFW_INIT_SUCESS = 1, + NSFW_INIT_MEMADDR_ERR = 2 +} nsfw_init_state; + +typedef struct _nsfw_init_nty_msg +{ + nsfw_init_state init_state; + u16 rsp_code; +} nsfw_init_nty_msg; + +u8 nsfw_init_result_send(u8 local_proc, nsfw_init_state state, u8 rsp_flag); + +extern int g_cur_upg_state; +extern int g_start_type; + typedef enum _nsfw_exit_code { - NSFW_EXIT_SUCCESS = 0, - NSFW_EXIT_FAILED = 1, - NSFW_EXIT_DST_ERROR = 2, - NSFW_EXIT_TIME_OUT = 3, + NSFW_EXIT_SUCCESS = 0, + NSFW_EXIT_FAILED = 1, + NSFW_EXIT_DST_ERROR = 2, + NSFW_EXIT_TIME_OUT = 3, - NSFW_EXIT_MAX_COM_ERR = 31, + NSFW_EXIT_MAX_COM_ERR = 31, } nsfw_exit_code; +extern int nsfw_vermgr_module_init(void *param); /*#############################################*/ /*#################SOFT_PARAM##################*/ @@ -120,37 +194,69 @@ typedef enum _nsfw_exit_code typedef struct _nsfw_soft_param_msg { - u32 param_name; - u32 rsp_code; - u8 param_value[NSFW_MGR_MSG_BODY_LEN - sizeof (u32) - sizeof (u32)]; + u32 param_name; + u32 rsp_code; + u8 param_value[NSFW_MGR_MSG_BODY_LEN - sizeof(u32) - sizeof(u32)]; } nsfw_soft_param_msg; typedef enum _nsfw_soft_param { - NSFW_DBG_MODE_PARAM = 1, - NSFW_HBT_TIMER = 2, - NSFW_HBT_COUNT_PARAM = 3, - NSFW_APP_EXIT_TIMER = 4, - NSFW_SRV_RESTORE_TIMER = 5, - NSFW_APP_RESEND_TIMER = 6, - NSFW_APP_SEND_PER_TIME = 7, - - NSFW_MAX_SOFT_PARAM = 1024 + NSFW_DBG_MODE_PARAM = 1, + NSFW_HBT_TIMER = 2, + NSFW_HBT_COUNT_PARAM = 3, + NSFW_APP_EXIT_TIMER = 4, + NSFW_SRV_RESTORE_TIMER = 5, + NSFW_APP_RESEND_TIMER = 6, + NSFW_APP_SEND_PER_TIME = 7, + NSFW_TCP_OOSLE_PARAM = 8, + + NSFW_MAX_SOFT_PARAM = 1024 } nsfw_soft_param; typedef int (*nsfw_set_soft_fun) (u32 param, char *buf, u32 buf_len); -extern u8 nsfw_soft_param_reg_fun (u32 param_name, nsfw_set_soft_fun fun); -extern u8 nsfw_soft_param_reg_int (u32 param_name, u32 size, u32 min, - u32 max, u64 * data); +extern u8 nsfw_soft_param_reg_fun(u32 param_name, nsfw_set_soft_fun fun); +extern u8 nsfw_soft_param_reg_int(u32 param_name, u32 size, u32 min, u32 max, + u64 * data); -extern void nsfw_set_soft_para (fw_poc_type proc_type, u32 para_name, - void *value, u32 size); +extern void nsfw_set_soft_para(fw_poc_type proc_type, u32 para_name, + void *value, u32 size); -extern int nsfw_isdigitstr (const char *str); +extern int nsfw_isdigitstr(const char *str); #define NSFW_REG_SOFT_INT(_param,_data,_min, _max) nsfw_soft_param_reg_int(_param,sizeof(_data),_min,_max,(u64*)&_data) /*#############################################*/ +/*################# SPLNET ######################*/ +#define NSFW_FAU_INJ_MODULE "nsfw_splnet" + +typedef enum +{ + SPLNET_ACTION_NULL = 0, + SPLNET_ACTION_SETDROP, + SPLNET_ACTION_GETDROP, + SPLNET_ACTION_BONDSWITCH, + SPLNET_ACTION_GETBONDPRI, + SPLNET_ACTION_MAX +} splnet_action; + +#define MAX_NETIF_NAME_LEN 256 +#define MAX_NETIF_NUM 32 + +typedef struct _nsfw_splnet_msg +{ + struct timeval start_time; + splnet_action action; + char name[MAX_NETIF_NAME_LEN]; //means eth list when fault_inject, or network name when bondswitch + int drop_numer; + int drop_denom; + int exp_time; +} nsfw_splnet_msg; + +extern struct netif_fault_ctl *alloc_netif_fault_ctl_entry(); +extern bool do_drop_packet(struct netif_fault_ctl *fault_ctl); + +/*#############################################*/ + /*#################LOG_CONFIG##################*/ #define NSFW_LOG_CFG_MODULE "nsfw_log_cfg" @@ -160,9 +266,9 @@ extern int nsfw_isdigitstr (const char *str); typedef struct _nsfw_set_log_msg { - u16 rsp_code; - char module[NSFW_MODULE_NAME_LEN]; - char log_level[NSFW_LOG_VALUE_LEN]; + u16 rsp_code; + char module[NSFW_MODULE_NAME_LEN]; + char log_level[NSFW_LOG_VALUE_LEN]; } nsfw_set_log_msg; /*#############################################*/ @@ -174,38 +280,55 @@ typedef struct _nsfw_set_log_msg #define SPL_DFX_RES_CONN "conn" #define SPL_DFX_RES_L2TO4 "l2to4" #define SPL_DFX_RES_UNMATCH "version" -#define SPL_DFX_RES_SOCKET_CB "socketcb" -#define SPL_DFX_RES_COMM_MEMPOOL "mbufpool" +#define SPL_DFX_RES_SOCKT_CB "socketcb" +#define SPL_DFX_RES_RTP_MEMPOOL "mbufpool" #define SPL_DFX_RES_PCBLIST "pcblist" #define SPL_DFX_RES_ARPLIST "arplist" typedef enum { - DFX_ACTION_SNAPSHOT, - DFX_ACTION_RST_STATS, - DFX_ACTION_SWITCH, - DFX_ACTION_MAX + DFX_ACTION_SNAPSHOT, + DFX_ACTION_RST_STATS, + DFX_ACTION_SWITCH, + DFX_ACTION_GET_CONTAINER_STAT, + DFX_ACTION_GET_CONTAINER_L4_STAT, + DFX_ACTION_MAX } dfx_module_action; typedef struct _nsfw_dfx_qry_msg { - dfx_module_action action; - char resource[MAX_DFX_QRY_RES_LEN]; - char flag; //for snapshot print "all" + dfx_module_action action; + char resource[MAX_DFX_QRY_RES_LEN]; + char flag; //for snapshot print "all" } nsfw_dfx_qry_msg; +typedef struct _nsfw_dfx_qry_container_stat_msg +{ + dfx_module_action action; + char container_id[256]; //TODO +} nsfw_dfx_qry_container_stat_msg; + typedef enum { - QUERY_ACTION_GET, - QUERY_ACTION_MAX + QUERY_ACTION_GET, + QUERY_ACTION_MAX } query_action; typedef struct _nsfw_qry_msg { - query_action action; - char resource[MAX_DFX_QRY_RES_LEN]; + query_action action; + char resource[MAX_DFX_QRY_RES_LEN]; } nsfw_get_qry_msg; +typedef enum _qry_errcode +{ + QUERY_OK = 0, + QUERY_INTERNAL_ERR = 1, + QUERY_CONTAINER_STAT_NOT_SURPPORTED = 32, + QUERY_NO_SUCH_CONTAINER = 33, + QUERY_ERR_MAX = 127 +} qry_errcode; + /*##################DFX#########################*/ /*#################for tcpdump#####################*/ @@ -219,10 +342,20 @@ typedef struct _nsfw_qry_msg #define TCPDUMP_MODULE "tcpdump_tool" -#define DUMP_MSG_NUM (64 * 1024) -COMPAT_PROTECT (DUMP_MSG_NUM, 64 * 1024); +#define MIN_DUMP_MSG_NUM (4 * 1024) +#define MAX_DUMP_MSG_NUM (64 * 1024) + +#define DUMP_NO_LIMIT 0 //must be set to 0 dumping only packets header for release + +/* *INDENT-OFF* */ +#if DUMP_NO_LIMIT +#define DUMP_MSG_SIZE 1515 // can not be less than 14 +COMPAT_PROTECT_RETURN (DUMP_MSG_SIZE, 1515) +#else #define DUMP_MSG_SIZE 128 // can not be less than 14 -COMPAT_PROTECT (DUMP_MSG_SIZE, 128); +COMPAT_PROTECT_RETURN (DUMP_MSG_SIZE, 128) +#endif +/* *INDENT-ON* */ #define DEFAULT_DUMP_TIME 600 #define MAX_DUMP_TIME 86400 @@ -233,84 +366,492 @@ COMPAT_PROTECT (DUMP_MSG_SIZE, 128); #define DUMP_HBT_CHK_INTERVAL 4 #define DUMP_TASK_HBT_TIME_OUT 30 -#define DUMP_SHMEM_RIGN_NAME "tcpdump_ring" +#define DUMP_SHMEM_RING_NAME "tcpdump_ring" #define DUMP_SHMEM_POOL_NAME "tcpdump_pool" +/* for multi-dump */ +#define DUMP_SHMEM_INFO_NAME_MST "tcpdump_infozone_mst" +#define DUMP_SHMEM_INFO_NAME_SLV "tcpdump_infozone_slv" + +#define DUMP_SHMEM_RING_NAME_MST "tcpdump_ring_mst" +#define DUMP_SHMEM_POOL_NAME_MST "tcpdump_pool_mst" + +#define DUMP_SHMEM_RING_NAME_SLV_0 "tcpdump_ring_slv_0" +#define DUMP_SHMEM_POOL_NAME_SLV_0 "tcpdump_pool_slv_0" +#define DUMP_SHMEM_RING_NAME_SLV_1 "tcpdump_ring_slv_1" +#define DUMP_SHMEM_POOL_NAME_SLV_1 "tcpdump_pool_slv_1" +#define DUMP_SHMEM_RING_NAME_SLV_2 "tcpdump_ring_slv_2" +#define DUMP_SHMEM_POOL_NAME_SLV_2 "tcpdump_pool_slv_2" +#define DUMP_SHMEM_RING_NAME_SLV_3 "tcpdump_ring_slv_3" +#define DUMP_SHMEM_POOL_NAME_SLV_3 "tcpdump_pool_slv_3" + enum L2_PROTOCOL { - PROTOCOL_IP = 0x0800, - PROTOCOL_ARP = 0x0806, - PROTOCOL_RARP = 0x8035, - PROTOCOL_OAM_LACP = 0x8809, - INVALID_L2_PROTOCOL = 0xFFFF + PROTOCOL_IP = 0x0800, + PROTOCOL_ARP = 0x0806, + PROTOCOL_RARP = 0x8035, + PROTOCOL_IPV6 = 0x86DD, + PROTOCOL_OAM_LACP = 0x8809, + INVALID_L2_PROTOCOL = 0xFFFF }; enum L3_PROTOCOL { - PROTOCOL_ICMP = 1, - PROTOCOL_TCP = 6, - PROTOCOL_UDP = 17, - INVALID_L3_PROTOCOL = 0xFF + PROTOCOL_ICMP = 1, + PROTOCOL_TCP = 6, + PROTOCOL_UDP = 17, + INVALID_L3_PROTOCOL = 0xFF }; enum DUMP_MSG_DIRECTION { - DUMP_SEND = 1, - DUMP_RECV = 2, - DUMP_SEND_RECV = 3 + DUMP_SEND = 1, + DUMP_RECV = 2, + DUMP_SEND_RECV = 3 }; enum DUMP_MSG_TYPE { - START_DUMP_REQ, - STOP_DUMP_REQ, - TOOL_COM_HBT_REQ, + START_DUMP_REQ, + STOP_DUMP_REQ, + TOOL_COM_HBT_REQ, + START_DUMP_MASTER_REQ, - DUMP_MSG_TYPE_RSP = 0x00010000, + DUMP_MSG_TYPE_RSP = 0x00010000, //65536 - START_DUMP_RSP = START_DUMP_REQ + DUMP_MSG_TYPE_RSP, - STOP_DUMP_RSP = STOP_DUMP_REQ + DUMP_MSG_TYPE_RSP, + START_DUMP_RSP = START_DUMP_REQ + DUMP_MSG_TYPE_RSP, + STOP_DUMP_RSP = STOP_DUMP_REQ + DUMP_MSG_TYPE_RSP, + TOOL_COM_HBT_RSP = TOOL_COM_HBT_REQ + DUMP_MSG_TYPE_RSP, + START_DUMP_MASTER_RSP = START_DUMP_MASTER_REQ + DUMP_MSG_TYPE_RSP, - DUMP_MSG_TYPE_INVALID + DUMP_MSG_TYPE_INVALID }; typedef struct _nsfw_tool_hbt { - u32 seq; - i16 task_id; + u32 seq; + i16 task_id; } nsfw_tool_hbt; typedef struct _nsfw_tool_dump_msg { - u16 op_type; - i16 task_id; - u32 task_keep_time; + u16 op_type; + i16 task_id; + u32 task_keep_time; } nsfw_tool_dump_msg; typedef struct _dump_msg_info { - u32 len; - u16 direction; // 1:SEND, 2:RECV - u32 dump_sec; - u32 dump_usec; - nsfw_res res_chk; - char buf[1]; + u32 org_len; + u16 direction; // 1:SEND, 2:RECV + u32 dump_sec; + u32 dump_usec; + u32 len; + nsfw_res res_chk; + char buf[1]; } dump_msg_info; typedef struct _dump_timer_info { - u32 seq; - i16 task_id; - void *interval; - void *ptimer; + u32 seq; + i16 task_id; + void *interval; + void *ptimer; } dump_timer_info; -extern void ntcpdump_loop (void *buf, u32 buf_len, u16 direction, - void *eth_addr); -extern void ntcpdump (void *buf, u32 buf_len, u16 direction); +extern void ntcpdump_loop(void *buf, u32 buf_len, u16 direction, + void *eth_addr); +extern void ntcpdump(void *buf, u32 buf_len, u16 direction); +extern int get_dump_status(char *jbuf, int pid); /*##############for tcpdump######################*/ +/*################# HOTFIX Begin ##################*/ +#define NSFW_HOTFIX_MODULE "nsfw_hotfix" +#define ALARM_HOTFIX_NAME "hotfix" + +#define MAX_PATCH_PATH_LEN 256 +#define MAX_PATCH_VER_LEN 64 + +#define HOTFIX_STR_ACTV "activate" +#define HOTFIX_STR_ROLLBACK "rollback" +#define HOTFIX_STR_QUERY "query" + +#define HOTFIX_STR_SUCCESS "success" +#define HOTFIX_STR_FAIL "fail" + +#define HOTFIX_SUCCESS 0 +#define HOTFIX_FAIL 1 + +/* hotfix operation type */ +typedef enum +{ + HOTFIX_IDLE, //invalid value, not use + HOTFIX_ACTV, //activate: load & activate & run a patch + HOTFIX_ROLLBACK, //rollback: remove a patch + HOTFIX_QUERY, //query: query product version + HOTFIX_MAX +} hotfix_optype; + +typedef struct _nsfw_hotfix_msg +{ + u16 rsp_code; + hotfix_optype optype; + char patch_path[MAX_PATCH_PATH_LEN]; + char patch_version[MAX_PATCH_VER_LEN]; //product's patch version +} nsfw_hotfix_msg; + +typedef struct _hotfix_res +{ + fw_poc_type proc_type; //process type + hotfix_optype action; + int result; + char patch_version[MAX_PATCH_VER_LEN]; //product's patch version +} hotfix_res; + +extern int nsfw_hotfix_module_init(void *param); +/*################# HOTFIX End##################*/ +#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_THREAD_NUM = 0, + CFG_BASE_SOCKET_NUM, + CFG_BASE_RING_SIZE, + CFG_BASE_HAL_PORT_NUM, + CFG_BASE_ARP_STALE_TIME, + CFG_BASE_ARP_BC_RETRANS_NUM, + MAX_BASE_CFG +}; +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (MAX_BASE_CFG, 6) +/* *INDENT-ON* */ + +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_ACCEPT_RING_SIZE, + + /* PCB config */ + CFG_TCP_PCB_NUM, + CFG_UDP_PCB_NUM, + CFG_RAW_PCB_NUM, + + CFG_ARP_QUEUE_NUM, + + MAX_CUSTOM_CFG +}; + +enum EN_CFG_SEG +{ + CFG_SEG_BASE = 0, + CFG_SEG_LOG, + CFG_SEG_PATH, + CFG_SEG_PRI, + CFG_SEG_FOR_MACRO, + CFG_SEG_PARAM, + EN_CFG_SEG, + CFG_SEG_TCP, + CFG_SEG_SYNC, + CFG_SEG_RET, + CFG_SEG_MAX +}; + +enum EN_CFG_ITEM_TYPE +{ + CFG_ITEM_TYPE_INT = 0, + CFG_ITEM_TYPE_STRING +}; + +enum EN_SEG_BASE_ITEM +{ + CFG_ITEM_BASE_SOCKET_NUM = 0, + CFG_ITEM_BASE_ARP_STALE_TIME, + CFG_ITEM_BASE_ARP_BC_RETRANS_NUM, + CFG_ITEM_BASE_APP_SOCKET_NUM, + CFG_ITEM_BASE_RING_BASE_SIZE, + CFG_ITEM_BASE_TCP_PCB_NUM, + CFG_ITEM_BASE_UDP_PCB_NUM, + CFG_ITEM_BASE_RAW_PCB_NUM, + CFG_ITEM_BASE_SPL_MAX_RING_SIZE, + CFG_ITEM_BASE_ARP_QUEUE_NUM, + CFG_ITEM_BASE_DUMP_MSG_NUM, + CFG_ITEM_BASE_TX_MBUF_POOL_SIZE, + CFG_ITEM_BASE_PKT_BURT_NUM, + CFG_ITEM_BASE_MAX +}; + +enum EN_SEG_TCP_ITEM +{ + CFG_ITEM_TCP_SYN_REXMIT_INTERVAL_MS = 0, + CFG_ITEM_TCP_SYN_REXMIT_TIMES, + CFG_ITEM_TCP_ESTABLISHED_REXMIT_TIMES, + CFG_ITEM_TCP_MAX +}; + +enum EN_SEG_THREAD_PRI_ITEM +{ + CFG_ITEM_THREAD_PRI_POLICY = 0, + CFG_ITEM_THREAD_PRI_PRI, + CFG_ITEM_THREAD_PRI_MAX +}; + +enum EN_SEG_FOR_MACRO_ITEM +{ + CFG_ITEM_C10M_SUPPORT = 0, + CFG_ITEM_FOR_MACRO_MAX +}; + +enum EN_SEG_MACRO_CUSTOM +{ + CFG_SBR_FD_NETCONN_SIZE = 0, + CFG_SS_NETCONN_SIZE, + CFG_DEF_APP_SOCKET_NUM, + CFG_SOCKET_NUM_PER_THREAD, + CFG_MAX_SOCKET_NUM, // same as socket num + CFG_APP_POOL_NUM, + CFG_MAX_TCP_HASH_SIZE, + CFG_DEF_RX_MBUF_POOL_SIZE, // from POOL_RING_BASE_SIZE + CFG_DEF_TX_MBUF_POOL_SIZE, + CFG_MAX_LISTEN_SOCKET_NUM, + CFG_DEF_SPL_MAX_ACCEPT_RING_SIZE, + CFG_DEF_TCP_PCB_NUM, + CFG_DEF_UDP_PCB_NUM, + CFG_DEF_RAW_PCB_NUM, + CFG_MAX_EPOLL_NUM, + CFG_MAX_EPITEM_NUM, + CFG_MAX_SOCK_FOR_KERNEL, + CFG_MAX_SOCK_FOR_STACK, + CFG_DEF_SPL_MAX_RING_SIZE, + CFG_DEF_HAL_RX_RING_SIZE, + CFG_DEF_TX_MSG_POOL_SIZE, + CFG_DEF_MBOX_RING_SIZE, + CFG_DEF_MPTCP_VERSION, + CFG_ITEM_MACRO_CUSTOM_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]; +extern u32 g_macro_custom_cfg_items[CFG_ITEM_MACRO_CUSTOM_MAX]; +extern struct cfg_item_info g_cfg_item_info[CFG_SEG_MAX][MAX_CFG_ITEM]; + +#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) + +/* stackpool config data definition */ +#ifndef C10M_SUPPORT +#define C10M_SUPPORT get_cfg_info(CFG_SEG_FOR_MACRO, CFG_ITEM_C10M_SUPPORT) +#endif + +#define CFG(item) g_macro_custom_cfg_items[item] +/* + MAX_SOCKET_NUM: max socket fd number one app can use, it should equal the max socket + number nstack support(CUR_CFG_SOCKET_NUM) +*/ + +/* *INDENT-OFF* */ +#define DEF_SOCKET_NUM 1024 /* default socket number */ +COMPAT_PROTECT_RETURN (DEF_SOCKET_NUM, 1024) +#define MIN_SOCKET_NUM 1024 /* min socket number */ +/* *INDENT-ON* */ + +#define MAX_SOCKET_NUM 8192 /* default: 8K sockets */ +#define CUR_CFG_SOCKET_NUM get_base_cfg(CFG_BASE_SOCKET_NUM) /* max socket number nstack support */ + +/* socket num per instance, CUR_CFG_THREAD_NUM should be 2^n */ +#define INSTANCE_SOCKET_NUM (CUR_CFG_SOCKET_NUM/CUR_CFG_THREAD_NUM) + +#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) + +/* thread number config */ +#define DEF_THREAD_NUM 1 /* default stackpool thread number */ +#define MIN_THREAD_NUM 1 /* min thread number */ +#define MAX_THREAD_NUM 8 +#define CUR_CFG_THREAD_NUM get_base_cfg(CFG_BASE_THREAD_NUM) + +/* use GLOBAL_THREAD_INDEX to create socket in apps */ +#define GLOBAL_THREAD_INDEX 0 + +/* hal port number config */ +#define DEF_HAL_PORT_NUM 20 /* port number */ +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (DEF_HAL_PORT_NUM, 20) +/* *INDENT-ON* */ +#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 */ +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (MAX_VF_NUM, 4) +/* *INDENT-ON* */ + +/* base ring size config */ +#define DEF_RING_BASE_SIZE 2048 /* base ring size */ +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (DEF_RING_BASE_SIZE, 2048) +/* *INDENT-ON* */ +#define MIN_RING_BASE_SIZE 1024 +#define MAX_RING_BASE_SIZE 4096 +#define POOL_RING_BASE_SIZE get_base_cfg(CFG_BASE_RING_SIZE) + +#define RX_MBUF_MID_THRESHOLD RX_MBUF_POOL_SIZE/4 +#define RX_MBUF_MIN_THRESHOLD RX_MBUF_POOL_SIZE/16 + +/* mbuf data size config */ +#define DEF_MBUF_DATA_SIZE 2048 /* mbuf data size */ +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (DEF_MBUF_DATA_SIZE, 2048) +/* *INDENT-ON* */ +#define TX_MBUF_MAX_LEN get_custom_cfg(CFG_MBUF_DATA_SIZE) +/* ptk/task burst config */ +#define MAX_PKT_BURST 512 +#define MIN_PKT_BURST 1 +#define DEF_PKT_BURST 32 +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (DEF_PKT_BURST, 32) +/* *INDENT-ON* */ + +/*tcp related param*/ +#define SPL_TCP_SYN_RTX_INTVAL ((u32)get_cfg_info(CFG_SEG_TCP, CFG_ITEM_TCP_SYN_REXMIT_INTERVAL_MS)) +#define SPL_TCP_SYNMAXRTX ((u32)get_cfg_info(CFG_SEG_TCP, CFG_ITEM_TCP_SYN_REXMIT_TIMES)) +#define SPL_TCP_MAXRTX ((u32)get_cfg_info(CFG_SEG_TCP, CFG_ITEM_TCP_ESTABLISHED_REXMIT_TIMES)) + +/* tx mbuf pool size config */ +#define TX_MBUF_POOL_SIZE get_custom_cfg(CFG_TX_MBUF_NUM) +#define RX_MBUF_POOL_SIZE get_custom_cfg(CFG_RX_MBUF_NUM) + +#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) + +/* stackpool recv ring size config */ + +#define SPL_MAX_RING_SIZE (u32)get_cfg_info(CFG_SEG_BASE, CFG_ITEM_BASE_SPL_MAX_RING_SIZE) /* ring size config, used in recv ring(per socket) */ + +#define MIN_ARP_QUEUE_NUM 300 +#define LARGE_ARP_QUEUE_NUM (512*1024) +#define CUR_ARP_QUEUE_NUM (u32)get_cfg_info(CFG_SEG_BASE, CFG_ITEM_BASE_ARP_QUEUE_NUM) + +#define CUR_CFG_DEF_TCP_PCB_NUM (u32)get_cfg_info(CFG_SEG_BASE, CFG_ITEM_BASE_TCP_PCB_NUM) +#define CUR_CFG_DEF_UDP_PCB_NUM (u32)get_cfg_info(CFG_SEG_BASE, CFG_ITEM_BASE_UDP_PCB_NUM) +#define CUR_CFG_DEF_RAW_PCB_NUM (u32)get_cfg_info(CFG_SEG_BASE, CFG_ITEM_BASE_RAW_PCB_NUM) + +/* tcp seg number config */ + /* seg num = txbuf num + rxbuf num, and mptcp may double, so set it to txbuf num * 4 */ +#define DEF_MEMP_NUM_TCP_SEG (4 * CFG(CFG_APP_POOL_NUM) * CFG(CFG_DEF_TX_MBUF_POOL_SIZE)) + +#define TX_MSG_POOL_SIZE get_custom_cfg(CFG_MP_MSG_NUM) /* msg number, used by stackpool internal, per thread */ + +#define MBOX_RING_SIZE get_custom_cfg(CFG_MBOX_RING_SIZE) /* mbox ring size config, per thread */ + +#define MIN_DUMP_MSG_NUM (4 * 1024) +#define MAX_DUMP_MSG_NUM (64 * 1024) + +/*some problem if CUSOTM_RECV_RING_SIZE more than 4096*/ +#define CUSOTM_RECV_RING_SIZE 4096 +/* *INDENT-OFF* */ +COMPAT_PROTECT_RETURN (CUSOTM_RECV_RING_SIZE, 4096) +/* *INDENT-ON* */ + +u32 get_cfg_info(int tag, int item); +u32 get_cfg_share_mem_size(); + +int get_share_cfg_from_mem(void *mem); + +void get_default_base_cfg(u32 thread_num); + +int set_share_cfg_to_mem(void *mem); + +void config_module_init(cfg_module_param * param); + +/*##############for netstat######################*/ +typedef enum _netstat_protocol_type +{ + NETSTAT_TCP_UDP_CONN, + NETSTAT_TCP_CONN, + NETSTAT_UDP_CONN +} netstat_protocol_type; + +typedef struct _netstat_send_para +{ + netstat_protocol_type protocol_type; /*0:all; 1:TCP; 2:UDP */ + unsigned int instance_flag; /*0: all instance; 1:specific instance */ + int instance_id; +} netstat_send_para; + +typedef struct _netstat_data_info +{ + unsigned int local_addr; + unsigned int remote_addr; + unsigned short local_port; + unsigned short remote_port; + unsigned short state; + unsigned short resv; +} netstat_data_info; + +typedef struct _netstat_info +{ + unsigned int pcb_num; + netstat_data_info data[10240]; +} netstat_info; + #ifdef __cplusplus /* *INDENT-OFF* */ } diff --git a/src/framework/include/nsfw_mem_api.h b/src/framework/include/nsfw_mem_api.h index db7f5e7..f22fd32 100644 --- a/src/framework/include/nsfw_mem_api.h +++ b/src/framework/include/nsfw_mem_api.h @@ -22,18 +22,35 @@ #include "types.h" #include "nsfw_mgr_com_api.h" #include "nstack_log.h" +#include <unistd.h> +#include <string.h> #define NSFW_MEM_MGR_MODULE "nsfw_mem_mgr" /* *the max len of memory name is 32bytes, but app just can use max 22bytes, left 10bytes to memory manager module */ -#define NSFW_MEM_NAME_LENGTH (32) -#define NSFW_MEM_APPNAME_LENGTH (22) +#define NSFW_MEM_NAME_LENTH (32) +#define NSFW_MEM_APPNAME_LENTH (22) #define NSFW_SOCKET_ANY (-1) -#define NSFW_MEM_OK (0) -#define NSFW_MEM_ERR (-1) + +#define NSFW_MEM_NOT_INIT (0) +#define NSFW_MEM_INIT_ERR (1) +#define NSFW_MEM_INIT_OK (2) + +/* + * type of init error + */ +typedef enum +{ + NSFW_MEM_ERR_MISALIGN = -2, + NSFW_MEM_ERR = -1, + NSFW_MEM_OK = 0, + NSFW_MEM_RTP_FAIL = 1, /* init rtp fail */ + NSFW_MEM_MALLOC_FAIL = 2, /* mem alloc fail */ + NSFW_MEM_MEMSET_FAIL = 3, +} nsfw_init_errno; /* *type of memory: @@ -42,20 +59,20 @@ */ typedef enum { - NSFW_SHMEM, - NSFW_NSHMEM, - NSFW_MEM_TYPEMAX, + NSFW_SHMEM, + NSFW_NSHMEM, + NSFW_MEM_TYPEMAX, } nsfw_mem_type; /*type of ring operation*/ typedef enum { - NSFW_MRING_SPSC, /*single producer single consumer ring */ - NSFW_MRING_MPSC, /*multi producer single consumer ring */ - NSFW_MRING_SPMC, /*single producer multi consumer ring */ - NSFW_MRING_MPMC, /*multi producer multi consumer ring */ - NSFW_MRING_SPSC_ST, /*single producer single consumer and belong to one thread ring */ - NSFW_MPOOL_TYPEMAX, + NSFW_MRING_SPSC, /*sigle producer sigle consumer ring */ + NSFW_MRING_MPSC, /*multi producer sigle consumer ring */ + NSFW_MRING_SPMC, /*sigle producer multi consumer ring */ + NSFW_MRING_MPMC, /*multi producer multi consumer ring */ + NSFW_MRING_SPSC_ST, /*single producer single consumer and belong to one thread ring */ + NSFW_MPOOL_TYPEMAX, } nsfw_mpool_type; typedef void *mpool_handle; @@ -66,169 +83,190 @@ typedef void *mring_handle; /*initial of param*/ typedef struct { - i32 iargsnum; - i8 **pargs; - fw_poc_type enflag; /*app, nStackMain, Master */ + i32 iargsnum; + i8 **pargs; + fw_poc_type enflag; /*app, daemon-stack, Master */ } nsfw_mem_para; typedef struct { - nsfw_mem_type entype; - fw_poc_type enowner; /*notes: 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, + nsfw_mem_type entype; + fw_poc_type enowner; /*notes: 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, * end with null created by nStackMaster, and end with _<pid> created by other. * 2. pname->enowner is available only when call look up shared memory. * 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, * the name must be full name. - * for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, + * for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, * must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add * _(pid) at the end of name, nstack_123. */ - i8 aname[NSFW_MEM_NAME_LENGTH]; /*the length of name must be less than NSFW_MEM_APPNAME_LENGTH. */ + i8 aname[NSFW_MEM_NAME_LENTH]; /*the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ } nsfw_mem_name; typedef struct { - nsfw_mem_name stname; - size_t length; - i32 isocket_id; - i32 ireserv; + nsfw_mem_name stname; + size_t lenth; + i32 isocket_id; + i32 ireserv; } nsfw_mem_zone; typedef struct { - nsfw_mem_name stname; - unsigned usnum; /*the really created mbfpool num is (num+1) power of 2 */ - unsigned uscash_size; - unsigned uspriv_size; - unsigned usdata_room; - i32 isocket_id; - nsfw_mpool_type enmptype; + nsfw_mem_name stname; + unsigned usnum; /*the really created mbfpool num is (num+1) power of 2 */ + unsigned uscash_size; + unsigned uspriv_size; + unsigned usdata_room; + i32 isocket_id; + nsfw_mpool_type enmptype; } nsfw_mem_mbfpool; typedef struct { - nsfw_mem_name stname; - u32 usnum; /*the really created sppool num is (num+1) power of 2 */ - u32 useltsize; - i32 isocket_id; - nsfw_mpool_type enmptype; + nsfw_mem_name stname; + u32 usnum; /*the really created sppool num is (num+1) power of 2 */ + u32 useltsize; + i32 isocket_id; + nsfw_mpool_type enmptype; } nsfw_mem_sppool; typedef struct { - nsfw_mem_name stname; - u32 usnum; /*the really created ring num is (num+1) power of 2 */ - i32 isocket_id; - nsfw_mpool_type enmptype; + nsfw_mem_name stname; + u32 usnum; /*the really created ring num is (num+1) power of 2 */ + i32 isocket_id; + nsfw_mpool_type enmptype; } nsfw_mem_mring; typedef enum { - NSFW_MEM_ALLOC_SUCC = 1, - NSFW_MEM_ALLOC_FAIL = 2, + NSFW_MEM_ALLOC_SUCC = 1, + NSFW_MEM_ALLOC_FAIL = 2, } nsfw_mem_alloc_state; typedef enum { - NSFW_MEM_MZONE, - NSFW_MEM_MBUF, - NSFW_MEM_SPOOL, - NSFW_MEM_RING + NSFW_MEM_MZONE, + NSFW_MEM_MBUF, + NSFW_MEM_SPOOL, + NSFW_MEM_RING } nsfw_mem_struct_type; typedef enum { - NSFW_RESERV_REQ_MSG, - NSFW_RESERV_ACK_MSG, - NSFW_MBUF_REQ_MSG, - NSFW_MBUF_ACK_MSG, - NSFW_SPPOOL_REQ_MSG, - NSFW_SPPOOL_ACK_MSG, - NSFW_RING_REQ_MSG, - NSFW_RING_ACK_MSG, - NSFW_RELEASE_REQ_MSG, - NSFW_RELEASE_ACK_MSG, - NSFW_MEM_LOOKUP_REQ_MSG, - NSFW_MEM_LOOKUP_ACK_MSG, - NSFW_MEM_MAX_MSG + NSFW_RESERV_REQ_MSG, + NSFW_RESERV_ACK_MSG, + NSFW_MBUF_REQ_MSG, + NSFW_MBUF_ACK_MSG, + NSFW_SPPOOL_REQ_MSG, + NSFW_SPPOOL_ACK_MSG, + NSFW_RING_REQ_MSG, + NSFW_RING_ACK_MSG, + NSFW_RELEASE_REQ_MSG, + NSFW_RELEASE_ACK_MSG, + NSFW_MEM_LOOKUP_REQ_MSG, + NSFW_MEM_LOOKUP_ACK_MSG, + NSFW_MEM_MAX_MSG } nsfw_remote_msg; typedef struct __nsfw_shmem_msg_head { - unsigned usmsg_type; - unsigned uslength; - i32 aidata[0]; + unsigned usmsg_type; + unsigned uslenth; + + i32 aidata[0]; + } nsfw_shmem_msg_head; typedef struct __nsfw_shmem_ack { - void *pbase_addr; - u16 usseq; - i8 cstate; - i8 creserv; - i32 ireserv; + void *pbase_addr; + u16 usseq; + i8 cstate; + i8 creserv; + i32 ireserv; } nsfw_shmem_ack; typedef struct __nsfw_shmem_reserv_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 usreserv; - i32 isocket_id; - size_t length; - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 usreserv; + i32 isocket_id; + size_t lenth; + i32 ireserv; } nsfw_shmem_reserv_req; typedef struct __nsfw_shmem_mbuf_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 enmptype; - unsigned usnum; - unsigned uscash_size; - unsigned uspriv_size; - unsigned usdata_room; - i32 isocket_id; - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 enmptype; + unsigned usnum; + unsigned uscash_size; + unsigned uspriv_size; + unsigned usdata_room; + i32 isocket_id; + i32 ireserv; } nsfw_shmem_mbuf_req; typedef struct __nsfw_shmem_sppool_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 enmptype; - u32 usnum; - u32 useltsize; - i32 isocket_id; - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 enmptype; + u32 usnum; + u32 useltsize; + i32 isocket_id; + i32 ireserv; } nsfw_shmem_sppool_req; typedef struct __nsfw_shmem_ring_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 enmptype; - u32 usnum; - i32 isocket_id; - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 enmptype; + u32 usnum; + i32 isocket_id; + i32 ireserv; } nsfw_shmem_ring_req; typedef struct __nsfw_shmem_free_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 ustype; /*structure of memory(memzone,mbuf,mpool,ring) */ - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 ustype; /*structure of memory(memzone,mbuf,mpool,ring) */ + i32 ireserv; } nsfw_shmem_free_req; typedef struct __nsfw_shmem_lookup_req { - i8 aname[NSFW_MEM_NAME_LENGTH]; - u16 usseq; - u16 ustype; /*structure of memory(memzone,mbuf,mpool,ring) */ - i32 ireserv; + i8 aname[NSFW_MEM_NAME_LENTH]; + u16 usseq; + u16 ustype; /*structure of memory(memzone,mbuf,mpool,ring) */ + i32 ireserv; } nsfw_shmem_lookup_req; +typedef struct __nsfw_mem_ring_health_info +{ + struct + { + u32 head; //Head of the Ring, used to indicate pos where to pull a val + u32 tail; //for nshmem, shmem not used. + } prod; + struct + { + u32 head; //for nshmem, shmem not used. + u32 tail; //Tail of the Ring, used to indicate pos where to push a val + } cons; + struct timeval overflow_time; + u32 size; + u32 mask; + u16 overflow_count; + +} nsfw_mem_ring_health_info; + typedef int (*nsfw_mem_ring_enqueue_fun) (mring_handle ring, void *box); typedef int (*nsfw_mem_ring_dequeue_fun) (mring_handle ring, void **box); typedef int (*nsfw_mem_ring_dequeuev_fun) (mring_handle ring, void **box, @@ -236,200 +274,190 @@ typedef int (*nsfw_mem_ring_dequeuev_fun) (mring_handle ring, void **box, typedef struct { - nsfw_mem_ring_enqueue_fun ring_ops_enqueue; - nsfw_mem_ring_dequeue_fun ring_ops_dequeue; - nsfw_mem_ring_dequeuev_fun ring_ops_dequeuev; + nsfw_mem_ring_enqueue_fun ring_ops_enqueue; + nsfw_mem_ring_dequeue_fun ring_ops_dequeue; + nsfw_mem_ring_dequeuev_fun ring_ops_dequeuev; } nsfw_ring_ops; /* * memory module init - * para:point to nstack_fwmem_para + * para:point to nstak_fwmem_para */ -i32 nsfw_mem_init (void *para); +i32 nsfw_mem_init(void *para); /* * create a block memory with name * nsfw_mem_zone::stname * nsfw_mem_zone::isize - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -mzone_handle nsfw_mem_zone_create (nsfw_mem_zone * pinfo); +mzone_handle nsfw_mem_zone_create(nsfw_mem_zone * pinfo); /* *create some memory blocks - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_zone_createv (nsfw_mem_zone * pmeminfo, i32 inum, - mzone_handle * paddr_array, i32 iarray_num); +i32 nsfw_mem_zone_createv(nsfw_mem_zone * pmeminfo, i32 inum, + mzone_handle * paddr_array, i32 iarray_num); /* *look up a memory - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. * 2. if the memory is shared, pname->enowner indicate that who create this memory, * note: - * 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, + * 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, * end with none created by nStackMaster, and end with _<pid> created by other. * 2. pname->enowner is available only when call look up shared memory. * 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, * the name must be full name. - * for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, + * for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, * must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add * _(pid) at the end of name, nstack_123. */ -mzone_handle nsfw_mem_zone_lookup (nsfw_mem_name * pname); +mzone_handle nsfw_mem_zone_lookup(nsfw_mem_name * pname); /*release a memory*/ -i32 nsfw_mem_zone_release (nsfw_mem_name * pname); +i32 nsfw_mem_zone_release(nsfw_mem_name * pname); /* *create a mbuf pool */ -mpool_handle nsfw_mem_mbfmp_create (nsfw_mem_mbfpool * pbufinfo); +mpool_handle nsfw_mem_mbfmp_create(nsfw_mem_mbfpool * pbufinfo); /* *create some mbuf pools - * note: 1. the name of length must be less than NSFW_MEM_APPNAME_LENGTH. - */ -i32 nsfw_mem_mbfmp_createv (nsfw_mem_mbfpool * pmbfname, i32 inum, - mpool_handle * phandle_array, i32 iarray_num); - -/* - *alloc a mbuf from mbuf pool + * note: 1. the name of lenth must be less than NSFW_MEM_APPNAME_LENTH. */ -mbuf_handle nsfw_mem_mbf_alloc (mpool_handle mhandle, nsfw_mem_type entype); - -/* - *put a mbuf backintp mbuf pool - */ -i32 nsfw_mem_mbf_free (mbuf_handle mhandle, nsfw_mem_type entype); +i32 nsfw_mem_mbfmp_createv(nsfw_mem_mbfpool * pmbfname, i32 inum, + mpool_handle * phandle_array, i32 iarray_num); /* *look up mbuf mpool - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. * 2. if the memory is shared, pname->enowner indicate that who create this memory. * note: - * 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, + * 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, * end with none created by nStackMaster, and end with _<pid> created by other. * 2. pname->enowner is available only when call look up shared memory. * 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, * the name must be full name. - * for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, + * for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, * must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add * _(pid) at the end of name, nstack_123. */ -mpool_handle nsfw_mem_mbfmp_lookup (nsfw_mem_name * pmbfname); +mpool_handle nsfw_mem_mbfmp_lookup(nsfw_mem_name * pmbfname); /* *release mbuf pool - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_mbfmp_release (nsfw_mem_name * pname); +i32 nsfw_mem_mbfmp_release(nsfw_mem_name * pname); /* *create a simple pool - *note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + *note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -mring_handle nsfw_mem_sp_create (nsfw_mem_sppool * pmpinfo); +mring_handle nsfw_mem_sp_create(nsfw_mem_sppool * pmpinfo); /* *create some simple pools one time - *note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + *note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_sp_createv (nsfw_mem_sppool * pmpinfo, i32 inum, - mring_handle * pringhandle_array, i32 iarray_num); +i32 nsfw_mem_sp_createv(nsfw_mem_sppool * pmpinfo, i32 inum, + mring_handle * pringhandle_array, i32 iarray_num); /* *create a simple pool with many rings - *note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + *note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_sp_ring_create (nsfw_mem_mring * prpoolinfo, - mring_handle * pringhandle_array, i32 iringnum); +i32 nsfw_mem_sp_ring_create(nsfw_mem_mring * prpoolinfo, + mring_handle * pringhandle_array, i32 iringnum); /* *release a simple mempool - *note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + *note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_sp_release (nsfw_mem_name * pname); +i32 nsfw_mem_sp_release(nsfw_mem_name * pname); /* *look up a simpile ring - * note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. * 2. if the memory is shared, pname->enowner indicate that who create this memory, * note: - * 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, + * 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, * end with none created by nStackMaster, and end with _<pid> created by other. * 2. pname->enowner is available only when call look up shared memory. * 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, * the name must be full name. - * for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, + * for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, * must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add * _(pid) at the end of name, nstack_123. */ -mring_handle nsfw_mem_sp_lookup (nsfw_mem_name * pname); +mring_handle nsfw_mem_sp_lookup(nsfw_mem_name * pname); /* *create a ring - *note: 1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. - * 2. shared memory ring (NSFW_SHMEM) just can put a pointer into the queue, the queue also point to a shared block memory. + *note: 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. + * 2. shared memory ring (NSFW_SHMEM) just can put a pointor into the queue, the queue also point to a shared block memory. * no shared memory ring(NSFW_NSHMEM) is other wise. */ -mring_handle nsfw_mem_ring_create (nsfw_mem_mring * pringinfo); +mring_handle nsfw_mem_ring_create(nsfw_mem_mring * pringinfo); /* *look up a ring by name - * note:1. the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + * note:1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. * 2. if the memory is shared, pname->enowner indicate that who create this memory, * note: - * 1. when calling any shared memory create inferface, the name of memory end with _0 created by nStackMain, + * 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, * end with none created by nStackMaster, and end with _<pid> created by other. * 2. pname->enowner is available only when call look up shared memory. * 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, * the name must be full name. - * for examles if the memory was created by nStackMain and pname->enowner is NSFW_PROC_NULL, + * for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, * must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add * _(pid) at the end of name, nstack_123. */ -mring_handle nsfw_mem_ring_lookup (nsfw_mem_name * pname); +mring_handle nsfw_mem_ring_lookup(nsfw_mem_name * pname); /* * reset the number of producer and consumer, also, the state of ring reset to empty * notes: must be called before doing any operations base on the ring */ -void nsfw_mem_ring_reset (mring_handle mhandle, nsfw_mpool_type entype); +void nsfw_mem_ring_reset(mring_handle mhandle, nsfw_mpool_type entype); extern nsfw_ring_ops g_ring_ops_arry[NSFW_MEM_TYPEMAX][NSFW_MPOOL_TYPEMAX]; /***************************************************************************** * Prototype : nsfw_mem_ring_dequeue * Description : get a member from a ring -* note : if NSFW_SHMEM ring, pdata returned already a local address +* note : if NSFW_SHMEM ring, pdata returned alread a local address * Input : mring_handle mhandle * void** pdata * Output : None * Return Value : the num of elment get from the queue, =0: get null, <0: err happen, >0: return num. * Calls : * Called By : -* *****************************************************************************/ -static inline i32 -nsfw_mem_ring_dequeue (mring_handle mhandle, void **pdata) +static inline i32 nsfw_mem_ring_dequeue(mring_handle mhandle, void **pdata) { - if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX - || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) + if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX + || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return -1; + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return -1; } - return - g_ring_ops_arry[*((u8 *) mhandle)][*((u8 *) mhandle + 1)].ring_ops_dequeue - (mhandle, pdata); + return + g_ring_ops_arry[*((u8 *) mhandle)][* + ((u8 *) mhandle + + 1)].ring_ops_dequeue(mhandle, + pdata); } /***************************************************************************** * Prototype : nsfw_mem_ring_dequeuev * Description : get some members from a ring -* note : if NSFW_SHMEM ring, pdata returned already a local address +* note : if NSFW_SHMEM ring, pdata returned alread a local address * Input : mring_handle mhandle * void** pdata * unsigned inum @@ -437,23 +465,23 @@ nsfw_mem_ring_dequeue (mring_handle mhandle, void **pdata) * Return Value : the num of elment get from the queue, =0: get null, <0: err happen, >0: return num. * Calls : * Called By : -* *****************************************************************************/ -static inline i32 -nsfw_mem_ring_dequeuev (mring_handle mhandle, void **pdata, unsigned int inum) +static inline i32 nsfw_mem_ring_dequeuev(mring_handle mhandle, void **pdata, + unsigned int inum) { - if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX - || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) + if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX + || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return -1; + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return -1; } - return - g_ring_ops_arry[*((u8 *) mhandle)][* - ((u8 *) mhandle + - 1)].ring_ops_dequeuev (mhandle, pdata, - inum); + return + g_ring_ops_arry[*((u8 *) mhandle)][* + ((u8 *) mhandle + + 1)].ring_ops_dequeuev(mhandle, + pdata, + inum); } /***************************************************************************** @@ -467,80 +495,118 @@ nsfw_mem_ring_dequeuev (mring_handle mhandle, void **pdata, unsigned int inum) * Return Value : the num of elment put into the queue, =0: put null, <0: err happen, >0: return num. * Calls : * Called By : -* *****************************************************************************/ -static inline i32 -nsfw_mem_ring_enqueue (mring_handle mhandle, void *pdata) +static inline i32 nsfw_mem_ring_enqueue(mring_handle mhandle, void *pdata) { - if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX - || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) + if (NULL == mhandle || *((u8 *) mhandle) >= NSFW_MEM_TYPEMAX + || *((u8 *) mhandle + 1) >= NSFW_MPOOL_TYPEMAX) { - NSCOMM_LOGERR ("input para error] mhandle=%p", mhandle); - return -1; + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return -1; } - return - g_ring_ops_arry[*((u8 *) mhandle)][*((u8 *) mhandle + 1)].ring_ops_enqueue - (mhandle, pdata); + return + g_ring_ops_arry[*((u8 *) mhandle)][* + ((u8 *) mhandle + + 1)].ring_ops_enqueue(mhandle, + pdata); } /* *get the free number of ring */ -u32 nsfw_mem_ring_free_count (mring_handle mhandle); +u32 nsfw_mem_ring_free_count(mring_handle mhandle); /* *get the in using number of ring */ -u32 nsfw_mem_ring_using_count (mring_handle mhandle); +u32 nsfw_mem_ring_using_count(mring_handle mhandle); /* *get size of ring */ -u32 nsfw_mem_ring_size (mring_handle mhandle); +u32 nsfw_mem_ring_size(mring_handle mhandle); /* *release a ring memory - *note: the length of name must be less than NSFW_MEM_APPNAME_LENGTH. + *note: the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. */ -i32 nsfw_mem_ring_release (nsfw_mem_name * pname); +i32 nsfw_mem_ring_release(nsfw_mem_name * pname); /* *statics mbufpool, sppool, ring mem size *return: <=0, err happen, >0 mem size - * NSFW_MEM_MZONE: not surport because you already know the length when create - */ -ssize_t nsfw_mem_get_len (void *handle, nsfw_mem_struct_type type); - -/* - *recycle mbuf - * + * NSFW_MEM_MZONE: not surport because you already know the lenth when create */ -i32 nsfw_mem_mbuf_pool_recycle (mpool_handle handle); +ssize_t nsfw_mem_get_len(void *handle, nsfw_mem_struct_type type); typedef int (*nsfw_mem_item_fun) (void *data, void *argv); -i32 nsfw_mem_sp_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); -i32 nsfw_mem_mbuf_iterator (mpool_handle handle, u32 start, u32 end, - nsfw_mem_item_fun fun, void *argv); +i32 nsfw_mem_sp_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv); +i32 nsfw_mem_mbuf_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv); +i32 nsfw_mem_ring_iterator(mpool_handle handle, nsfw_mem_item_fun fun, + void *argv); -/***************************************************************************** -* Prototype : nsfw_mem_dfx_ring_print -* Description : print ring info -* Input : mring_handle mhandle -* char *pbuf -* int length -* Output : None -* Return Value : i32 -* Calls : -* Called By : -* -*****************************************************************************/ -i32 nsfw_mem_dfx_ring_print (mring_handle mhandle, char *pbuf, int length); +nsfw_mem_ring_health_info nsfw_mem_get_health_info(mring_handle mhandle); -#ifdef SYS_MEM_RES_STAT -u32 nsfw_mem_mbfpool_free_count (mpool_handle mhandle); -#endif +typedef struct +{ + fw_poc_type enflag; /*app, daemon-stack, Master */ +} nsfw_mem_localdata; + +/*memory access inferface define*/ +typedef struct +{ + i32(*mem_ops_init) (nsfw_mem_para * para); + void (*mem_ops_destroy) (void); + mzone_handle(*mem_ops_zone_creae) (nsfw_mem_zone * pinfo); + i32(*mem_ops_zone_createv) (nsfw_mem_zone * pmeminfo, i32 inum, + mzone_handle * paddr_array, i32 iarray_num); + mzone_handle(*mem_ops_zone_lookup) (nsfw_mem_name * pname); + i32(*mem_ops_mzone_release) (nsfw_mem_name * pname); + mpool_handle(*mem_ops_mbfmp_create) (nsfw_mem_mbfpool * pbufinfo); + i32(*mem_ops_mbfmp_createv) (nsfw_mem_mbfpool * pmbfname, i32 inum, + mpool_handle * phandle_array, + i32 iarray_num); + mpool_handle(*mem_ops_mbfmp_lookup) (nsfw_mem_name * pmbfname); + i32(*mem_ops_mbfmp_release) (nsfw_mem_name * pname); + mring_handle(*mem_ops_sp_create) (nsfw_mem_sppool * pmpinfo); + i32(*mem_ops_sp_createv) (nsfw_mem_sppool * pmpinfo, i32 inum, + mring_handle * pringhandle_array, + i32 iarray_num); + i32(*mem_ops_spring_create) (nsfw_mem_mring * prpoolinfo, + mring_handle * pringhandle_array, + i32 iringnum); + i32(*mem_ops_sp_release) (nsfw_mem_name * pname); + mring_handle(*mem_ops_sp_lookup) (nsfw_mem_name * pname); + mring_handle(*mem_ops_ring_create) (nsfw_mem_mring * pringinfo); + mring_handle(*mem_ops_ring_lookup) (nsfw_mem_name * pname); + i32(*mem_ops_ring_release) (nsfw_mem_name * pname); + ssize_t(*mem_ops_mem_statics) (void *handle, nsfw_mem_struct_type type); + i32(*mem_ops_sp_iterator) (mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv); + i32(*mem_ops_mbuf_iterator) (mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv); + i32(*mem_ops_ring_iterator) (mpool_handle handle, + nsfw_mem_item_fun fun, void *argv); + void *(*mem_ops_shddr_to_laddr) (void *addr); + uint64_t(*mem_ops_laddr_to_shddr) (void *addr); + int (*mem_ops_attach_core_id) (nsfw_mem_name * name); +} nsfw_mem_ops; + + /**/ typedef struct +{ + nsfw_mem_type entype; + nsfw_mem_ops *stmemop; +} nsfw_mem_attr; + +extern nsfw_mem_attr g_nsfw_mem_ops[]; +extern i32 g_mem_type_num; +#define SHMEM_ADDR_SHTOL(addr) (g_nsfw_mem_ops[NSFW_SHMEM].stmemop->mem_ops_shddr_to_laddr(addr)) +#define SHMEM_ADDR_LTOSH(addr) (g_nsfw_mem_ops[NSFW_SHMEM].stmemop->mem_ops_laddr_to_shddr(addr)) +#define SHMEM_PTR_SHTOL(type, addr) ((type)SHMEM_ADDR_SHTOL(addr)) +#define SHMEM_ADDR_LTOSH_EXT(addr) (SHMEM_ADDR_LTOSH(addr)) #endif diff --git a/src/framework/include/nsfw_mgr_com_api.h b/src/framework/include/nsfw_mgr_com_api.h index 9bbcaca..52d34bf 100644 --- a/src/framework/include/nsfw_mgr_com_api.h +++ b/src/framework/include/nsfw_mgr_com_api.h @@ -20,6 +20,8 @@ #ifndef _NSFW_MGRCOM_API_H #define _NSFW_MGRCOM_API_H +#include "types.h" + #ifdef __cplusplus /* *INDENT-OFF* */ extern "C"{ @@ -32,96 +34,102 @@ extern "C"{ typedef enum _mgr_msg_type { - MGR_MSG_NULL = 0, - /*#############common msg type################# */ - MGR_MSG_CHK_INIT_REQ = 1, - MGR_MSG_INIT_NTY_REQ, - MGR_MSG_CHK_HBT_REQ, - MGR_MSG_APP_EXIT_REQ, - MGR_MSG_SRV_CTL_REQ, - MGR_MSG_VER_MGR_REQ, - MGR_MSG_SOF_PAR_REQ, - - /*############################################# */ - MGR_MSG_MEM_ALLOC_REQ = 64, /* memory msg type */ - - /*############################################# */ - MGR_MSG_DFX_QRY_REQ = 96, /* nStackCtrl maintain msg */ - MGR_MSG_SET_LOG_REQ, - - /*############################################# */ - MGR_MSG_RCC_END_REQ = 128, /* service msg type */ - - /*############################################# */ - MGR_MSG_TOOL_TCPDUMP_REQ = 256, /* for tools */ - MGR_MSG_TOOL_HEART_BEAT, - - /*###query message with large rsp message begin## */ - MGR_MSG_LARGE_QRY_REQ_BEGIN = 384, - MGR_MSG_LARGE_STA_QRY_REQ = MGR_MSG_LARGE_QRY_REQ_BEGIN, - MGR_MSG_LARGE_MT_QRY_REQ, /* nStackCtrl maintain msg */ - - /*############################################# */ - MGR_MSG_LARGE_ALARM_REQ = 500, /* alarm msg type */ - - MGR_MSG_RSP_BASE = 512, - /*#############common msg type################# */ - MGR_MSG_CHK_INIT_RSP = MRG_RSP (MGR_MSG_CHK_INIT_REQ), - MGR_MSG_INIT_NTY_RSP = MRG_RSP (MGR_MSG_INIT_NTY_REQ), - MGR_MSG_CHK_HBT_RSP = MRG_RSP (MGR_MSG_CHK_HBT_REQ), - MGR_MSG_APP_EXIT_RSP = MRG_RSP (MGR_MSG_APP_EXIT_REQ), - MGR_MSG_SRV_CTL_RSP = MRG_RSP (MGR_MSG_SRV_CTL_REQ), - MGR_MSG_VER_MGR_RSP = MRG_RSP (MGR_MSG_VER_MGR_REQ), - MGR_MSG_SOF_PAR_RSP = MRG_RSP (MGR_MSG_SOF_PAR_REQ), - /*############################################# */ - - MGR_MSG_MEM_ALLOC_RSP = MRG_RSP (MGR_MSG_MEM_ALLOC_REQ), - - MGR_MSG_DFX_QRY_RSP = MRG_RSP (MGR_MSG_DFX_QRY_REQ), - - MGR_MSG_SET_LOG_RSP = MRG_RSP (MGR_MSG_SET_LOG_REQ), - - MGR_MSG_RCC_END_RSP = MRG_RSP (MGR_MSG_RCC_END_REQ), - - /*############################################# */ - MGR_MSG_TOOL_TCPDUMP_RSP = MRG_RSP (MGR_MSG_TOOL_TCPDUMP_REQ), - MGR_MSG_TOOL_HEART_BEAT_RSP = MRG_RSP (MGR_MSG_TOOL_HEART_BEAT), - - /*##############LARGE RSP MESSAGE################## */ - MGR_MSG_LAG_QRY_RSP_BEGIN = MRG_RSP (MGR_MSG_LARGE_QRY_REQ_BEGIN), - MGR_MSG_LAG_STA_QRY_RSP = MRG_RSP (MGR_MSG_LARGE_STA_QRY_REQ), - MGR_MSG_LAG_MT_QRY_RSP = MRG_RSP (MGR_MSG_LARGE_MT_QRY_REQ), - MGR_MSG_LARGE_ALARM_RSP = MRG_RSP (MGR_MSG_LARGE_ALARM_REQ), - MGR_MSG_MAX = 1024 + MGR_MSG_NULL = 0, + /*#############common msg type################# */ + MGR_MSG_CHK_INIT_REQ = 1, + MGR_MSG_INIT_NTY_REQ, + MGR_MSG_CHK_HBT_REQ, + MGR_MSG_APP_EXIT_REQ, + MGR_MSG_SRV_CTL_REQ, + MGR_MSG_VER_MGR_REQ, + MGR_MSG_SOF_PAR_REQ, + MGR_MSG_HOTFIX_REQ, + + /*############################################# */ + MGR_MSG_MEM_ALLOC_REQ = 64, /* memory msg type */ + + /*############################################# */ + MGR_MSG_DFX_QRY_REQ = 96, /* nStackCtrl maitain msg */ + MGR_MSG_SET_LOG_REQ, + + /*############################################# */ + MGR_MSG_RCC_END_REQ = 128, /* service msg type */ + + /*############################################# */ + MGR_MSG_TOOL_TCPDUMP_REQ = 256, /* for tools */ + MGR_MSG_TOOL_HEART_BEAT, + + /*###query message with large rsp message begin## */ + MGR_MSG_LARGE_QRY_REQ_BEGIN = 384, + MGR_MSG_LARGE_STA_QRY_REQ = MGR_MSG_LARGE_QRY_REQ_BEGIN, + MGR_MSG_LARGE_MT_QRY_REQ, /* nStackCtrl maitain msg */ + MGR_MSG_SPLNET_REQ, + + /*############################################# */ + MGR_MSG_LARGE_ALARM_REQ = 500, /* alarm msg type */ + MGR_MSG_LARGE_MT_NETSTAT, /* netstat tool */ + + MGR_MSG_RSP_BASE = 512, + /*#############common msg type################# */ + MGR_MSG_CHK_INIT_RSP = MRG_RSP(MGR_MSG_CHK_INIT_REQ), + MGR_MSG_INIT_NTY_RSP = MRG_RSP(MGR_MSG_INIT_NTY_REQ), + MGR_MSG_CHK_HBT_RSP = MRG_RSP(MGR_MSG_CHK_HBT_REQ), + MGR_MSG_APP_EXIT_RSP = MRG_RSP(MGR_MSG_APP_EXIT_REQ), + MGR_MSG_SRV_CTL_RSP = MRG_RSP(MGR_MSG_SRV_CTL_REQ), + MGR_MSG_VER_MGR_RSP = MRG_RSP(MGR_MSG_VER_MGR_REQ), + MGR_MSG_SOF_PAR_RSP = MRG_RSP(MGR_MSG_SOF_PAR_REQ), + MGR_MSG_HOTFIX_RSP = MRG_RSP(MGR_MSG_HOTFIX_REQ), + /*############################################# */ + + MGR_MSG_MEM_ALLOC_RSP = MRG_RSP(MGR_MSG_MEM_ALLOC_REQ), + + MGR_MSG_DFX_QRY_RSP = MRG_RSP(MGR_MSG_DFX_QRY_REQ), + + MGR_MSG_SET_LOG_RSP = MRG_RSP(MGR_MSG_SET_LOG_REQ), + + MGR_MSG_RCC_END_RSP = MRG_RSP(MGR_MSG_RCC_END_REQ), + + /*############################################# */ + MGR_MSG_TOOL_TCPDUMP_RSP = MRG_RSP(MGR_MSG_TOOL_TCPDUMP_REQ), + MGR_MSG_TOOL_HEART_BEAT_RSP = MRG_RSP(MGR_MSG_TOOL_HEART_BEAT), + + /*##############LARGE RSP MESSAGE################## */ + MGR_MSG_LAG_QRY_RSP_BEGIN = MRG_RSP(MGR_MSG_LARGE_QRY_REQ_BEGIN), + MGR_MSG_LAG_STA_QRY_RSP = MRG_RSP(MGR_MSG_LARGE_STA_QRY_REQ), + MGR_MSG_LAG_MT_QRY_RSP = MRG_RSP(MGR_MSG_LARGE_MT_QRY_REQ), + MGR_MSG_SPLNET_RSP = MRG_RSP(MGR_MSG_SPLNET_REQ), + MGR_MSG_LARGE_ALARM_RSP = MRG_RSP(MGR_MSG_LARGE_ALARM_REQ), + MGR_MSG_LARGE_MT_NETSTAT_RSP = MRG_RSP(MGR_MSG_LARGE_MT_NETSTAT), + MGR_MSG_MAX = 1024 } mgr_msg_type; typedef enum _fw_poc_type { - NSFW_PROC_NULL = 0, - NSFW_PROC_MAIN, - NSFW_PROC_MASTER, - NSFW_PROC_APP, - NSFW_PROC_CTRL, - NSFW_PROC_TOOLS, - NSFW_PROC_ALARM, - NSFW_PROC_MAX = 16 + NSFW_PROC_NULL = 0, + NSFW_PROC_MAIN, + NSFW_PROC_MASTER, + NSFW_PROC_APP, + NSFW_PROC_CTRL, + NSFW_PROC_TOOLS, + NSFW_PROC_ALARM, + NSFW_PROC_MAX = 16 } fw_poc_type; -#define NSFW_DOMAIN_DIR "/var/log/nStack/ip_module/" +#define NSFW_DOMAIN_DIR "/var/run" #define NSTACK_MAX_PROC_NAME_LEN 20 typedef enum _nsfw_mgr_msg_rsp_code { - NSFW_MGR_SUCCESS, - NSFW_MGR_MSG_TYPE_ERROR, + NSFW_MGR_SUCESS, + NSFW_MGR_MSG_TYPE_ERROR, } mgr_msg_rsp_code; -extern char *nsfw_get_proc_name (u8 proc_type); +extern char *nsfw_get_proc_name(u8 proc_type); #define GET_USER_MSG(_stu, _msg) ((_stu *)(&(_msg)->msg_body[0])) /*for log print*/ -#define MSGINFO "msg=%p,len=%d,t=%d,sq=%d,st=%d,sp=%d,dt=%d,dp=%d" +#define MSGINFO "msg=%p,len=%u,t=%u,sq=%d,st=%u,sp=%u,dt=%u,dp=%u" #define PRTMSG(msg) (msg), (msg)->msg_len,(msg)->msg_type,(msg)->seq, (msg)->src_proc_type,(msg)->src_pid,(msg)->dst_proc_type,(msg)->dst_pid #define NSFW_MGR_MSG_LEN 512 @@ -131,62 +139,66 @@ extern char *nsfw_get_proc_name (u8 proc_type); #define NSFW_MGR_LARGE_MSG_LEN (256*1024) #define NSFW_MGR_LARGE_MSG_BODY_LEN (NSFW_MGR_LARGE_MSG_LEN - NSFW_MGR_MSG_HDR_LEN) +/* When copy data to msg->body[], use this MACRO instead of using NSFW_MGR_MSG_BODY_LEN/NSFW_MGR_LARGE_MSG_BODY_LEN directly. + * Because msg's body length is various, use this MACRO will help you select the real body len*/ +#define MSG_BODY_LEN(msg) (msg->msg_len - NSFW_MGR_MSG_HDR_LEN) + typedef struct _nsfw_mgr_msg { - u16 msg_type; /* mgr_msg_type */ - u16 u16Reserve; - u32 msg_len; - - u8 alloc_flag:1; - u8 fw_flag:1; - u8 from_mem:1; - u8 more_msg_flag:1; - u8 reserve_flag:4; - u8 resp_code; - u8 src_proc_type; /* fw_poc_type */ - u8 dst_proc_type; - i32 seq; - - u32 src_pid; - u32 dst_pid; - - u8 msg_body[NSFW_MGR_MSG_BODY_LEN]; + u16 msg_type; /* mgr_msg_type */ + u16 u16Reserve; + u32 msg_len; + + u8 alloc_flag:1; + u8 fw_flag:1; + u8 from_mem:1; + u8 more_msg_flag:1; + u8 reserve_flag:4; + u8 resp_code; + u8 src_proc_type; /* fw_poc_type */ + u8 dst_proc_type; + i32 seq; + u32 src_pid; + u32 dst_pid; + u64 padding; + u8 msg_body[NSFW_MGR_MSG_BODY_LEN]; } nsfw_mgr_msg; -extern nsfw_mgr_msg *nsfw_mgr_msg_alloc (u16 msg_type, u8 dst_proc_type); -extern void nsfw_mgr_msg_free (nsfw_mgr_msg * msg); +extern nsfw_mgr_msg *nsfw_mgr_msg_alloc(u16 msg_type, u8 dst_proc_type); +extern void nsfw_mgr_msg_free(nsfw_mgr_msg * msg); + +extern const char *get_home_path(); /* for rsp msg alloc*/ -extern nsfw_mgr_msg *nsfw_mgr_null_rspmsg_alloc (); -extern nsfw_mgr_msg *nsfw_mgr_rsp_msg_alloc (nsfw_mgr_msg * req_msg); +extern nsfw_mgr_msg *nsfw_mgr_null_rspmsg_alloc(); +extern nsfw_mgr_msg *nsfw_mgr_rsp_msg_alloc(nsfw_mgr_msg * req_msg); /* for msg proc fun reg*/ typedef int (*nsfw_mgr_msg_fun) (nsfw_mgr_msg * msg); -extern u8 nsfw_mgr_reg_msg_fun (u16 msg_type, nsfw_mgr_msg_fun fun); +extern u8 nsfw_mgr_reg_msg_fun(u16 msg_type, nsfw_mgr_msg_fun fun); -extern u8 nsfw_mgr_send_msg (nsfw_mgr_msg * msg); -extern u8 nsfw_mgr_send_req_wait_rsp (nsfw_mgr_msg * req_msg, - nsfw_mgr_msg * rsp_msg); +extern u8 nsfw_mgr_send_msg(nsfw_mgr_msg * msg); +extern u8 nsfw_mgr_send_req_wait_rsp(nsfw_mgr_msg * req_msg, + nsfw_mgr_msg * rsp_msg); /* for fork clear parent resource*/ -extern void nsfw_mgr_close_dst_proc (u8 proc_type, u32 dst_pid); -extern u8 nsfw_mgr_clr_fd_lock (); +extern void nsfw_mgr_close_dst_proc(u8 proc_type, u32 dst_pid); +extern u8 nsfw_mgr_clr_fd_lock(); /* for epoll thread reg other sock proc fun*/ typedef int (*nsfw_mgr_sock_fun) (i32 epfd, i32 socket, u32 events); -extern u8 nsfw_mgr_reg_sock_fun (i32 socket, nsfw_mgr_sock_fun fun); -extern void nsfw_mgr_unreg_sock_fun (i32 socket); -extern int nsfw_mgr_com_socket_error (i32 fd, nsfw_mgr_sock_fun fun, - i32 timer); -extern u8 nsfw_mgr_ep_start (); -extern int nsfw_mgr_com_module_init (void *param); -extern int nsfw_mgr_run_script (const char *cmd, char *result, - int result_buf_len); - -extern int nsfw_mgr_com_chk_hbt (int v_add); -extern i32 nsfw_set_close_on_exec (i32 sock); -extern int nsfw_mgr_comm_fd_init (u32 proc_type); -extern void nsfw_mgr_com_mkdir_domainpath (char *pathname); +extern u8 nsfw_mgr_reg_sock_fun(i32 socket, nsfw_mgr_sock_fun fun); +extern void nsfw_mgr_unreg_sock_fun(i32 socket); +extern int nsfw_mgr_com_socket_error(i32 fd, nsfw_mgr_sock_fun fun, + i32 timer); +extern int nsfw_mgr_com_module_init(void *param); +extern int nsfw_mgr_run_script(const char *cmd, char *result, + int result_buf_len); + +extern int nsfw_mgr_com_chk_hbt(int v_add); +/* close on exec */ +extern i32 nsfw_set_close_on_exec(i32 sock); +extern int nsfw_mgr_comm_fd_init(u32 proc_type); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/nsfw_ps_api.h b/src/framework/include/nsfw_ps_api.h index 69fa992..36a64ee 100644 --- a/src/framework/include/nsfw_ps_api.h +++ b/src/framework/include/nsfw_ps_api.h @@ -18,6 +18,7 @@ #define _NSFW_PS_API_H #include "list.h" +#include "compiling_check.h" #ifdef __cplusplus /* *INDENT-OFF* */ extern "C"{ @@ -29,101 +30,109 @@ extern "C"{ #define NSFW_PS_MAX_CALLBACK 16 #define NSFW_MAX_HBT_CHK_COUNT_DEF 60 +#define NSFW_MAX_PID 65535 +COMPAT_PROTECT_RETURN(NSFW_MAX_PID, 65535); typedef enum _nsfw_ps_state { - NSFW_PS_NULL = 0, - NSFW_PS_START, - NSFW_PS_RUNNING, - NSFW_PS_PARENT_FORK, - NSFW_PS_CHILD_FORK, - NSFW_PS_HBT_FAILED, - NSFW_PS_EXITING, - NSFW_PS_EXIT, - NSFW_PS_MAX + NSFW_PS_NULL = 0, + NSFW_PS_START, + NSFW_PS_RUNNING, + NSFW_PS_PARENT_FORK, + NSFW_PS_CHILD_FORK, + NSFW_PS_HBT_FAILED, + NSFW_PS_EXITING, + NSFW_PS_EXIT, + NSFW_PS_MAX } nsfw_ps_state; /* for state change call back proc*/ typedef int (*nsfw_ps_proc_fun) (void *pps_info, void *argv); typedef struct _nsfw_ps_callback { - u8 state; - nsfw_ps_proc_fun fun; - void *argv; + u8 state; + nsfw_ps_proc_fun fun; + void *argv; } nsfw_ps_callback; /* for value in ps_info get/set*/ typedef enum _nsfw_ps_user_value { - NSFW_REC_IDX = 1, - NSFW_REC_TIMER = 2, - NSFW_PS_UV_MAX = 16 + NSFW_REC_IDX = 1, + NSFW_REC_TIMER = 2, + NSFW_PS_UV_MAX = 16 } nsfw_ps_user_value; #define nsfw_ps_set_uv(_pps_info, _type, _value) (_pps_info)->value[(_type)] = (_value) #define nsfw_ps_get_uv(_pps_info, _type) ((_pps_info)->value[(_type)]) typedef struct _nsfw_ps_info { - struct list_head node; - u8 alloc_flag; - u8 state; /*nsfw_ps_state */ - u8 proc_type; /*fw_poc_type */ - u8 rechk_flg; - u32 host_pid; - u32 parent_pid; /* only use for fork */ - u32 cur_child_pid; /* only use for fork */ - void *exit_timer_ptr; - void *resend_timer_ptr; - void *hbt_timer_ptr; - u32 hbt_failed_count; - nsfw_ps_callback callback[NSFW_PS_MAX_CALLBACK]; - void *value[NSFW_PS_UV_MAX]; + struct list_head node; + u8 alloc_flag; + u8 state; /*nsfw_ps_state */ + u8 proc_type; /*fw_poc_type */ + u8 rechk_flg; + u32 host_pid; + u32 parent_pid; /* only use for fork */ + u32 cur_child_pid; /* only use for fork */ + void *exit_timer_ptr; + void *resend_timer_ptr; + void *hbt_timer_ptr; + u32 hbt_failed_count; + nsfw_ps_callback callback[NSFW_PS_MAX_CALLBACK]; + void *value[NSFW_PS_UV_MAX]; } nsfw_ps_info; typedef struct _nsfw_thread_dogs { - u8 alloc_flag; - i32 count; - u32 thread_id; + u8 alloc_flag; + i32 count; + u32 thread_id; } nsfw_thread_dogs; -extern nsfw_ps_info *nsfw_ps_info_alloc (u32 pid, u8 proc_type); -extern nsfw_ps_info *nsfw_ps_info_get (u32 pid); -extern void nsfw_ps_info_free (nsfw_ps_info * ps_info); +extern nsfw_ps_info *nsfw_ps_info_alloc(u32 pid, u8 proc_type, + u8 realloc_flg); +extern nsfw_ps_info *nsfw_ps_info_get(u32 pid); +extern void nsfw_ps_info_free(nsfw_ps_info * ps_info); -extern u8 nsfw_ps_reg_fun (nsfw_ps_info * pps_info, u8 ps_state, - nsfw_ps_proc_fun fun, void *argv); +extern u8 nsfw_ps_reg_fun(nsfw_ps_info * pps_info, u8 ps_state, + nsfw_ps_proc_fun fun, void *argv); /* will auto reg after ps_info alloc*/ -extern u8 nsfw_ps_reg_global_fun (u8 proc_type, u8 ps_state, - nsfw_ps_proc_fun fun, void *argv); +extern u8 nsfw_ps_reg_global_fun(u8 proc_type, u8 ps_state, + nsfw_ps_proc_fun fun, void *argv); typedef struct _nsfw_ps_info_msg { - u32 host_pid; - u32 parent_pid; - u64 reserve; + u32 host_pid; + u32 parent_pid; + u64 reserve; } nsfw_ps_info_msg; -extern u8 nsfw_ps_exit_end_notify (u32 pid); +extern u8 nsfw_ps_exit_end_notify(u32 pid); /*for heartbeat check*/ -extern u8 nsfw_ps_check_dst_init (u8 dst_proc_type); -extern u8 nsfw_thread_chk (); -extern nsfw_thread_dogs *nsfw_thread_getDog (); -extern u8 nsfw_thread_chk_unreg (); -extern u8 nsfw_ps_hbt_start (nsfw_ps_info * ps_info); -extern u8 nsfw_ps_hbt_stop (nsfw_ps_info * ps_info); +extern u8 nsfw_ps_check_dst_init(u8 dst_proc_type); +extern u8 nsfw_thread_chk(); +extern nsfw_thread_dogs *nsfw_thread_get_dog(); +extern u8 nsfw_thread_chk_unreg(); +extern u8 nsfw_ps_hbt_start(nsfw_ps_info * ps_info); +extern u8 nsfw_ps_hbt_stop(nsfw_ps_info * ps_info); -extern u32 nsfw_ps_iterator (nsfw_ps_proc_fun fun, void *argv); +extern u32 nsfw_ps_iterator(nsfw_ps_proc_fun fun, void *argv); +/* print bt */ #define MAX_THREAD 16 extern pthread_t g_all_thread[]; -extern u8 nsfw_reg_trace_thread (pthread_t tid); +extern u8 nsfw_reg_trace_thread(pthread_t tid); typedef int (*nsfw_ps_pid_fun) (u32 pid, u8 proc_type, void *argv); -extern int nsfw_ps_rechk_pid_exit (nsfw_ps_pid_fun fun, void *argv); -extern nsfw_ps_info *nsfw_share_ps_info_get (u32 pid); -extern void nsfw_ps_cfg_set_chk_count (u16 count); +extern int nsfw_ps_rechk_pid_exit(nsfw_ps_pid_fun fun, void *argv); +extern nsfw_ps_info *nsfw_share_ps_info_get(u32 pid); +extern void nsfw_ps_cfg_set_chk_count(u16 count); + +extern int nsfw_ps_check_pid_nstack_status(int pid); +extern u64 nsfw_ps_get_starttime_from_file(u32 pid); +extern u64 nsfw_ps_get_starttime_from_info(u32 pid); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/nsfw_recycle_api.h b/src/framework/include/nsfw_recycle_api.h index 9d7f3bb..35ba388 100644 --- a/src/framework/include/nsfw_recycle_api.h +++ b/src/framework/include/nsfw_recycle_api.h @@ -17,6 +17,8 @@ #ifndef _NSFW_RECYCLE_API_H #define _NSFW_RECYCLE_API_H +#include "types.h" + #ifdef __cplusplus /* *INDENT-OFF* */ extern "C"{ @@ -27,40 +29,40 @@ extern "C"{ typedef enum _nsfw_recycle_item_type { - NSFW_REC_TYPE_NULL = 0, - NSFW_REC_SBR_START = 1, - NSFW_REC_SBR_SOCKET, - NSFW_REC_SBR_END = NSFW_REC_SBR_START + 63, - NSFW_REC_NSOCKET_START, - NSFW_REC_NSOCKET_EPOLL, - NSFW_REC_NSOCKET_END = NSFW_REC_NSOCKET_START + 63, - NSFW_REC_TYPE_MAX = 512 + NSFW_REC_TYPE_NULL = 0, + NSFW_REC_SBR_START = 1, + NSFW_REC_SBR_SOCKET, + NSFW_REC_SBR_END = NSFW_REC_SBR_START + 63, + NSFW_REC_NSOCKET_START, + NSFW_REC_NSOCKET_EPOLL, + NSFW_REC_NSOCKET_END = NSFW_REC_NSOCKET_START + 63, + NSFW_REC_TYPE_MAX = 512 } nsfw_recycle_item_type; typedef enum _nsfw_recycle_priority { - NSFW_REC_PRO_HIGHTEST = 0, - NSFW_REC_PRO_NORMAL = 1, - NSFW_REC_PRO_DEFAULT = 2, - NSFW_REC_PRO_LOWEST = 3, - NSFW_REC_PRO_MAX = 4 + NSFW_REC_PRO_HIGHTEST = 0, + NSFW_REC_PRO_NORMAL = 1, + NSFW_REC_PRO_DEFALUT = 2, + NSFW_REC_PRO_LOWEST = 3, + NSFW_REC_PRO_MAX = 4 } nsfw_recycle_priority; typedef enum _nsfw_rcc_stat { - NSFW_RCC_CONTINUE = 0, - NSFW_RCC_SUSPEND = 1, - NSFW_RCC_FAILED = 2, + NSFW_RCC_CONTINUE = 0, + NSFW_RCC_SUSPEND = 1, + NSFW_RCC_FAILED = 2, } nsfw_rcc_stat; -/*work on nStackMain*/ -typedef nsfw_rcc_stat (*nsfw_recycle_fun) (u32 exit_pid, void *pdata, - u16 rec_type); -extern u8 nsfw_recycle_reg_fun (u16 obj_type, nsfw_recycle_fun fun); -extern u8 nsfw_recycle_obj_end (u32 pid); -extern u8 nsfw_recycle_lock_rel_fun (nsfw_recycle_fun fun, void *data, - u8 proc_type); -extern int nsfw_recycle_exit_pid_lock (u32 pid, u8 proc_type, void *argv); +/*work on daemon-stack*/ +typedef nsfw_rcc_stat(*nsfw_recycle_fun) (u32 exit_pid, void *pdata, + u16 rec_type); +extern u8 nsfw_recycle_reg_fun(u16 obj_type, nsfw_recycle_fun fun); +extern u8 nsfw_recycle_obj_end(u32 pid); +extern u8 nsfw_recycle_lock_rel_fun(nsfw_recycle_fun fun, void *data, + u8 proc_type); +extern int nsfw_recycle_exit_pid_lock(u32 pid, u8 proc_type, void *argv); #define REGIST_RECYCLE_OBJ_FUN(_obj_type, _fun) \ NSTACK_STATIC void regist_ ## _obj_type ## _fun (void) \ @@ -79,9 +81,9 @@ extern int nsfw_recycle_exit_pid_lock (u32 pid, u8 proc_type, void *argv); } /*work on nStackApp*/ -extern void *nsfw_recycle_reg_obj (u8 priority, u16 rec_type, void *data); -extern u8 nsfw_recycle_fork_init (); -extern int nsfw_recycle_rechk_lock (); +extern void *nsfw_recycle_reg_obj(u8 priority, u16 rec_type, void *data); +extern u8 nsfw_recycle_fork_init(); +extern int nsfw_recycle_rechk_lock(); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/include/nsfw_ring_data.h b/src/framework/include/nsfw_ring_data.h new file mode 100644 index 0000000..cafffe0 --- /dev/null +++ b/src/framework/include/nsfw_ring_data.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 _NSFW_RING_DATA_H_ +#define _NSFW_RING_DATA_H_ + +#include <stdint.h> +#include "types.h" + +#define VALUE_LEN 40 + +/* +Ring Data has two part; Ver&Data +val is a pointer offset base on rtp_perf_ring::Addrbase, this struct support 1TB, it's enough now; +future __int128 maybe used, this type can perfectly solve the version & address rang problem. +*/ +union RingData_U +{ + struct RingData_S + { + /* + value of data, indeed it's a pointer offset base on rtp_perf_ring::Addrbase;40bit is enough for user space addr + ver must using 24bit, so val using 40bit; a CAS now just support 64bit; in future, we may using __int128,now __int128 not support well. + */ + volatile unsigned long long val:VALUE_LEN; + /* + version of data, using 16b store version flg is more suitable for Address save, but using 16b version is too short, it's value range is [0-65535]; + between two cpu schedule time (TM-SPACE) of one process/thread, other processes/threads do N times queue oper. if N > 65535, still have a chance of ABA. + if using a 24bit save version flg, if ABA happened, 16777216 times queue oper need done in one TM-SPACE, it's impossible for today cpu. + */ + volatile unsigned long long ver:(64 - VALUE_LEN); + } data_s; + u64 data_l; +}; + +/* + this high perf Ring rely on the init value of Ring Slot; + Ring Must init using PerfRingInit, Pool Must init using PerfPoolInit + + the addrbase is base addr for all element; now we support 1024G offset; + for nstack the Ring element is from hugepage, and the addr is in stack space. + + 1. not support a ring who's element space range bigger than 1024GB + [if one element from heep, one from stack, range will bigger than 1024GB, we not support] + 2. one more thing addr from mmap is in stack + 3. rtp_perf_ring must create by rtp_perf_ring_create/rtp_perf_pool_create +*/ +struct nsfw_mem_ring +{ + u8 memtype; //shared, no shared + u8 ringflag; //scmp, scsp, mcsp,mcmp + u16 overflow_count; //reserv data + u32 size; //size of the Ring, must 2^n + u32 eltsize; //for sppool, it is the size of per buf, if is ring, eltsize is zero. + u32 mask; //mask of the Ring, used mask mod Head/Tail to get real pos, must 2^n-1 + void *Addrbase; /*Cause the Addr we support just 40b(1024G), we using a basAddr+offset to get the real addr; ring[x].data_s.val just store offset; + * not used when no shared mode + */ + volatile u32_t prodhflag; //for nshmem fork recover + volatile u32_t prodtflag; //for nshmem fork recover + volatile u32_t conshflag; //for nshmem fork recover + volatile u32_t constflag; //for nshmem fork recover + nsfw_res res_chk; + + struct + { + volatile u32 head; //Head of the Ring, used to indicat pos where to pull a val + volatile u32 tail; //for nshmem, shmem not used. + } prod; + struct + { + volatile u32 head; //for nshmem, shmem not used. + volatile u32 tail; //Tail of the Ring, used to indicat pos where to push a val + } cons; + struct timeval overflow_time; + + union RingData_U ring[0]; //Value of Ring + +}; + +#define PERFRING_ADDR_RANGE (0xFFFFFFFFFFL) +#define PERFRING_HEAD_INCRASE_MASK (0x03) + +#define PERFRING_HEAD_INCRASE_VALUE (PERFRING_HEAD_INCRASE_MASK+1) + +#endif /*_NSFW_RING_DATA_H_*/ diff --git a/src/framework/include/nsfw_ring_fun.h b/src/framework/include/nsfw_ring_fun.h new file mode 100644 index 0000000..f93a59d --- /dev/null +++ b/src/framework/include/nsfw_ring_fun.h @@ -0,0 +1,114 @@ +/* +* +* 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 _NSFW_RING_FUN_H_ +#define _NSFW_RING_FUN_H_ + +#include <stdint.h> +#include "nsfw_mem_api.h" +#include "nsfw_ring_data.h" +#include "nsfw_branch_prediction.h" +#include "pid_common.h" + +/* + for nstack I advise addrbase set to lowest of mmaped hugepage Addr. + to simple: + 1. ring element is from mmaped mem, set Addrbase to 0x7fffffffffff - 0xffffffffff is OK; + 1. ring element is from heap, set Addrbase to NULL is ok; +*/ +static inline void nsfw_mem_ring_init(struct nsfw_mem_ring *ring, + unsigned int size, void *addrbase, + unsigned char memtype, + unsigned char flag) +{ + unsigned int loop = 0; + + if (!ring) + { + return; + } + + ring->prod.head = 0; + ring->prod.tail = 0; + ring->cons.head = 0; + ring->cons.tail = 0; + ring->size = size; + ring->eltsize = 0; + ring->mask = size - 1; + ring->memtype = memtype; + ring->ringflag = flag; + ring->prodtflag = ring->prodhflag = get_sys_pid(); + ring->conshflag = ring->constflag = get_sys_pid(); + /*if shmem, addrbase already changed to primary memory address */ + ring->Addrbase = addrbase; + + ring->overflow_count = 0; + ring->overflow_time.tv_sec = 0; + ring->overflow_time.tv_usec = 0; + + /*init Ring */ + for (loop = 0; loop < size; loop++) + { + /* + for a empty ring, version is the mapping head val - size + so the empty ring's ver is loop-size; + */ + ring->ring[loop].data_s.ver = (loop - size); + ring->ring[loop].data_s.val = 0; + } +} + +/* +another way to init Pool while no continuous space +1. init a empt rtp_perf_ring +2. add element to PerRing. +*/ +static inline void nsfw_mem_pool_head_init(struct nsfw_mem_ring *ring, + unsigned int size, + unsigned int eltsize, + void *addrbase, + nsfw_mem_type memtype, + nsfw_mpool_type flag) +{ + ring->prod.head = size; + ring->prod.tail = size; + ring->cons.head = 0; + ring->cons.tail = 0; + ring->size = size; + ring->eltsize = eltsize; + ring->mask = size - 1; + ring->memtype = memtype; + ring->ringflag = flag; + ring->prodtflag = ring->prodhflag = get_sys_pid(); + ring->conshflag = ring->constflag = get_sys_pid(); + /*if shmem, addrbase already changed to primary memory address */ + ring->Addrbase = addrbase; + ring->overflow_count = 0; + ring->overflow_time.tv_sec = 0; + ring->overflow_time.tv_usec = 0; + + return; +} + +#define NSFW_RING_FLAG_CHECK_RET(handle, desc) {\ + if (((struct nsfw_mem_ring*)mhandle)->ringflag >= NSFW_MPOOL_TYPEMAX) \ + { \ + NSRTP_LOGERR("invalid ring]desc=%s,ringflag=%d", desc, ((struct nsfw_mem_ring*)mhandle)->ringflag); \ + return 0; \ + } \ + } + +#endif /*_NSFW_RING_FUN_H_*/ diff --git a/src/framework/include/nsfw_snapshot.h b/src/framework/include/nsfw_snapshot_api.h index 5ce64aa..46df683 100644 --- a/src/framework/include/nsfw_snapshot.h +++ b/src/framework/include/nsfw_snapshot_api.h @@ -14,12 +14,11 @@ * limitations under the License. */ -#ifndef _FW_SNAPSHOT_H -#define _FW_SNAPSHOT_H +#ifndef _NSFW_SNAPSHOT_API_H +#define _NSFW_SNAPSHOT_API_H #include <stdlib.h> #include "types.h" -#include "../snapshot/fw_ss_tlv.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -51,76 +50,86 @@ extern "C"{ /* * This structure tells how to describe one object and its members */ -typedef struct _nsfw_ss_objMemDesc +typedef struct _nsfw_ss_obj_mem_desc { - u16 type; // object type(7 bits) | member type (7 bits) | is object(1 bit) | is array(1 bit) - u32 length; - u8 offset; -} nsfw_ss_objMemDesc_t; + u16 type; // object type(7 bits) | member type (7 bits) | is object(1 bit) | is array(1 bit) + u32 length; + u8 offset; +} nsfw_ss_obj_mem_desc_t; -typedef struct _nsfw_ss_objDesc +typedef struct _nsfw_ss_obj_desc { - u16 objType; /* Type number of object */ - u8 memNum; /* Nubmer of object members */ - u32 objSize; - nsfw_ss_objMemDesc_t *memDesc; /* Member descript */ -} nsfw_ss_objDesc_t; + u16 objType; /* Type number of object */ + u8 memNum; /* Nubmer of object members */ + u32 objSize; + nsfw_ss_obj_mem_desc_t *memDesc; /* Member descripe */ +} nsfw_ss_obj_desc_t; #define NSFW_SS_MAX_OBJDESC_NUM 256 /* Traversal, you can save the current value to start the search, do not need to start from the beginning of the search, because the value is generally a sequential */ -typedef struct _nsfw_ss_objDescManager +typedef struct _nsfw_ss_obj_desc_manager { - nsfw_ss_objDesc_t *g_nsfw_ss_objDescs[NSFW_SS_MAX_OBJDESC_NUM]; - int g_nsfw_ss_objDesNum; -} nsfw_ss_objDescManager_t; + nsfw_ss_obj_desc_t *g_nsfw_ss_obj_descs[NSFW_SS_MAX_OBJDESC_NUM]; + int g_nsfw_ss_obj_des_num; +} nsfw_ss_obj_desc_manager_t; -extern nsfw_ss_objDescManager_t g_nsfw_ss_objDescManager; +/* package the parameters to a struct */ +typedef struct _nsfw_ss_obj_restore +{ + void *objMem; /*memory of object */ + void *mem; /*memory of storage */ + u32 storeMemLen; /*maximal length of storage memory */ + u32 reserved; +} nsfw_ss_obj_restore_t; + +extern nsfw_ss_obj_desc_manager_t g_nsfw_ss_obj_desc_manager; -#define nsfw_ss_getObjDescManagerInst() (&g_nsfw_ss_objDescManager) +#define nsfw_ss_get_obj_desc_manager_inst() (&g_nsfw_ss_obj_desc_manager) /** - * @Function nsfw_ss_register_ObjDesc - * @Description Register object description to snapshot + * @Function nsfw_ss_registe_ObjDesc + * @Description Registe object description to snapshot * @param objDesc - description of object * @return void */ -extern void nsfw_ss_register_ObjDesc (nsfw_ss_objDesc_t * objDesc); +extern void nsfw_ss_register_obj_desc(nsfw_ss_obj_desc_t * objDesc); /** * @Function nsfw_ss_store * @Description store object to memory * @param (in) objType - type of object - * @param (in) obj - address of object memory + * @param (in) obj - adderss of object memory * @param (in) storeMem - address of memory to store object data * @param (in) storeMemLen - maximal length of storage memory * @return positive integer means length of memory cost on success. return -1 if error */ -extern int nsfw_ss_store (u16 objType, void *obj, void *storeMem, - u32 storeMemLen); +extern int nsfw_ss_store(u16 objType, void *obj, void *storeMem, + u32 storeMemLen); /** * @Function nsfw_ss_restore * @Description restore object from memory - * @param (in) objMem - memory of object - * @param (in) mem - memory of storage - * @param (in) storeMemLen - maximal length of storage memory + * @param (in) obj_res - memory of object/storage memory info + * @param (in) count - recursion max num * @return positive integer stands on object type, -1 on error */ -extern int nsfw_ss_restore (void *objMem, void *mem, u32 storeMemLen); +extern int nsfw_ss_restore(nsfw_ss_obj_restore_t * obj_res); /** - * @Function nsfw_ss_getObjStoreMemLen + * @Function nsfw_ss_get_obj_store_mem_len * @Description Get the maximal memory it needs * @param (in) objType - type of object * @return length of memory needs, -1 if error */ -extern int nsfw_ss_getObjStoreMemLen (int objType); +extern int nsfw_ss_get_obj_store_mem_len(int objType); #define _NSFW_SNAPSHOT_OBJDESC_REGISTER_SURFIX(_value, _surfix) \ + \ static __attribute__((__constructor__(121))) void nsfw_snapshot_objdesc_register_constructor##_surfix(void){\ - nsfw_ss_register_ObjDesc((_value));\ + nsfw_ss_register_obj_desc((_value));\ + \ } #define NSFW_SNAPSHOT_OBJDESC_REGISTER_SURFIX(_value, _surfix) \ @@ -130,7 +139,7 @@ extern int nsfw_ss_getObjStoreMemLen (int objType); NSFW_SNAPSHOT_OBJDESC_REGISTER_SURFIX(_value, __LINE__) /** - * Using this macro to register object description + * Using this marcro to register object description */ #define NSFW_SS_REGSITER_OBJDESC(_value) \ NSFW_SNAPSHOT_OBJDESC_REGISTER_UNIQUE(_value) diff --git a/src/framework/include/nsfw_upgrade.h b/src/framework/include/nsfw_upgrade.h index d5cb5aa..a4e809c 100644 --- a/src/framework/include/nsfw_upgrade.h +++ b/src/framework/include/nsfw_upgrade.h @@ -32,9 +32,9 @@ extern "C" { #define USE_MEM_BIT(mem_bit, struct, mem) (mem_bit |= ((i64)1 << struct ## _ ## mem)) -#define UPGRADE_MEM_VAL(mem_bit, struct, mem, obj, default) { \ +#define UPGRADE_MEM_VAL(mem_bit, struct, mem, obj, defalut) { \ if (!GET_MEM_BIT(mem_bit, struct, mem)){ \ - obj->mem = default; \ + obj->mem = defalut; \ } \ } diff --git a/src/framework/include/nstack_log.h b/src/framework/include/nstack_log.h deleted file mode 100644 index 9473aa4..0000000 --- a/src/framework/include/nstack_log.h +++ /dev/null @@ -1,474 +0,0 @@ -/* -* -* 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_LOG_H_ -#define _NSTACK_LOG_H_ -/*==============================================* - * include header files * - *----------------------------------------------*/ -#pragma GCC diagnostic ignored "-Wcpp" -#include <stdio.h> -#include <string.h> -#include <stdint.h> -#include <stdarg.h> -#include <stdlib.h> -#include <sys/time.h> -#include <sys/types.h> -#include <unistd.h> - -#include <unistd.h> -#include <sys/syscall.h> -#include <sys/types.h> -#include <signal.h> -#include "types.h" - -#include "glog/nstack_glog.ph" -#include "glog/nstack_glog_in.h" - -#define NSTACK_GETVER_MODULE "nStack" - -#ifndef NSTACK_GETVER_VERSION -#error "need define version first" -#endif - -#define NSTACK_GETVER_BUILDTIME "[" __DATE__ "]" "[" __TIME__ "]" -#define NSTACK_VERSION NSTACK_GETVER_VERSION " (" NSTACK_GETVER_MODULE ") " NSTACK_GETVER_BUILDTIME - -#define LOG_TIME_STAMP_LEN 17 // "YYYYMMDDHHMMSS"; - -/*==============================================* - * constants or macros define * - *----------------------------------------------*/ -typedef enum _LOG_MODULE -{ - NSOCKET = 1, - STACKX, - OPERATION, - MASTER, - LOGTCP, - LOGUDP, - LOGIP, - LOGCMP, - LOGARP, - LOGRTE, - LOGHAL, - LOGDFX, - LOGFW, - LOGSBR, - MAX_LOG_MODULE -} LOG_MODULE; - -enum _LOG_TYPE -{ - LOG_TYPE_NSTACK = 0, - LOG_TYPE_OPERATION, - LOG_TYPE_MASTER, - LOG_TYPE_APP, - MAX_LOG_TYPE -}; - -enum _LOG_PROCESS -{ - LOG_PRO_NSTACK = 0, - LOG_PRO_MASTER, - LOG_PRO_APP, - LOG_PRO_OMC_CTRL, - LOG_PRO_INVALID -}; - -#define LOG_INVALID_VALUE 0xFFFF - -#define NSLOG_DBG 0x10 -#define NSLOG_INF 0x08 -#define NSLOG_WAR 0x04 -#define NSLOG_ERR 0x02 -#define NSLOG_EMG 0x01 -#define NSLOG_OFF 0x00 - -#define LOG_LEVEL_EMG "emg" -#define LOG_LEVEL_ERR "err" -#define LOG_LEVEL_WAR "war" -#define LOG_LEVEL_DBG "dbg" -#define LOG_LEVEL_INF "inf" - -#define GET_FILE_NAME(name_have_path) strrchr(name_have_path,'/')?strrchr(name_have_path,'/')+1:name_have_path - -#define NSTACK_LOG_NAME "/var/log/nStack/" - -#define STACKX_LOG_NAME "running.log" - -#define OPERATION_LOG_NAME "operation.log" - -#define MASTER_LOG_NAME "master.log" - -#define OMC_CTRL_LOG_NAME "omc_ctrl.log" - -#define FAILURE_LOG_NAME "fail_dump.log" - -#define FLUSH_TIME 10 - -#define APP_LOG_SIZE 30 -#define APP_LOG_COUNT 10 -#define APP_LOG_PATH "/var/log" -#define APP_LOG_NAME "nStack_nSocket.log" - -#define NS_LOG_STACKX_ON 0x80U -#define NS_LOG_STACKX_TRACE 0x40U -#define NS_LOG_STACKX_STATE 0x20U -#define NS_LOG_STACKX_FRESH 0x10U -#define NS_LOG_STACKX_HALT 0x08U -#define NS_LOG_STACKX_OFF 0x00U - -#define NULL_STRING "" -#define MODULE_INIT_FORMAT_STRING "module %s]name=[%s]%s" -#define MODULE_INIT_START "init" -#define MODULE_INIT_FAIL "start failed" -#define MODULE_INIT_SUCCESS "start success" - -#define PRE_INIT_LOG_LENGTH 128 - -struct nstack_logs -{ - uint32_t level; /**< Log level. */ - int pad64; - int inited; - int file_type; -}; - -struct log_init_para -{ - uint32_t run_log_size; - uint32_t run_log_count; - char *run_log_path; - uint32_t mon_log_size; //master and ctrl both use the parameter to reduce the redundancy - uint32_t mon_log_count; //master and ctrl both use the parameter to reduce the redundancy - char *mon_log_path; //master and ctrl both use the parameter to reduce the redundancy -}; - -enum LOG_CTRL_ID -{ - // for socket api - LOG_CTRL_SEND = 0, - LOG_CTRL_RECV, - LOG_CTRL_SENDMSG, - LOG_CTRL_RECVMSG, - LOG_CTRL_READ, - LOG_CTRL_WRITE, - LOG_CTRL_READV, - LOG_CTRL_WRITEV, - LOG_CTRL_GETSOCKNAME, - LOG_CTRL_GETPEERNAME, - LOG_CTRL_GETSOCKOPT, - - // for nstack service - LOG_CTRL_RECV_QUEUE_FULL, - LOG_CTRL_L4_RECV_QUEUE_FULL, - LOG_CTRL_HUGEPAGE_ALLOC_FAIL, - LOG_CTRL_TCP_MEM_NOT_ENOUGH, - LOG_CTRL_IPREASS_OVERFLOW, - LOG_CTRL_ID_MAX -}; - -struct log_ctrl_info -{ - u32 expire_time; - u32 unprint_count; - struct timespec last_log_time; -}; - -struct pre_init_info -{ - uint32_t level; /**< Log level. */ - char log_buffer[PRE_INIT_LOG_LENGTH]; -}; - -#define NS_LOG_STACKX(dbug,_module,_prestr,_level,fmt, ...) \ -{\ - if ((dbug) & NS_LOG_STACKX_ON)\ - {\ - NS_LOGPID(_module,_prestr,_level,fmt,##__VA_ARGS__);\ - }\ -}\ - - -/***************************************************************************** -* Prototype : nstack_get_log_level -* Description : get log level -* Input : int module -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -extern struct nstack_logs g_nstack_logs[MAX_LOG_MODULE]; -static inline int -nstack_get_log_level (int module) -{ - /* validity check for path */ - if ((MAX_LOG_MODULE <= module) || (module < 0)) - { - return -1; - } - - return g_nstack_logs[module].level; -} - -/***************************************************************************** -* Prototype : level_stoa -* Description : convert stack log level to app log level -* Input : unsigned int nstack_level -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -static inline unsigned int -level_stoa (unsigned int level) -{ - unsigned int golg_level; - switch (level) - { - case NSLOG_DBG: - golg_level = GLOG_LEVEL_DEBUG; - break; - case NSLOG_INF: - golg_level = GLOG_LEVEL_INFO; - break; - case NSLOG_WAR: - golg_level = GLOG_LEVEL_WARNING; - break; - case NSLOG_ERR: - golg_level = GLOG_LEVEL_ERROR; - break; - case NSLOG_EMG: - golg_level = GLOG_LEVEL_FATAL; - break; - default: - golg_level = GLOG_LEVEL_BUTT; - break; - } - return golg_level; -} - -/* use the glog function to replace old nstack log module */ - -/* segregate the dump info */ -#define LOG_TYPE(_module, _level) \ - (((STACKX == _module) && (NSLOG_EMG == _level)) ? GLOG_LEVEL_ERROR : ((OPERATION == _module) ? GLOG_LEVEL_WARNING : GLOG_LEVEL_INFO)) - -#define log_shooting(_module,_level) \ - ((NULL == g_log_hook_tag.log_hook) ? (nstack_get_log_level(_module) >= _level) : (level_stoa(_level) >= g_log_hook_tag.level)) - -/* add the non reentry protection */ -extern __thread unsigned int nstack_log_nonreentry; - -/* hanging up version check log need restrain */ -extern int ctrl_log_switch; - -#define NS_LOGPID(_module,_prestr,_level,fmt, ...) \ -{\ - if (log_shooting(_module, _level) && (0 == nstack_log_nonreentry) && (0 == ctrl_log_switch))\ - {\ - nstack_log_nonreentry = 1;\ - if(nstack_log_info_check(_module, _level))\ - glog_print(LOG_TYPE(_module,_level),_prestr,level_stoa(_level),-1,GET_FILE_NAME(__FILE__),\ - __LINE__,__func__,fmt, ##__VA_ARGS__);\ - nstack_log_nonreentry = 0;\ - }\ -} - -#define NS_LOG_CTRL(_id, _module, _prestr, _level, fmt, ...) \ -{\ - if (log_shooting(_module, _level) && (0 == nstack_log_nonreentry) && check_log_prt_time(_id))\ - {\ - nstack_log_nonreentry = 1;\ - if(nstack_log_info_check(_module, _level))\ - glog_print(LOG_TYPE(_module,_level),_prestr,level_stoa(_level),get_unprt_log_count(_id),\ - GET_FILE_NAME(__FILE__),__LINE__,__func__,fmt, ##__VA_ARGS__);\ - clr_unprt_log_count(_id);\ - nstack_log_nonreentry = 0;\ - }\ -} - -#define NS_LOG_CTRL_STACKX(_id, dbug,_module,_prestr,_level,fmt, ...) \ -{\ - if ((dbug) & NS_LOG_STACKX_ON)\ - {\ - NS_LOG_CTRL(_id, _module,_prestr,_level,fmt,##__VA_ARGS__);\ - }\ -}\ - - -/*for every log modules should def marcos below use a sort module name, just like MON means Monitor*/ -#define NSMON_LOGINF(fmt, ...) NS_LOGPID(MASTER,"NSMON",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSMON_LOGDBG(fmt, ...) NS_LOGPID(MASTER,"NSMON",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSMON_LOGWAR(fmt, ...) NS_LOGPID(MASTER,"NSMON",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSMON_LOGERR(fmt, ...) NS_LOGPID(MASTER,"NSMON",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSPOL_LOGINF(debug,fmt, ...)NS_LOG_STACKX(debug,STACKX,"NSLWIP",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSPOL_LOGDBG(debug,fmt, ...) NS_LOG_STACKX(debug,STACKX,"NSLWIP",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSPOL_LOGWAR(debug,fmt, ...) NS_LOG_STACKX(debug,STACKX,"NSLWIP",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSPOL_LOGERR(fmt, ...) NS_LOGPID(STACKX,"NSLWIP",NSLOG_ERR,fmt,##__VA_ARGS__) -#define NSPOL_LOGEMG(fmt, ...) NS_LOGPID(STACKX,"NSLWIP",NSLOG_EMG,fmt,##__VA_ARGS__) - -#define NSOPR_LOGINF(fmt, ...) NS_LOGPID(OPERATION,"NSOPR",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSOPR_LOGDBG(fmt, ...) NS_LOGPID(OPERATION,"NSOPR",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSOPR_LOGWAR(fmt, ...) NS_LOGPID(OPERATION,"NSOPR",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSOPR_LOGERR(fmt, ...) NS_LOGPID(OPERATION,"orchestration",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSSOC_LOGINF(fmt, ...) NS_LOGPID(NSOCKET,"NSSOC",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSSOC_LOGDBG(fmt, ...) NS_LOGPID(NSOCKET,"NSSOC",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSSOC_LOGWAR(fmt, ...) NS_LOGPID(NSOCKET,"NSSOC",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSSOC_LOGERR(fmt, ...) NS_LOGPID(NSOCKET,"NSSOC",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSSBR_LOGINF(fmt, ...) NS_LOGPID(LOGSBR,"NSSBR",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSSBR_LOGDBG(fmt, ...) NS_LOGPID(LOGSBR,"NSSBR",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSSBR_LOGWAR(fmt, ...) NS_LOGPID(LOGSBR,"NSSBR",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSSBR_LOGERR(fmt, ...) NS_LOGPID(LOGSBR,"NSSBR",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSCOMM_LOGINF(fmt, ...) NS_LOGPID(LOGRTE, "NSRTE",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSCOMM_LOGDBG(fmt, ...) NS_LOGPID(LOGRTE, "NSRTE",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSCOMM_LOGWAR(fmt, ...) NS_LOGPID(LOGRTE, "NSRTE",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSCOMM_LOGERR(fmt, ...) NS_LOGPID(LOGRTE, "NSRTE",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSTCP_LOGINF(fmt, ...) NS_LOGPID(LOGTCP,"NSTCP",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSTCP_LOGDBG(fmt, ...) NS_LOGPID(LOGTCP,"NSTCP",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSTCP_LOGWAR(fmt, ...) NS_LOGPID(LOGTCP,"NSTCP",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSTCP_LOGERR(fmt, ...) NS_LOGPID(LOGTCP,"NSTCP",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSIP_LOGINF(fmt, ...) NS_LOGPID(LOGIP,"NSIP",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSIP_LOGDBG(fmt, ...) NS_LOGPID(LOGIP,"NSIP",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSIP_LOGWAR(fmt, ...) NS_LOGPID(LOGIP,"NSIP",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSIP_LOGERR(fmt, ...) NS_LOGPID(LOGIP,"NSIP",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSUDP_LOGINF(fmt, ...) NS_LOGPID(LOGUDP,"NSUDP",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSUDP_LOGDBG(fmt, ...) NS_LOGPID(LOGUDP,"NSUDP",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSUDP_LOGWAR(fmt, ...) NS_LOGPID(LOGUDP,"NSUDP",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSUDP_LOGERR(fmt, ...) NS_LOGPID(LOGUDP,"NSUDP",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSHAL_LOGINF(fmt, ...) NS_LOGPID(LOGHAL,"NSHAL",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSHAL_LOGDBG(fmt, ...) NS_LOGPID(LOGHAL,"NSHAL",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSHAL_LOGWAR(fmt, ...) NS_LOGPID(LOGHAL,"NSHAL",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSHAL_LOGERR(fmt, ...) NS_LOGPID(LOGHAL,"NSHAL",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSARP_LOGINF(fmt, ...) NS_LOGPID(LOGARP,"NSARP",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSARP_LOGDBG(fmt, ...) NS_LOGPID(LOGARP,"NSARP",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSARP_LOGWAR(fmt, ...) NS_LOGPID(LOGARP,"NSARP",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSARP_LOGERR(fmt, ...) NS_LOGPID(LOGARP,"NSARP",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSDFX_LOGINF(fmt, ...) NS_LOGPID(LOGDFX,"NSDFX",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSDFX_LOGDBG(fmt, ...) NS_LOGPID(LOGDFX,"NSDFX",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSDFX_LOGWAR(fmt, ...) NS_LOGPID(LOGDFX,"NSDFX",NSLOG_WAR,fmt,##__VA_ARGS__) -#define NSDFX_LOGERR(fmt, ...) NS_LOGPID(LOGDFX,"NSDFX",NSLOG_ERR,fmt,##__VA_ARGS__) - -#define NSFW_LOGINF(fmt, ...) NS_LOGPID(LOGFW,"NSFW",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSFW_LOGDBG(fmt, ...) NS_LOGPID(LOGFW,"NSFW",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSFW_LOGERR(fmt, ...) NS_LOGPID(LOGFW,"NSFW",NSLOG_ERR,fmt,##__VA_ARGS__) -#define NSFW_LOGWAR(fmt, ...) NS_LOGPID(LOGFW,"NSFW",NSLOG_WAR,fmt,##__VA_ARGS__) - -#define NSAM_LOGINF(fmt, ...) NS_LOGPID(LOGFW,"NSAM",NSLOG_INF,fmt,##__VA_ARGS__) -#define NSAM_LOGDBG(fmt, ...) NS_LOGPID(LOGFW,"NSAM",NSLOG_DBG,fmt,##__VA_ARGS__) -#define NSAM_LOGERR(fmt, ...) NS_LOGPID(LOGFW,"NSAM",NSLOG_ERR,fmt,##__VA_ARGS__) -#define NSAM_LOGWAR(fmt, ...) NS_LOGPID(LOGFW,"NSAM",NSLOG_WAR,fmt,##__VA_ARGS__) - -#define INIT_LOG_ASSEM(log_module,_prestr,_level, init_module , function, errString, errValue, status) \ - if ((LOG_INVALID_VALUE <= errValue) && (1 == sizeof(errString))) \ - { \ - NS_LOGPID(log_module,_prestr, _level,MODULE_INIT_FORMAT_STRING, (char*)status, init_module, function ); \ - } \ - else if (LOG_INVALID_VALUE <= errValue)\ - { \ - NS_LOGPID(log_module,_prestr, _level,MODULE_INIT_FORMAT_STRING",err_string=%s", (char*)status, init_module, function, errString ); \ - } \ - else if (1 == sizeof(errString))\ - { \ - NS_LOGPID(log_module,_prestr, _level,MODULE_INIT_FORMAT_STRING",err_value=%d", (char*)status, init_module, function, errValue ); \ - } \ - else \ - { \ - NS_LOGPID(log_module,_prestr, _level,MODULE_INIT_FORMAT_STRING",err_string=%s,err_value=%d", (char*)status, init_module, function, errString, errValue ); \ - } \ - -#define INITPOL_LOGINF(init_module_name, function, err_string, err_value, status) \ - INIT_LOG_ASSEM(STACKX,"NSLWIP",NSLOG_INF,init_module_name , function, err_string, err_value, status)\ - -#define INITPOL_LOGERR(init_module_name, function, err_string, err_value, status) \ - INIT_LOG_ASSEM(STACKX,"NSLWIP",NSLOG_ERR,init_module_name , function, err_string, err_value, status)\ - -#define INITTCP_LOGINF(init_module_name , function, err_string, err_value, status) \ - INIT_LOG_ASSEM(LOGTCP,"NSTCP",NSLOG_INF,init_module_name , function, err_string, err_value, status)\ - -#define INITTCP_LOGERR(init_module_name , function, err_string, err_value, status) \ - INIT_LOG_ASSEM(LOGTCP,"NSTCP",NSLOG_ERR,init_module_name , function, err_string, err_value, status)\ - -#define INITMON_LOGERR(init_module_name , function, err_string, err_value, status) \ - INIT_LOG_ASSEM(MASTER,"NSMON",NSLOG_ERR,init_module_name , function, err_string, err_value, status)\ - -#define INITSOC_LOGERR(init_module_name , function, err_string, err_value, status) \ - INIT_LOG_ASSEM(NSOCKET,"NSSOC",NSLOG_ERR,init_module_name , function, err_string, err_value, status) - -#define NSPOL_DUMP_LOGINF(fmt, ...) NSPOL_LOGINF(0x80, fmt, ##__VA_ARGS__) -#define NSPOL_DUMP_LOGDBG(fmt, ...) NSPOL_LOGDBG(0x80, fmt, ##__VA_ARGS__) -#define NSPOL_DUMP_LOGERR(fmt, ...) NSPOL_LOGERR(fmt, ##__VA_ARGS__) -#define NSPOL_DUMP_LOGWAR(fmt, ...) NSPOL_LOGWAR(0x80, fmt, ##__VA_ARGS__) - -/*==============================================* - * routines' or functions' implementations * - *----------------------------------------------*/ - -void save_pre_init_log (uint32_t level, char *fmt, ...); -void write_pre_init_log (); - -void set_log_init_para (struct log_init_para *para); - -void nstack_setlog_level (int module, uint32_t level); -bool nstack_log_info_check (uint32_t module, uint32_t level); -int nstack_log_init (); -void nstack_log_init_app (); -int get_app_env_log_path (char *app_file_path, unsigned int app_file_size); -void set_log_proc_type (int log_proc_type); - -int setlog_level_value (const char *param, const char *value); -int get_str_value (const char *arg); -int check_log_dir_valid (const char *path); -void nstack_segment_error (int s); -void init_log_ctrl_info (); -void set_log_ctrl_time (int id, int ctrl_time); - -int cmp_log_path (const char *path); - -#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 /* sys_sleep_ns */ - -int check_log_prt_time (int id); -int get_unprt_log_count (int id); -void clr_unprt_log_count (int id); - -void get_current_time (char *buf, const int len); - -#endif diff --git a/src/framework/include/nstack_rd_data.h b/src/framework/include/nstack_rd_data.h index 3924680..4d6ed15 100644 --- a/src/framework/include/nstack_rd_data.h +++ b/src/framework/include/nstack_rd_data.h @@ -17,64 +17,62 @@ #ifndef __NSTACK_RD_DATA_H #define __NSTACK_RD_DATA_H +#include "dmm_spinlock.h" +#include "nstack_rd_api.h" + /*choose router base on ip seg*/ -#define STACK_NAME_MAX 32 +#define STACK_NAME_MAX (32) #define RD_PLANE_NAMELEN (32) -#define NSTACK_IP_BIT_MAX (32) #define NSTACK_RD_DATA_MAX (2048) -#define RD_IP_STR_MAX_LEN (32) +/* correspond to the parameters called by *socket* */ typedef enum __rd_data_type { - RD_DATA_TYPE_IP, - RD_DATA_TYPE_PROTO, - RD_DATA_TYPE_MAX, + RD_DATA_TYPE_IP, /* domain */ + RD_DATA_TYPE_IP6, + RD_DATA_TYPE_TYPE, /* type */ + RD_DATA_TYPE_PROTO, /* protocol */ + RD_DATA_TYPE_MAX, } rd_data_type; typedef enum __rd_node_state { - RD_NODE_USELESS, - RD_NODE_USING, - RD_NODE_DELETING, - RD_NODE_MAX, + RD_NODE_USELESS, + RD_NODE_USING, + RD_NODE_DELETING, + RD_NODE_MAX, } rd_node_state; -/*route info base on ip*/ -typedef struct __rd_route_ip_data -{ - unsigned int addr; - unsigned int masklen; - unsigned int resev[2]; -} rd_ip_data; - -/*route data*/ +/* route data */ typedef struct __rd_route_data { - /*route info type , for example base on ip */ - rd_data_type type; - char stack_name[RD_PLANE_NAMELEN]; - union - { - rd_ip_data ipdata; - unsigned int proto_type; - /*:::other type to be add */ - }; + /*route info type , for example base on ip */ + rd_data_type type; + char stack_name[RD_PLANE_NAMELEN]; + union + { + rd_ip_data ipdata; + rd_type_data type_data; + rd_proto_data proto_data; + rd_ip6_data ip6data; + /*:::other type to be add */ + }; } rd_route_data; typedef struct __rd_route_node { - rd_node_state flag; - int agetime; - rd_route_data data; + rd_node_state flag; + int agetime; + rd_route_data data; } rd_route_node; typedef struct __rd_route_table { - int size; - int icnt; - rd_route_node node[NSTACK_RD_DATA_MAX]; + volatile int rdtbl_ver; + dmm_spinlock_t rd_lock; + int size; + int icnt; + rd_route_node node[NSTACK_RD_DATA_MAX]; } rd_route_table; -#define MASK_V(ipaddr, masklen) ((ipaddr) & (~0 << (NSTACK_IP_BIT_MAX - (masklen)))) - #endif diff --git a/src/framework/include/nstack_securec.h b/src/framework/include/nstack_securec.h deleted file mode 100644 index c9efb4f..0000000 --- a/src/framework/include/nstack_securec.h +++ /dev/null @@ -1,145 +0,0 @@ -/* -* -* 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_SECUREC_H__ -#define __NSTACK_SECUREC_H__ - -/*if you need export the function of this library in Win32 dll, use __declspec(dllexport) */ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C" { -/* *INDENT-ON* */ - -#endif /* */ -#ifndef SECUREC_LIB -#include <stdio.h> -#include <stdarg.h> -#include <wchar.h> -#include <string.h> - -#ifndef NULL -#define NULL ((void *)0) -#endif /* - */ - -/*define error code*/ -#ifndef errno_t -typedef int errno_t; - -#endif /* - */ - -/* success */ -#define EOK (0) - -/* invalid parameter */ -#ifndef EINVAL -#define EINVAL (22) -#endif /* - */ - -#define EINVAL_AND_RESET (22 | 0X80) -#define ERANGE_AND_RESET (34 | 0X80) - -#define SCANF_S scanf -#define WSCANF_S wscanf -#define VSCANF_S vscanf -#define VWSCANF_S vwscanf -#define FSCANF_S fscanf -#define FWSCANF_S fwscanf -#define VFSCANF_S vfscanf -#define VFWSCANF_S vfwscanf -#define SSCANF_S sscanf -#define SWSCANF_S swscanf -#define VSSCANF_S vsscanf -#define VSWSCANF_S vswscanf - -#define SPRINTF_S(a, b, ...) sprintf(a, ##__VA_ARGS__) -#define SWPRINTF_S(a, b, c, ...) swprintf(a, b, c, ##__VA_ARGS__) -#define VSPRINTF_S(a, b, c, d) vsprintf(a, c, d) -#define VSWPRINTF_S(a, b, c, d) vswprintf(a, b, c, d) -#define VSNPRINTF_S(a, b, c, d, e) vsnprintf(a, c, d, e) -#define SNPRINTF_S(a, b, c, d, ...) snprintf(a, c, d, ##__VA_ARGS__) - -#define WMEMCPY_S(a, b, c, d) ((NULL == wmemcpy(a, c, d)) ? EINVAL : EOK) -#define MEMMOVE_S(a, b, c, d) ((NULL == memmove(a, c, d)) ? EINVAL : EOK) -#define WMEMMOVE_S(a, b, c, d) ((NULL == wmemmove(a, c, d)) ? EINVAL : EOK) -#define WCSCPY_S(a, b, c) ((NULL == wcscpy(a, c)) ? EINVAL : EOK) -#define WCSNCPY_S(a, b, c, d) ((NULL == wcsncpy(a, c, d)) ? EINVAL : EOK) -#define WCSCAT_S(a, b, c) ((NULL == wcscat(a, c)) ? EINVAL : EOK) -#define WCSNCAT_S(a, b, c, d) ((NULL == wcsncat(a, c, d)) ? EINVAL : EOK) - -#define MEMSET_S(a, b, c, d) ((NULL == memset(a, c, d)) ? EINVAL : EOK) -#define MEMCPY_S(a, b, c, d) ((NULL == memcpy(a, c, d)) ? EINVAL : EOK) -#define STRCPY_S(a, b, c) ((NULL == strcpy(a, c )) ? EINVAL : EOK) -#define STRNCPY_S(a, b, c, d) ((NULL == strncpy(a, c, d)) ? EINVAL : EOK) -#define STRCAT_S(a, b, c) ((NULL == strcat(a, c)) ? EINVAL : EOK) -#define STRNCAT_S(a, b, c, d) ((NULL == strncat(a, c, d)) ? EINVAL : EOK) - -#define STRTOK_S(a, b, c) strtok(a, b) -#define WCSTOK_S(a, b, c) wcstok(a, b) -#define GETS_S(a, b) gets(a) - -#else /* */ -#include "securec.h" - -#define SCANF_S scanf_s -#define WSCANF_S wscanf_s -#define VSCANF_S vscanf_s -#define VWSCANF_S vwscanf_s -#define FSCANF_S fscanf_s -#define FWSCANF_S fwscanf_s -#define VFSCANF_S vfscanf_s -#define VFWSCANF_S vfwscanf_s -#define SSCANF_S sscanf_s -#define SWSCANF_S swscanf_s -#define VSSCANF_S vsscanf_s -#define VSWSCANF_S vswscanf_s - -#define SPRINTF_S(a, b, ...) sprintf_s (a, b, ##__VA_ARGS__) -#define SWPRINTF_S(a, b, c, ...) swprintf_s(a, b, c, ##__VA_ARGS__) -#define VSPRINTF_S(a, b, c, d) vsprintf_s(a, b, c, d) -#define VSWPRINTF_S(a, b, c, d) vswprintf_s(a, b, c, d) -#define VSNPRINTF_S(a, b, c, d, e) vsnprintf_s(a, b, c, d, e) -#define SNPRINTF_S(a, b, c, d, ...) snprintf_s(a, b, c, d, ##__VA_ARGS__) - -#define WMEMCPY_S(a, b, c, d) wmemcpy_s(a, b, c, d) -#define MEMMOVE_S(a, b, c, d) memmove_s(a, b, c, d) -#define WMEMMOVE_S(a, b, c, d) wmemmove_s(a, b, c, d) -#define WCSCPY_S(a, b, c) wcscpy_s(a, b, c) -#define WCSNCPY_S(a, b, c, d) wcsncpy_s(a, b, c, d) -#define WCSCAT_S(a, b, c) wcscat_s(a, b, c) -#define WCSNCAT_S(a, b, c, d) wcsncat_s(a, b, c, d) - -#define MEMSET_S(a, b, c, d) memset_s(a, b, c, d) -#define MEMCPY_S(a, b, c, d) memcpy_s(a, b, c, d) -#define STRCPY_S(a, b, c) strcpy_s(a, b, c) -#define STRNCPY_S(a, b, c, d) strncpy_s(a, b, c, d) -#define STRCAT_S(a, b, c) strcat_s(a, b, c) -#define STRNCAT_S(a, b, c, d) strncat_s(a, b, c, d) - -#define STRTOK_S(a, b, c) strtok_s(a, b, c) -#define WCSTOK_S(a, b, c) wcstok_s(a, b, c) -#define GETS_S(a, b) gets_s(a, b) -#endif /* */ -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -#endif /* __NSTACK_SECUREC_H__ */ diff --git a/src/framework/include/nstack_share_res.h b/src/framework/include/nstack_share_res.h new file mode 100644 index 0000000..930456d --- /dev/null +++ b/src/framework/include/nstack_share_res.h @@ -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. +*/ + +#ifndef NSTACK_SHARE_RES_H +#define NSTACK_SHARE_RES_H + +#include "nstack_log.h" +#include "compiling_check.h" +#include "nsfw_recycle_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#define NSTACK_VERSION_SHM "nstack_version" +#define MAX_U16_INT 0xFFFF +#define NSTACK_VERSION_LEN 128 + +COMPAT_PROTECT_RETURN(NSTACK_VERSION_LEN, 128); +#define MAX_UNMATCH_VER_CNT 32 +COMPAT_PROTECT_RETURN(MAX_UNMATCH_VER_CNT, 32); + +/* Add dfx timer tick */ +#define NSTACK_GLOBAL_TICK_SHM "nstack_global_tick" + +typedef struct unmatch_ver_info +{ + int unmatch_count; + char lib_version[NSTACK_VERSION_LEN]; + char first_time_stamp[LOG_TIME_STAMP_LEN]; +} unmatch_ver_info_t; + +/* Add dfx timer tick Begin */ +#define DFX_TMR_INTERVAL 60000 /*60 seconds */ +typedef struct nstack_tick_info +{ + u64 *tick_ptr; // tick from shared memory + u64 interval; // tick interval, only used in stack process + /* tick refference, updated periodically and read in tcpip_thread only */ + struct timeval ref_time; // ref tick time + u64 ref_tick; // ref tick +} nstack_tick_info_t; +/* Add dfx timer tick End */ + +int nstack_init_share_res(); +int nstack_attach_share_res(); + +void fork_parent_start(i32 ppid); +void fork_wait_child_done(u32 ppid); +void fork_parent_failed(u32 ppid); +void fork_child_start(u32 ppid); +void fork_child_done(u32 ppid); +int fork_recycle_check(u32 pid); +void fork_delay_recycle(u8 sec, nsfw_recycle_fun fun); + +static inline u16 calculate_elapse(u64 a, u64 b) +{ + u64 ret = 0; + if (a > b) + { + ret = a - b; + return ret < MAX_U16_INT ? (u16) ret : (u16) MAX_U16_INT; + } + else + { + return 0; + } +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif + +#endif diff --git a/src/framework/init/CMakeLists.txt b/src/framework/init/CMakeLists.txt deleted file mode 100644 index ff8d4d2..0000000 --- a/src/framework/init/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -######################################################################### -# -# 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(LIBSBR_SRC fw_init.c fw_module.c) - -SET(COMM_CONFIG ${PROJECT_SOURCE_DIR}/src/framework/common/base/include/common_sys_config.h) -ADD_DEFINITIONS(-fPIC -mssse3) -ADD_DEFINITIONS(-include ${COMM_CONFIG}) - -ADD_LIBRARY(nStackfwinit static ${LIBSBR_SRC}) - diff --git a/src/framework/init/fw_init.c b/src/framework/init/fw_init.c index 2764479..636fe20 100644 --- a/src/framework/init/fw_init.c +++ b/src/framework/init/fw_init.c @@ -18,6 +18,7 @@ #include <stdlib.h> #include <string.h> #include "nstack_securec.h" +#include "nsfw_init_api.h" #include "fw_module.h" #include "nstack_log.h" @@ -27,290 +28,302 @@ extern "C"{ /* *INDENT-ON* */ #endif /* __cplusplus */ -NSTACK_STATIC int -nsfw_module_instance_isIndepend (nsfw_module_instance_t * inst) +int g_fw_init_err = 0; +int get_fw_init_err() { - nsfw_module_depends_t *dep = inst->depends; - while (dep) + return g_fw_init_err; +} + +void set_fw_init_err(int x) +{ + g_fw_init_err = x; +} + +NSTACK_STATIC int nsfw_module_instance_is_independ(nsfw_module_instance_t * + inst) +{ + nsfw_module_depends_t *dep = inst->depends; + while (dep) { - if (!dep->isReady) - return 1; - dep = dep->next; + if (!dep->isReady) + return 1; + dep = dep->next; } - return 0; + return 0; } -NSTACK_STATIC void -nsfw_module_instance_depend_check (nsfw_module_instance_t * inst) +NSTACK_STATIC void nsfw_module_instance_depend_check(nsfw_module_instance_t * + inst) { - nsfw_module_instance_t *curInst = nsfw_module_getManager ()->inst; - while (curInst) + nsfw_module_instance_t *curInst = nsfw_module_get_manager()->inst; + while (curInst) { - if (curInst == inst) - goto nextLoop; - if (NSFW_INST_STAT_CHECKING == curInst->stat - || NSFW_INST_STAT_DEPENDING == curInst->stat) + if (curInst == inst) + goto nextLoop; + if (NSFW_INST_STAT_CHECKING == curInst->stat + || NSFW_INST_STAT_DEPENDING == curInst->stat) { - nsfw_module_depends_t *dep = curInst->depends; - while (dep) + nsfw_module_depends_t *dep = curInst->depends; + while (dep) { - if (0 == dep->isReady && 0 == strcmp (dep->name, inst->name)) + if (0 == dep->isReady && 0 == strcmp(dep->name, inst->name)) { - dep->isReady = 1; /* Don't break for case that duplicate name exist, though I think it should + dep->isReady = 1; /* Don't break for case that duplicate name exist, though I think it should not happen */ } - dep = dep->next; + dep = dep->next; } } - nextLoop: - curInst = curInst->next; + nextLoop: /*this type usually use like this and no "space" */ + curInst = curInst->next; } } -/** - * @Function nstack_framework_init - * @Description Init child modules - * @param father instance , NULL means root - * @return 0 on success, -1 on error - */ -NSTACK_STATIC int -nstack_framework_initChild_unsafe (nsfw_module_instance_t * father) +NSTACK_STATIC int nstack_framework_init_child_unsafe(nsfw_module_instance_t * + father) { - NSFW_LOGDBG ("init framework module] name=%s", - father ? father->name : "NULL"); - - nsfw_module_instance_t *inst = nsfw_module_getManager ()->inst; + NSFW_LOGDBG("init framework module] name=%s", + father ? father->name : "NULL"); - while (inst) + nsfw_module_instance_t *inst = nsfw_module_get_manager()->inst; + int initRet = 0; + while (inst) { - NSFW_LOGDBG - ("init child] inst=%s, inst->father=%s, inst->depends=%s, inst->state=%d", - inst->name, inst->father ? inst->father->name : "NULL", - inst->depends ? inst->depends->name : "NULL", inst->stat); + NSFW_LOGDBG + ("init child] inst=%s, inst->father=%s, inst->depends=%s, inst->state=%d", + inst->name, inst->father ? inst->father->name : "NULL", + inst->depends ? inst->depends->name : "NULL", inst->stat); - if (father != inst->father) + if (father != inst->father) { - NSFW_LOGDBG ("inst->father not match] inst=%s, ", inst->name); + NSFW_LOGDBG("inst->father not match] inst=%s, ", inst->name); - inst = inst->next; - continue; + inst = inst->next; + continue; } - switch (inst->stat) + switch (inst->stat) { - case NSFW_INST_STAT_CHECKING: - /* First, check if any depends, then check if other instance depends on it */ - if (nsfw_module_instance_isIndepend (inst)) - { - inst->stat = NSFW_INST_STAT_DEPENDING; - NSFW_LOGDBG ("inst is still depending] name=%s", inst->name); - inst = inst->next; - break; - } + case NSFW_INST_STAT_CHECKING: + /* First, check if any depends, then check if other instance depends on it */ + if (nsfw_module_instance_is_independ(inst)) + { + inst->stat = NSFW_INST_STAT_DEPENDING; + NSFW_LOGDBG("inst is still depending] name=%s", + inst->name); + inst = inst->next; + break; + } - NSFW_LOGINF ("Going to init module] name=%s, init fun=%p", - inst->name, inst->fnInit); - if (NULL != inst->fnInit && 0 != inst->fnInit (inst->param)) - { - NSFW_LOGERR ("initial fail!!!] inst=%s", inst->name); - inst->stat = NSFW_INST_STAT_FAIL; - return -1; - } + NSFW_LOGINF("Going to init module]name=%s,init fun=%p", + inst->name, inst->fnInit); + if (NULL != inst->fnInit + && 0 != (initRet = inst->fnInit(inst->param))) + { + NSFW_LOGERR("initial fail]inst=%s,initRet=%d", + inst->name, initRet); + inst->stat = NSFW_INST_STAT_FAIL; + if (get_fw_init_err() == 0) /* record first init err */ + { + NSFW_LOGERR("update g_fw_init_err to %d", initRet); + /* TODO: now g_fw_init_err conveys errcode and be processed in master_main, + * better way is to regsiter an error-handler for each inst */ + set_fw_init_err(initRet); + } + return -1; + } - inst->stat = NSFW_INST_STAT_DONE; - nsfw_module_instance_depend_check (inst); + inst->stat = NSFW_INST_STAT_DONE; + nsfw_module_instance_depend_check(inst); - if (-1 == nsfw_module_addDoneNode (inst)) - { - NSFW_LOGERR ("add done node fail"); - } + if (-1 == nsfw_module_add_done_node(inst)) + { + NSFW_LOGERR("add done node fail"); + } - inst = nsfw_module_getManager ()->inst; /* check from begining */ - break; - case NSFW_INST_STAT_DEPENDING: - /* check if depending stat is still there */ - if (!nsfw_module_instance_isIndepend (inst)) - { - inst->stat = NSFW_INST_STAT_CHECKING; - break; - } - case NSFW_INST_STAT_FAIL: - case NSFW_INST_STAT_DONE: - default: - inst = inst->next; - break; + inst = nsfw_module_get_manager()->inst; /* check from begining */ + break; + case NSFW_INST_STAT_DEPENDING: + /* check if depending stat is still there */ + if (!nsfw_module_instance_is_independ(inst)) + { + inst->stat = NSFW_INST_STAT_CHECKING; + break; + } + case NSFW_INST_STAT_FAIL: + case NSFW_INST_STAT_DONE: + default: + inst = inst->next; + break; } } - return 0; + return 0; } -NSTACK_STATIC void -nstack_framework_printInstanceInfo (nsfw_module_instance_t * inst) +NSTACK_STATIC + void nstack_framework_print_instance_info(nsfw_module_instance_t * inst) { - if (NULL == inst) + if (NULL == inst) { - NSFW_LOGERR ("param error,inst==NULL"); - return; + NSFW_LOGERR("param err]inst=NULL"); + return; } - char info[1024] = ""; - int plen = 0; + char info[1000] = ""; + int plen = 0; - int ret = SPRINTF_S (info, sizeof (info), "Inst:%s,father:%s,depends:", - inst->name, - inst->father ? inst->father->name : "NULL"); + int ret = sprintf_s(info, sizeof(info), "Inst:%s,father:%s,depends:", + inst->name, + inst->father ? inst->father->name : "NULL"); - if (ret <= 0) + if (ret <= 0) { - NSFW_LOGERR ("Sprintf Error] module=%s,state=%d, ret=%d", inst->name, - inst->stat, ret); - return; + NSFW_LOGERR("Sprintf err]module=%s,state=%d,ret=%d", inst->name, + inst->stat, ret); + return; } - else + else { - plen += ret; + plen += ret; } - if (NULL == inst->depends) + if (NULL == inst->depends) { - ret = SPRINTF_S (info + plen, sizeof (info) - plen, "NULL"); - if (ret <= 0) + ret = sprintf_s(info + plen, sizeof(info) - plen, "NULL"); + if (ret <= 0) { - NSFW_LOGERR ("Sprintf Error] module=%s,state=%d, ret=%d", - inst->name, inst->stat, ret); - return; + NSFW_LOGERR("Sprintf Err]module=%s,state=%d,ret=%d", inst->name, + inst->stat, ret); + return; } - NSFW_LOGINF ("] inst info=%s", info); - return; + NSFW_LOGINF("]inst info=%s", info); + return; } - nsfw_module_depends_t *dep = inst->depends; - while (dep) + nsfw_module_depends_t *dep = inst->depends; + while (dep && (plen < (int) sizeof(info))) { - ret = SPRINTF_S (info + plen, sizeof (info) - plen, "%s ", dep->name); - if (ret <= 0) + ret = sprintf_s(info + plen, sizeof(info) - plen, "%s ", dep->name); + if (ret <= 0) { - NSFW_LOGERR ("Sprintf Error] module=%s,state=%d, ret=%d", - inst->name, inst->stat, ret); - return; + NSFW_LOGERR("Sprintf Err]module=%s,state=%d,ret=%d", inst->name, + inst->stat, ret); + return; } - plen += ret; - dep = dep->next; + plen += ret; + dep = dep->next; } - NSFW_LOGINF ("] inst info=%s", info); + NSFW_LOGINF("]inst info=%s", info); } -NSTACK_STATIC void -nstack_framework_printInitialResult () +NSTACK_STATIC void nstack_framework_print_initial_result() { - nsfw_module_manager_t *manager = nsfw_module_getManager (); + nsfw_module_manager_t *manager = nsfw_module_get_manager(); - if (manager->doneHead) + if (manager->doneHead) { - NSFW_LOGINF ("Here is the initial done modules: "); + NSFW_LOGINF("Here is the initial done modules: "); - nsfw_module_doneNode_t *curNode = manager->doneHead; - while (curNode) + nsfw_module_done_node_t *curNode = manager->doneHead; + while (curNode) { - nstack_framework_printInstanceInfo (curNode->inst); - curNode = curNode->next; + nstack_framework_print_instance_info(curNode->inst); + curNode = curNode->next; } } - else + else { - NSFW_LOGERR ("No initial done modules"); + NSFW_LOGERR("No initial done modules"); } - nsfw_module_instance_t *curInst = manager->inst; - int unDoneNum = 0; - while (curInst) + nsfw_module_instance_t *curInst = manager->inst; + int unDoneNum = 0; + while (curInst) { - if (curInst->stat != NSFW_INST_STAT_DONE) + if (curInst->stat != NSFW_INST_STAT_DONE) { - if (0 == unDoneNum) + if (0 == unDoneNum) { - NSFW_LOGINF ("Here is the unInited modules:"); + NSFW_LOGINF("Here is the unInited modules:"); } - unDoneNum++; - nstack_framework_printInstanceInfo (curInst); + unDoneNum++; + nstack_framework_print_instance_info(curInst); } - curInst = curInst->next; + curInst = curInst->next; } - if (0 == unDoneNum) - NSFW_LOGINF ("All modules are inited"); + if (0 == unDoneNum) + NSFW_LOGINF("All modules are inited"); } /** * @Function nstack_framework_init - * @Description This function will do framework initial work, it will invoke all initial functions - * registered using macro NSFW_MODULE_INIT before + * @Description This function will do framework initial work, it will involk all initial functions + * registed using macro NSFW_MODULE_INIT before * @param none * @return 0 on success, -1 on error */ -int -nstack_framework_init (void) +int nstack_framework_init(void) { - int ret = -1; - if (nsfw_module_getManager ()->done) + int ret = -1; + if (nsfw_module_get_manager()->done) { - goto init_finished; + goto init_finished; } - if (pthread_mutex_lock (&nsfw_module_getManager ()->initMutex)) + if (pthread_mutex_lock(&nsfw_module_get_manager()->initMutex)) { - return -1; + return -1; } - if (nsfw_module_getManager ()->done) + if (nsfw_module_get_manager()->done) { - goto done; + goto done; } - ret = nstack_framework_initChild_unsafe (NULL); + ret = nstack_framework_init_child_unsafe(NULL); - if (0 == ret) + if (0 == ret) { - nsfw_module_getManager ()->done = 1; + nsfw_module_get_manager()->done = 1; } - else + else { - nsfw_module_getManager ()->done = -1; + nsfw_module_get_manager()->done = -1; } - // Going to print done modules and undone modules - nstack_framework_printInitialResult (); + // Going to print done modules and undone modules + nstack_framework_print_initial_result(); -done: - if (pthread_mutex_unlock (&nsfw_module_getManager ()->initMutex)) + done: + if (pthread_mutex_unlock(&nsfw_module_get_manager()->initMutex)) { - return -1; + return -1; } -init_finished: - ret = nsfw_module_getManager ()->done == 1 ? 0 : -1; - return ret; + init_finished: + ret = nsfw_module_get_manager()->done == 1 ? 0 : -1; + return ret; } /** - * @Function nstack_framework_setModuleParam + * @Function nstack_framework_set_module_param * @Description This function set parameter of module initial function parameter * @param module - name of module * @param param - parameter to set * @return 0 on success, -1 on error */ -int -nstack_framework_setModuleParam (char *module, void *param) +int nstack_framework_set_module_param(char *module, void *param) { - nsfw_module_instance_t *inst = nsfw_module_getModuleByName (module); - if (!inst) - return -1; + nsfw_module_instance_t *inst = nsfw_module_get_module_by_name(module); + if (!inst) + return -1; - inst->param = param; - return 0; + inst->param = param; + return 0; } #ifdef __cplusplus diff --git a/src/framework/init/fw_module.c b/src/framework/init/fw_module.c index 1f22ecb..66c06ee 100644 --- a/src/framework/init/fw_module.c +++ b/src/framework/init/fw_module.c @@ -20,6 +20,7 @@ #include <stdlib.h> #include "nstack_securec.h" #include "fw_module.h" +#include "nsfw_init_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -27,8 +28,8 @@ extern "C"{ /* *INDENT-ON* */ #endif /* __cplusplus */ -COMPAT_PROTECT (NSFW_MODULE_INSTANCE_POOL_SIZE, 64); -COMPAT_PROTECT (NSFW_MODULE_DEPENDS_POOL_SIZE, 128); +COMPAT_PROTECT_RETURN(NSFW_MODULE_INSTANCE_POOL_SIZE, 64); +COMPAT_PROTECT_RETURN(NSFW_MODULE_DEPENDS_POOL_SIZE, 128); nsfw_module_instance_pool_t g_nsfw_module_inst_pool; nsfw_module_depends_pool_t g_nsfw_module_deps_pool; @@ -37,291 +38,280 @@ nsfw_module_depends_pool_t g_nsfw_module_deps_pool; * WARNING!!!: * This function is only used in constructor progress. Multi-thread concurrent is not supported! */ -NSTACK_STATIC nsfw_module_instance_t * -nsfw_module_malloc_instance () +NSTACK_STATIC nsfw_module_instance_t *nsfw_module_malloc_instance() { - if (g_nsfw_module_inst_pool.last_idx >= NSFW_MODULE_INSTANCE_POOL_SIZE) + if (g_nsfw_module_inst_pool.last_idx >= NSFW_MODULE_INSTANCE_POOL_SIZE) { - return NULL; + return NULL; } - return - &g_nsfw_module_inst_pool.module_instance_pool[g_nsfw_module_inst_pool. - last_idx++]; + return + &g_nsfw_module_inst_pool.module_instance_pool[g_nsfw_module_inst_pool. + last_idx++]; } /* * WARNING!!!: * This function is only used in constructor progress. Multi-thread concurrent is not supported! */ -NSTACK_STATIC nsfw_module_depends_t * -nsfw_module_malloc_depends () +NSTACK_STATIC nsfw_module_depends_t *nsfw_module_malloc_depends() { - if (g_nsfw_module_deps_pool.last_idx >= NSFW_MODULE_DEPENDS_POOL_SIZE) + if (g_nsfw_module_deps_pool.last_idx >= NSFW_MODULE_DEPENDS_POOL_SIZE) { - return NULL; + return NULL; } - return - &g_nsfw_module_deps_pool.module_depends_pool[g_nsfw_module_deps_pool. - last_idx++]; + return + &g_nsfw_module_deps_pool.module_depends_pool[g_nsfw_module_deps_pool. + last_idx++]; } -NSTACK_STATIC void -nsfw_module_setChildInstance (nsfw_module_instance_t * - father, nsfw_module_instance_t * child) +/*Change module malloc to pool array End*/ + +NSTACK_STATIC void nsfw_module_set_child_instance(nsfw_module_instance_t * + father, + nsfw_module_instance_t * + child) { - if (NULL == father || NULL == child) - return; - child->father = father; + if (NULL == father || NULL == child) + return; + child->father = father; } -nsfw_module_depends_t * -nsfw_module_create_depends (char *name) +nsfw_module_depends_t *nsfw_module_create_depends(char *name) { - if (NULL == name) - return NULL; - - /*Change module malloc to pool array */ - nsfw_module_depends_t *dep = nsfw_module_malloc_depends (); - - if (NULL == dep) - return NULL; - - if (EOK != - MEMSET_S (dep, sizeof (nsfw_module_depends_t), 0, - sizeof (nsfw_module_depends_t))) + if (NULL == name) + return NULL; + /*Change module malloc to pool array */ + nsfw_module_depends_t *dep = nsfw_module_malloc_depends(); + if (NULL == dep) + return NULL; + + if (EOK != + memset_s(dep, sizeof(nsfw_module_depends_t), 0, + sizeof(nsfw_module_depends_t))) { - goto fail; + goto fail; } - /*change destMax from nameSize - 1 to sizeof(dep->name) */ - if (EOK != STRCPY_S (dep->name, sizeof (dep->name), name)) + /*change destMax from nameSize - 1 to sizeof(dep->name) */ + if (EOK != strcpy_s(dep->name, sizeof(dep->name), name)) { - goto fail; + goto fail; } - dep->isReady = 0; + dep->isReady = 0; - return dep; + return dep; -fail: - // NOTE: if dep is not null, we do not free it and just leave it there. - return NULL; + fail: + // NOTE: if dep is not null, we do not free it and just leave it there. + return NULL; } -nsfw_module_instance_t * -nsfw_module_create_instance (void) +nsfw_module_instance_t *nsfw_module_create_instance(void) { - /*Change module malloc to pool array */ - nsfw_module_instance_t *inst = nsfw_module_malloc_instance (); - if (NULL == inst) - return NULL; - - if (EOK != - MEMSET_S (inst, sizeof (nsfw_module_instance_t), 0, - sizeof (nsfw_module_instance_t))) + /*Change module malloc to pool array */ + nsfw_module_instance_t *inst = nsfw_module_malloc_instance(); + if (NULL == inst) + return NULL; + + if (EOK != + memset_s(inst, sizeof(nsfw_module_instance_t), 0, + sizeof(nsfw_module_instance_t))) { - // NOTE: if inst is not null, we do not free it and just leave it there. - return NULL; + // NOTE: if inst is not null, we do not free it and just leave it there. + return NULL; } - inst->stat = NSFW_INST_STAT_CHECKING; - return inst; + inst->stat = NSFW_INST_STAT_CHECKING; + return inst; } -void -nsfw_module_set_instance_name (nsfw_module_instance_t * inst, char *name) +void nsfw_module_set_instance_name(nsfw_module_instance_t * inst, char *name) { - if (NULL == inst || NULL == name || inst->name[0] != '\0') + if (NULL == inst || NULL == name || inst->name[0] != '\0') { - return; + return; } - /*change destMax from nameSize - 1 to sizeof(inst->name) */ - if (EOK != STRCPY_S (inst->name, sizeof (inst->name), name)) + /*change destMax from nameSize - 1 to sizeof(inst->name) */ + if (EOK != strcpy_s(inst->name, sizeof(inst->name), name)) { - return; + return; } - // Now we need to search if it's any instance's father - nsfw_module_instance_t *curInst = nsfw_module_getManager ()->inst; - while (curInst) + // Now we need to search if it's any instance's father + nsfw_module_instance_t *curInst = nsfw_module_get_manager()->inst; + while (curInst) { - if (curInst == inst) - goto next_loop; + if (curInst == inst) + goto next_loop; - if (0 == strcmp (curInst->fatherName, inst->name) - && NULL == curInst->father) + if (0 == strcmp(curInst->fatherName, inst->name) + && NULL == curInst->father) { - nsfw_module_setChildInstance (inst, curInst); + nsfw_module_set_child_instance(inst, curInst); } - next_loop: - curInst = curInst->next; + next_loop: /*usually use like this and no "space" */ + curInst = curInst->next; } - return; + return; } -void -nsfw_module_set_instance_father (nsfw_module_instance_t * inst, - char *fatherName) +void nsfw_module_set_instance_father(nsfw_module_instance_t * inst, + char *fatherName) { - if (NULL == inst || NULL == fatherName) + if (NULL == inst || NULL == fatherName) { - return; + return; } - if (EOK != - STRCPY_S (inst->fatherName, sizeof (inst->fatherName), fatherName)) + if (EOK != + strcpy_s(inst->fatherName, sizeof(inst->fatherName), fatherName)) { - return; + return; } - nsfw_module_instance_t *fatherInst = - nsfw_module_getModuleByName (fatherName); - if (fatherInst) + nsfw_module_instance_t *fatherInst = + nsfw_module_get_module_by_name(fatherName); + if (fatherInst) { - nsfw_module_setChildInstance (fatherInst, inst); + nsfw_module_set_child_instance(fatherInst, inst); } - return; + return; } -void -nsfw_module_set_instance_priority (nsfw_module_instance_t * inst, - int priority) +void nsfw_module_set_instance_priority(nsfw_module_instance_t * inst, + int priority) { - if (NULL == inst) - return; - inst->priority = priority; + if (NULL == inst) + return; + inst->priority = priority; - nsfw_module_del_instance (inst); - nsfw_module_add_instance (inst); - return; + nsfw_module_del_instance(inst); + nsfw_module_add_instance(inst); + return; } -void -nsfw_module_set_instance_initfn (nsfw_module_instance_t * inst, - nsfw_module_init_fn fn) +void nsfw_module_set_instance_initfn(nsfw_module_instance_t * inst, + nsfw_module_init_fn fn) { - if (NULL == inst) + if (NULL == inst) + return; + inst->fnInit = fn; return; - inst->fnInit = fn; - return; } -void -nsfw_module_set_instance_depends (nsfw_module_instance_t * inst, char *name) +void nsfw_module_set_instance_depends(nsfw_module_instance_t * inst, + char *name) { - if (NULL == inst || name == NULL) - return; + if (NULL == inst || name == NULL) + return; - // Check if depends already set - nsfw_module_depends_t *dep = inst->depends; - while (dep) + // Check if depends already set + nsfw_module_depends_t *dep = inst->depends; + while (dep) { - if (0 == strcmp (dep->name, name)) - return; - dep = dep->next; + if (0 == strcmp(dep->name, name)) + return; + dep = dep->next; } - dep = nsfw_module_create_depends (name); - if (NULL == dep) - return; + dep = nsfw_module_create_depends(name); + if (NULL == dep) + return; - if (NULL == inst->depends) - inst->depends = dep; - else - inst->depends->next = dep; + if (NULL == inst->depends) + inst->depends = dep; + else + inst->depends->next = dep; } -/* *INDENT-OFF* */ -nsfw_module_manager_t g_nsfw_module_manager = {.inst = NULL, .initMutex = - PTHREAD_MUTEX_INITIALIZER, .done = 0}; -/* *INDENT-ON* */ +nsfw_module_manager_t g_nsfw_module_manager = {.inst = NULL,.initMutex = + PTHREAD_MUTEX_INITIALIZER,.done = 0 +}; -void -nsfw_module_add_instance (nsfw_module_instance_t * inst) +void nsfw_module_add_instance(nsfw_module_instance_t * inst) { - nsfw_module_instance_t *curInst = nsfw_module_getManager ()->inst; + nsfw_module_instance_t *curInst = nsfw_module_get_manager()->inst; - if (NULL == curInst || curInst->priority > inst->priority) + if (NULL == curInst || curInst->priority > inst->priority) { - inst->next = curInst; - nsfw_module_getManager ()->inst = inst; + inst->next = curInst; + nsfw_module_get_manager()->inst = inst; } - else + else { - while (curInst->next && curInst->next->priority <= inst->priority) + while (curInst->next && curInst->next->priority <= inst->priority) { - curInst = curInst->next; + curInst = curInst->next; } - inst->next = curInst->next; - curInst->next = inst; + inst->next = curInst->next; + curInst->next = inst; } } -void -nsfw_module_del_instance (nsfw_module_instance_t * inst) +void nsfw_module_del_instance(nsfw_module_instance_t * inst) { - if (nsfw_module_getManager ()->inst == inst) + if (nsfw_module_get_manager()->inst == inst) { - nsfw_module_getManager ()->inst = inst->next; - return; + nsfw_module_get_manager()->inst = inst->next; + return; } - nsfw_module_instance_t *curInst = nsfw_module_getManager ()->inst; + nsfw_module_instance_t *curInst = nsfw_module_get_manager()->inst; - while (curInst->next && curInst->next != inst) - curInst = curInst->next; + while (curInst->next && curInst->next != inst) + curInst = curInst->next; - if (!curInst->next) - return; - curInst->next = inst->next; + if (!curInst->next) + return; + curInst->next = inst->next; } -nsfw_module_instance_t * -nsfw_module_getModuleByName (char *name) +nsfw_module_instance_t *nsfw_module_get_module_by_name(char *name) { - if (NULL == name) - return NULL; + if (NULL == name) + return NULL; - nsfw_module_instance_t *curInst = nsfw_module_getManager ()->inst; - while (curInst) + nsfw_module_instance_t *curInst = nsfw_module_get_manager()->inst; + while (curInst) { - if (0 == strcmp (curInst->name, name)) + if (0 == strcmp(curInst->name, name)) { - return curInst; + return curInst; } - curInst = curInst->next; + curInst = curInst->next; } - return NULL; + return NULL; } -int -nsfw_module_addDoneNode (nsfw_module_instance_t * inst) +int nsfw_module_add_done_node(nsfw_module_instance_t * inst) { - nsfw_module_doneNode_t *node = - (nsfw_module_doneNode_t *) malloc (sizeof (nsfw_module_doneNode_t)); - if (NULL == node) - return -1; - node->inst = inst; - node->next = NULL; - - nsfw_module_manager_t *manager = nsfw_module_getManager (); - if (NULL == manager->doneHead) + nsfw_module_done_node_t *node = (nsfw_module_done_node_t *) malloc(sizeof(nsfw_module_done_node_t)); /*malloc can use */ + if (NULL == node) + { + return -1; + } + node->inst = inst; + node->next = NULL; + + nsfw_module_manager_t *manager = nsfw_module_get_manager(); + if (NULL == manager->doneHead) { - manager->doneHead = node; + manager->doneHead = node; } - else + else { - nsfw_module_doneNode_t *tail = manager->doneHead; - while (tail->next) + nsfw_module_done_node_t *tail = manager->doneHead; + while (tail->next) { - tail = tail->next; + tail = tail->next; } - tail->next = node; + tail->next = node; } - return 0; + return 0; } #ifdef __cplusplus diff --git a/src/framework/init/fw_module.h b/src/framework/init/fw_module.h index 0818aed..a3da4f4 100644 --- a/src/framework/init/fw_module.h +++ b/src/framework/init/fw_module.h @@ -17,15 +17,13 @@ #ifndef _FW_MODULE #define _FW_MODULE #include <pthread.h> - +#include "nsfw_init_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ extern "C"{ /* *INDENT-ON* */ #endif /* _cplusplus */ -#include "nsfw_init.h" - /* Unique name declare */ #define NSFW__STRINGIFY(x) #x #define NSFW_STRINGIFY(x) NSFW__STRINGIFY(x) @@ -37,43 +35,45 @@ extern "C"{ #define NSFW_MODULE_INITFN(_fn) \ static int _fn(void* param) -extern nsfw_module_depends_t *nsfw_module_create_depends (char *name); + +#define NSFW_DEPENDS_SIZE 8 #define NSFW_MODULE_SET_STATE(inst, state) ((inst)->stat = (state)) -typedef struct _nsfw_module_doneNode +/*Change module malloc to pool array*/ +#define NSFW_MODULE_INSTANCE_POOL_SIZE 64 +#define NSFW_MODULE_DEPENDS_POOL_SIZE 128 + +typedef struct _nsfw_module_done_node { - nsfw_module_instance_t *inst; - struct _nsfw_module_doneNode *next; -} nsfw_module_doneNode_t; + nsfw_module_instance_t *inst; + struct _nsfw_module_done_node *next; +} nsfw_module_done_node_t; typedef struct _nsfw_module_manager { - pthread_mutex_t initMutex; - int done; // 0 - not finished, 1 - finished, -1 - error - nsfw_module_instance_t *inst; - nsfw_module_doneNode_t *doneHead; + pthread_mutex_t initMutex; + int done; // 0 - not finished, 1 - finished, -1 - error + nsfw_module_instance_t *inst; + nsfw_module_done_node_t *doneHead; } nsfw_module_manager_t; -extern int nsfw_module_addDoneNode (nsfw_module_instance_t * inst); +extern int nsfw_module_add_done_node(nsfw_module_instance_t * inst); extern nsfw_module_manager_t g_nsfw_module_manager; -#define nsfw_module_getManager() (&g_nsfw_module_manager) - -#define NSFW_MODULE_INSTANCE_POOL_SIZE 64 -#define NSFW_MODULE_DEPENDS_POOL_SIZE 128 +#define nsfw_module_get_manager() (&g_nsfw_module_manager) typedef struct _nsfw_module_instance_pool { - int last_idx; - nsfw_module_instance_t - module_instance_pool[NSFW_MODULE_INSTANCE_POOL_SIZE]; + int last_idx; + nsfw_module_instance_t + module_instance_pool[NSFW_MODULE_INSTANCE_POOL_SIZE]; } nsfw_module_instance_pool_t; typedef struct _nsfw_module_depends_pool { - int last_idx; - nsfw_module_depends_t module_depends_pool[NSFW_MODULE_DEPENDS_POOL_SIZE]; + int last_idx; + nsfw_module_depends_t module_depends_pool[NSFW_MODULE_DEPENDS_POOL_SIZE]; } nsfw_module_depends_pool_t; #ifdef __cplusplus diff --git a/src/framework/ipc/mgr_com/mgr_com.c b/src/framework/ipc/mgr_com/mgr_com.c index a2998fa..d09f1d5 100644 --- a/src/framework/ipc/mgr_com/mgr_com.c +++ b/src/framework/ipc/mgr_com/mgr_com.c @@ -20,8 +20,7 @@ #include "types.h" #include "nstack_securec.h" -#include "nsfw_init.h" -#include "common_mem_api.h" +#include "nsfw_init_api.h" #include "nsfw_mgr_com_api.h" #include "mgr_com.h" @@ -32,13 +31,12 @@ #include <stddef.h> #include <sys/epoll.h> #include <fcntl.h> -#include <sys/stat.h> #include "nsfw_maintain_api.h" #include "nsfw_ps_api.h" #include "nsfw_fd_timer_api.h" -#include "common_func.h" +#include "nsfw_maintain_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -46,49 +44,50 @@ extern "C"{ /* *INDENT-ON* */ #endif /* __cplusplus */ +nsfw_mgr_msg_fun g_mgr_fun[MGR_MSG_MAX][NSFW_MGRCOM_MAX_PROC_FUN]; /* *INDENT-OFF* */ +/* nstackMaster can't start daemon-stack successfully, + because daemon-stack can't successfully recv MGR_MSG_INIT_NTY_RSP */ +nsfw_mgr_init_cfg g_mgr_com_cfg = +{ + .msg_size = MGR_COM_MSG_COUNT_DEF, + .max_recv_timeout = MGR_COM_RECV_TIMEOUT_DEF, + .max_recv_drop_msg = MGR_COM_MAX_DROP_MSG_DEF, +}; -/* *INDENT-OFF* */ -nsfw_mgr_msg_fun g_mgr_fun[MGR_MSG_MAX][NSFW_MGRCOM_MAX_PROC_FUN]; -nsfw_mgr_init_cfg g_mgr_com_cfg; -nsfw_mgr_sock_map g_mgr_socket_map = {{0}, NULL}; +nsfw_mgr_sock_map g_mgr_sockt_map = {{0}, NULL}; nsfw_mgrcom_stat g_mgr_stat; -nsfw_mgrcom_proc g_ep_proc = { 0 }; -/* *INDENT-ON* */ - +nsfw_mgrcom_proc g_ep_proc = {0}; u32 g_mgr_sockfdmax = NSFW_MGRCOM_MAX_SOCKET; + char g_proc_info[NSFW_PROC_MAX][NSTACK_MAX_PROC_NAME_LEN] = { - "", "nStackMain", "nStackMaster", "nStackLib", "nStackTools", "nStackCtrl", - "", "", "", "", "", "", "", "", "", "" + "" + ,"nStackMain" + ,"nStackMaster" + ,"nStackLib" + ,"nStackCtrl" + ,"nStackTools" + ,"","","","","" + ,"","","","","" }; - /* *INDENT-ON* */ -int g_thread_policy = 0; -int g_thread_pri = 0; +char *g_home_direct = NULL; -void -nsfw_com_attr_set (int policy, int pri) +char *nsfw_get_proc_name(u8 proc_type) { - g_thread_policy = policy; - g_thread_pri = pri; -} - -char * -nsfw_get_proc_name (u8 proc_type) -{ - if (proc_type >= NSFW_PROC_MAX || NSFW_PROC_NULL == proc_type) + if (proc_type >= NSFW_PROC_MAX || NSFW_PROC_NULL == proc_type) { - return NULL; + return NULL; } - return g_proc_info[proc_type]; + return g_proc_info[proc_type]; } /***************************************************************************** * Prototype : nsfw_mgr_reg_msg_fun -* Description : reg the callback function when receive new message +* Description : reg the callback funciton when receive new message * Input : u16 msg_type * nsfw_mgr_msg_fun fun * Output : None @@ -96,29 +95,29 @@ nsfw_get_proc_name (u8 proc_type) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_reg_msg_fun (u16 msg_type, nsfw_mgr_msg_fun fun) +u8 nsfw_mgr_reg_msg_fun(u16 msg_type, nsfw_mgr_msg_fun fun) { - u32 i; - if (MGR_MSG_MAX <= msg_type) + u32 i; + if (MGR_MSG_MAX <= msg_type) { - NSFW_LOGERR ("reg mgr_msg]msg_type=%u,fun=%p", msg_type, fun); - return FALSE; + NSFW_LOGERR("reg mgr_msg]msg_type=%u,fun=%p", msg_type, fun); + return FALSE; } - for (i = 0; i < NSFW_MGRCOM_MAX_PROC_FUN; i++) + for (i = 0; i < NSFW_MGRCOM_MAX_PROC_FUN; i++) { - if (NULL == g_mgr_fun[msg_type][i]) + if (NULL == g_mgr_fun[msg_type][i]) { - g_mgr_fun[msg_type][i] = fun; - NSFW_LOGINF ("reg mgr_msg fun suc]msg_type=%u,fun=%p", msg_type, - fun); - return TRUE; + /*TODO should use cas */ + g_mgr_fun[msg_type][i] = fun; + NSFW_LOGINF("reg mgr_msg fun suc]msg_type=%u,fun=%p", msg_type, + fun); + return TRUE; } } - NSFW_LOGERR ("reg mgr_msg type full]msg_type=%u,fun=%p", msg_type, fun); - return FALSE; + NSFW_LOGERR("reg mgr_msg type full]msg_type=%u,fun=%p", msg_type, fun); + return FALSE; } /***************************************************************************** @@ -130,10 +129,9 @@ nsfw_mgr_reg_msg_fun (u16 msg_type, nsfw_mgr_msg_fun fun) * Calls : * Called By : *****************************************************************************/ -nsfw_mgr_msg * -nsfw_mgr_null_rspmsg_alloc () +nsfw_mgr_msg *nsfw_mgr_null_rspmsg_alloc() { - return nsfw_mgr_msg_alloc (MGR_MSG_NULL, NSFW_PROC_NULL); + return nsfw_mgr_msg_alloc(MGR_MSG_NULL, NSFW_PROC_NULL); } /***************************************************************************** @@ -146,86 +144,75 @@ nsfw_mgr_null_rspmsg_alloc () * Calls : * Called By : *****************************************************************************/ -nsfw_mgr_msg * -nsfw_mgr_msg_alloc (u16 msg_type, u8 dst_proc_type) +nsfw_mgr_msg *nsfw_mgr_msg_alloc(u16 msg_type, u8 dst_proc_type) { - nsfw_mgr_msg *p_msg = NULL; - u8 from_mem_flag = FALSE; - u32 alloc_len = sizeof (nsfw_mgr_msg); + nsfw_mgr_msg *p_msg = NULL; + u8 from_mem_flag = FALSE; + u32 alloc_len = sizeof(nsfw_mgr_msg); - if (MGR_MSG_LAG_QRY_RSP_BEGIN <= msg_type) + if (MGR_MSG_LAG_QRY_RSP_BEGIN <= msg_type + || MGR_MSG_SPLNET_REQ == msg_type) { - from_mem_flag = TRUE; - alloc_len = NSFW_MGR_LARGE_MSG_LEN; + from_mem_flag = TRUE; + alloc_len = NSFW_MGR_LARGE_MSG_LEN; } - if ((NULL == g_mgr_com_cfg.msg_pool) - && (MGR_MSG_INIT_NTY_REQ == msg_type - || MGR_MSG_INIT_NTY_RSP == msg_type)) + if ((NULL == g_mgr_com_cfg.msg_pool) + && (MGR_MSG_INIT_NTY_REQ == msg_type + || MGR_MSG_INIT_NTY_RSP == msg_type)) { - from_mem_flag = TRUE; + from_mem_flag = TRUE; } - if (FALSE == from_mem_flag) + if (FALSE == from_mem_flag) { - if (0 == - nsfw_mem_ring_dequeue (g_mgr_com_cfg.msg_pool, (void *) &p_msg)) + if (0 == + nsfw_mem_ring_dequeue(g_mgr_com_cfg.msg_pool, (void *) &p_msg)) { - NSFW_LOGERR ("alloc msg full]type=%u,dst=%u", msg_type, - dst_proc_type); - return NULL; + NSFW_LOGERR("alloc msg full]type=%u,dst=%u", msg_type, + dst_proc_type); + return NULL; } - alloc_len = sizeof (nsfw_mgr_msg); + alloc_len = sizeof(nsfw_mgr_msg); } - else + else { - p_msg = (nsfw_mgr_msg *) malloc (alloc_len); + p_msg = (nsfw_mgr_msg *) malloc(alloc_len); /*malloc() can be used */ } - if (NULL == p_msg) + if (NULL == p_msg) { - NSFW_LOGERR ("alloc msg nul]type=%u,dst=%u", msg_type, dst_proc_type); - return NULL; + NSFW_LOGERR("alloc msg nul]type=%u,dst=%u", msg_type, dst_proc_type); + return NULL; } - if (EOK != MEMSET_S (p_msg, alloc_len, 0, alloc_len)) + if (EOK != memset_s(p_msg, alloc_len, 0, alloc_len)) { - p_msg->from_mem = from_mem_flag; - nsfw_mgr_msg_free (p_msg); - NSFW_LOGERR ("alloc msg MEMSET_S failed]type=%u,dst=%u", msg_type, - dst_proc_type); - return NULL; + p_msg->from_mem = from_mem_flag; + + nsfw_mgr_msg_free(p_msg); + NSFW_LOGERR("alloc msg memset_s failed]type=%u,dst=%u", msg_type, + dst_proc_type); + return NULL; } - p_msg->from_mem = from_mem_flag; + p_msg->from_mem = from_mem_flag; - if (msg_type < MGR_MSG_RSP_BASE && msg_type > 0) + if (msg_type < MGR_MSG_RSP_BASE && msg_type > 0) { - p_msg->seq = common_mem_atomic32_add_return (&g_mgr_com_cfg.cur_idx, 1); + p_msg->seq = dmm_atomic_add_return(&g_mgr_com_cfg.cur_idx, 1); } - p_msg->from_mem = from_mem_flag; - p_msg->msg_type = msg_type; - p_msg->src_pid = get_sys_pid (); - p_msg->src_proc_type = g_mgr_com_cfg.proc_type; - p_msg->msg_len = alloc_len; - p_msg->dst_proc_type = dst_proc_type; - p_msg->alloc_flag = TRUE; - p_msg->more_msg_flag = 0; + p_msg->from_mem = from_mem_flag; + p_msg->msg_type = msg_type; + p_msg->src_pid = get_sys_pid(); + p_msg->src_proc_type = g_mgr_com_cfg.proc_type; + p_msg->msg_len = alloc_len; + p_msg->dst_proc_type = dst_proc_type; + p_msg->alloc_flag = TRUE; + p_msg->more_msg_flag = 0; - g_mgr_stat.msg_alloc++; - return p_msg; -} - -static inline void -lint_lock_1 () -{ - return; -} - -static inline void -lint_unlock_1 () -{ - return; + g_mgr_stat.msg_alloc++; + return p_msg; } /***************************************************************************** @@ -237,27 +224,26 @@ lint_unlock_1 () * Calls : * Called By : *****************************************************************************/ -nsfw_mgr_msg * -nsfw_mgr_rsp_msg_alloc (nsfw_mgr_msg * req_msg) +nsfw_mgr_msg *nsfw_mgr_rsp_msg_alloc(nsfw_mgr_msg * req_msg) { - nsfw_mgr_msg *p_msg = NULL; - if (NULL == req_msg) + nsfw_mgr_msg *p_msg = NULL; + if (NULL == req_msg) { - NSFW_LOGERR ("req msg nul!"); - return NULL; + NSFW_LOGERR("req msg nul!"); + return NULL; } - p_msg = - nsfw_mgr_msg_alloc (req_msg->msg_type + MGR_MSG_RSP_BASE, - req_msg->src_proc_type); - if (NULL == p_msg) + p_msg = + nsfw_mgr_msg_alloc(req_msg->msg_type + MGR_MSG_RSP_BASE, + req_msg->src_proc_type); + if (NULL == p_msg) { - return NULL; + return NULL; } - p_msg->dst_pid = req_msg->src_pid; - p_msg->seq = req_msg->seq; - return p_msg; + p_msg->dst_pid = req_msg->src_pid; + p_msg->seq = req_msg->seq; + return p_msg; } /***************************************************************************** @@ -269,44 +255,87 @@ nsfw_mgr_rsp_msg_alloc (nsfw_mgr_msg * req_msg) * Calls : * Called By : *****************************************************************************/ -void -nsfw_mgr_msg_free (nsfw_mgr_msg * msg) +void nsfw_mgr_msg_free(nsfw_mgr_msg * msg) { - if (NULL == msg) + + if (NULL == msg) { - return; + return; } - if (FALSE == msg->alloc_flag) + if (FALSE == msg->alloc_flag) + { + NSFW_LOGERR("msg refree]msg=%p, type=%u", msg, msg->msg_type); + return; + } + + msg->alloc_flag = FALSE; + + if (TRUE == msg->from_mem) + { + /*remove msg->msg_type judgement */ + free(msg); /*free() can be used */ + g_mgr_stat.msg_free++; + return; + } + else { - NSFW_LOGERR ("msg refree]msg=%p, type=%u", msg, msg->msg_type); - return; + if (0 == nsfw_mem_ring_enqueue(g_mgr_com_cfg.msg_pool, msg)) + { + NSFW_LOGERR("msg free failed pool full]msg=%p, type=%u", msg, + msg->msg_type); + return; + } + g_mgr_stat.msg_free++; } - msg->alloc_flag = FALSE; + return; +} - if (TRUE == msg->from_mem) +/***************************************************************************** +* Prototype : get_home_path +* Description : get the env "HOME" path info +* Input : +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +const char *get_home_path() +{ + //a extern global var, if not null ,just return it. + if (g_home_direct) { - if ((MGR_MSG_INIT_NTY_REQ == msg->msg_type - || MGR_MSG_INIT_NTY_RSP == msg->msg_type) - || (MGR_MSG_LAG_QRY_RSP_BEGIN <= msg->msg_type)) + return g_home_direct; + } + + //just need do one time. + const char *home_dir = getenv("HOME"); /*getenv() can be used */ + if (getuid() != 0 && home_dir != NULL) + { + g_home_direct = realpath(home_dir, NULL); + if (!g_home_direct) { - free (msg); - g_mgr_stat.msg_free++; - return; + NSFW_LOGWAR("realpath fail]home_dir=%s,errno=%d", home_dir, + errno); + return NULL; } - NSFW_LOGERR ("msg err free]type=%u", msg->msg_type); } - if (0 == nsfw_mem_ring_enqueue (g_mgr_com_cfg.msg_pool, msg)) + //check if the path is valid + if (check_log_dir_valid(g_home_direct) < 0) { - NSFW_LOGERR ("msg free failed pool full]msg=%p, type=%u", msg, - msg->msg_type); - return; + NSFW_LOGWAR("path check valid fail, free it]home_direct=%s", + g_home_direct); + if (g_home_direct) + { + free(g_home_direct); + g_home_direct = NULL; + } + return NULL; } - g_mgr_stat.msg_free++; - return; + return g_home_direct; } /***************************************************************************** @@ -318,82 +347,99 @@ nsfw_mgr_msg_free (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_mgr_get_listen_socket () +i32 nsfw_mgr_get_listen_socket() { - i32 fd, len, retVal; - struct sockaddr_un un; - char name[NSFW_MGRCOM_PATH_LEN] = { 0 }; + i32 fd, len; + struct sockaddr_un un; - if ((fd = nsfw_base_socket (AF_UNIX, SOCK_STREAM, 0)) < 0) + if ((fd = nsfw_base_socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - NSFW_LOGERR ("create sock failed!"); - return -1; + NSFW_LOGERR("create sock failed!"); + return -1; } - retVal = STRCPY_S ((char *) name, sizeof (name), - (char *) g_mgr_com_cfg.domain_path); - if (EOK != retVal) + if (-1 == unlink((char *) g_mgr_com_cfg.domain_path)) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("module mgr get listen STRCPY_S failed! ret=%d", retVal); - return -1; + NSFW_LOGWAR("unlink failed]error=%d", errno); } - if (EOK != STRCAT_S (name, NSFW_MGRCOM_PATH_LEN, NSFW_MAIN_FILE)) + if (EOK != memset_s(&un, sizeof(un), 0, sizeof(un))) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("module mgr get listen STRCAT_S failed!"); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("create sock memset_s failed!] error=%d", errno); + return -1; } - if (-1 == unlink ((char *) name)) + un.sun_family = AF_UNIX; + int retVal = strcpy_s((char *) un.sun_path, sizeof(un.sun_path), + (char *) g_mgr_com_cfg.domain_path); + if (EOK != retVal) { - NSFW_LOGWAR ("unlink failed]error=%d", errno); + (void) nsfw_base_close(fd); + NSFW_LOGERR("create sock strcpy_s failed!] error=%d", errno); + return -1; } - if (EOK != MEMSET_S (&un, sizeof (un), 0, sizeof (un))) + + /* close on exec */ + int rc = nsfw_set_close_on_exec(fd); + if (rc == -1) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("create sock MEMSET_S failed!] error=%d", errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", fd, errno); + return -1; } - un.sun_family = AF_UNIX; - retVal = STRCPY_S ((char *) un.sun_path, sizeof (un.sun_path), - (char *) name); - if (EOK != retVal) + len = offsetof(struct sockaddr_un, sun_path) +strlen((char *) g_mgr_com_cfg.domain_path); /*strlen() can be used */ + + if (nsfw_base_bind(fd, (struct sockaddr *) &un, len) < 0) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("create sock STRCPY_S failed!] error=%d", errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("bind failed!]mgr_fd=%d,error=%d", fd, errno); + return -1; } - int rc = nsfw_set_close_on_exec (fd); - if (rc == -1) + if (nsfw_base_listen(fd, 10) < 0) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", fd, errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("listen failed!]mgr_fd=%d,error=%d", fd, errno); + return -1; } - len = offsetof (struct sockaddr_un, sun_path) +strlen ((char *) name); + NSFW_LOGINF("mgr com start with]mgr_fd=%d", fd); + return fd; +} - if (nsfw_base_bind (fd, (struct sockaddr *) &un, len) < 0) +/***************************************************************************** +* Prototype : nsfw_mgr_connect_with_retry +* Description : connect dst_socket, retry some times every 100ms +* Input : nsfw_mgr_msg* req_msg +* nsfw_mgr_msg* rsp_msg +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mgr_connect_with_retry(i32 fd, struct sockaddr * un, i32 len, + i32 interval_ms, i32 retry_times) +{ + if (nsfw_base_connect(fd, un, len) == 0) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("bind failed!]mgr_fd=%d,error=%d", fd, errno); - return -1; + return 0; } - - if (nsfw_base_listen (fd, 10) < 0) + while (retry_times > 0) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("listen failed!]mgr_fd=%d,error=%d", fd, errno); - return -1; + sys_sleep_ns(0, interval_ms * 1000 * 1000); + --retry_times; + if (nsfw_base_connect(fd, un, len) == 0) + { + return 0; + } + else if (errno != ECONNRESET && errno != ECONNREFUSED) /* Retry is for Master upgrade only */ + { + return -1; + } } - - NSFW_LOGINF ("mgr com start with]mgr_fd=%d", fd); - return fd; + return -1; } /***************************************************************************** @@ -406,115 +452,138 @@ nsfw_mgr_get_listen_socket () * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_mgr_get_connect_socket (u8 proc_type, u32 host_pid) +i32 nsfw_mgr_get_connect_socket(u8 proc_type, u32 host_pid) { - i32 fd, len; - char *name; - struct sockaddr_un un; - const char *directory = NSFW_DOMAIN_DIR; - const char *home_dir = getenv ("HOME"); + i32 fd = -1; + i32 len = 0; + char *name; + struct sockaddr_un un; + i32 retry_times = 0; + i32 interval_ms = 50; + const char *directory = NSFW_DOMAIN_DIR; + const char *home_dir = get_home_path(); + if (home_dir) + { + directory = home_dir; + } - if (getuid () != 0 && home_dir != NULL) - directory = home_dir; + switch (proc_type) + { + case NSFW_PROC_MAIN: + name = NSFW_MAIN_FILE; + break; + case NSFW_PROC_MASTER: + name = NSFW_MASTER_FILE; + retry_times = 10; + break; + case NSFW_PROC_ALARM: /* alarm */ + directory = "/tmp"; + name = NSFW_ALARM_FILE; + break; + default: + NSFW_LOGERR("get dst socket err]type=%u,pid=%u", proc_type, + host_pid); + return -1; + } - switch (proc_type) + if ((fd = nsfw_base_socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - case NSFW_PROC_MAIN: - name = NSFW_MAIN_FILE; - break; - case NSFW_PROC_ALARM: - directory = "/tmp"; - name = NSFW_ALARM_FILE; - break; - default: - NSFW_LOGERR ("get dst socket err]type=%u,pid=%u", proc_type, host_pid); - return -1; + NSFW_LOGERR("create socket err]type=%u,pid=%u,errno=%d", proc_type, + host_pid, errno); + return -1; } - if ((fd = nsfw_base_socket (AF_UNIX, SOCK_STREAM, 0)) < 0) + if (EOK != memset_s(&un, sizeof(un), 0, sizeof(un))) { - NSFW_LOGERR ("create socket err]type=%u,pid=%u,errno=%d", proc_type, - host_pid, errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("get dst socket err]mgr_fd=%d,type=%u,pid=%u", fd, + proc_type, host_pid); + return -1; } - if (EOK != MEMSET_S (&un, sizeof (un), 0, sizeof (un))) + struct timeval tv; + tv.tv_sec = MGR_COM_RECV_TIMEOUT; + tv.tv_usec = 0; + if (nsfw_base_setsockopt + (fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof tv)) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("get dst socket err]mgr_fd=%d,type=%u,pid=%u", fd, - proc_type, host_pid); - return -1; + NSFW_LOGERR + ("setsockopt socket err]mgr_fd=%d,type=%u,pid=%u,errno=%d", fd, + proc_type, host_pid, errno); + (void) nsfw_base_close(fd); + return -1; } - struct timeval tv; - tv.tv_sec = MGR_COM_RECV_TIMEOUT; - tv.tv_usec = 0; - if (nsfw_base_setsockopt - (fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof tv)) + tv.tv_sec = MGR_COM_SEND_TIMEOUT_DEF; + tv.tv_usec = 0; + if (nsfw_base_setsockopt + (fd, SOL_SOCKET, SO_SNDTIMEO, (char *) &tv, sizeof tv)) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("setsockopt socket err]mgr_fd=%d,type=%u,pid=%u", fd, - proc_type, host_pid); - return -1; + NSFW_LOGERR + ("setsockopt socket err]mgr_fd=%d,type=%u,pid=%u,errno=%d", fd, + proc_type, host_pid, errno); + (void) nsfw_base_close(fd); + return -1; } - int rc = nsfw_set_close_on_exec (fd); - if (rc == -1) + /* close on exec Add Begin */ + int rc = nsfw_set_close_on_exec(fd); + if (rc == -1) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", fd, errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", fd, errno); + return -1; } - int size, size_len; - size = MAX_RECV_BUF_DEF; - size_len = sizeof (size); - if (0 > - nsfw_base_setsockopt (fd, SOL_SOCKET, SO_RCVBUF, (void *) &size, - (socklen_t) size_len)) + int size, size_len; + size = MAX_RECV_BUF_DEF; + size_len = sizeof(size); + if (0 > + nsfw_base_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void *) &size, + (socklen_t) size_len)) { - NSFW_LOGERR ("set socket opt err!]error=%d", errno); + NSFW_LOGERR("set socket opt err]error=%d", errno); } - if (0 > - nsfw_base_setsockopt (fd, SOL_SOCKET, SO_SNDBUF, (void *) &size, - (socklen_t) size_len)) + if (0 > + nsfw_base_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *) &size, + (socklen_t) size_len)) { - NSFW_LOGERR ("set socket opt err!]error=%d", errno); + NSFW_LOGERR("set socket opt err]error=%d", errno); } - un.sun_family = AF_UNIX;; - int retVal = STRCPY_S ((char *) un.sun_path, sizeof (un.sun_path), - (char *) directory); - if (EOK != retVal) + un.sun_family = AF_UNIX;; + int retVal = strcpy_s((char *) un.sun_path, sizeof(un.sun_path), + (char *) directory); + if (EOK != retVal) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("create sock STRCPY_S failed!] error=%d", errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("create sock strcpy_s fail]error=%d", errno); + return -1; } - retVal = STRCAT_S (un.sun_path, sizeof (un.sun_path), name); - if (EOK != retVal) + retVal = strcat_s(un.sun_path, sizeof(un.sun_path), name); + if (EOK != retVal) { - (void) nsfw_base_close (fd); - NSFW_LOGERR ("create sock STRCAT_S failed!] error=%d", errno); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR("create sock strcat_s fail]error=%d", errno); + return -1; } - len = offsetof (struct sockaddr_un, sun_path) +strlen (un.sun_path); - if (nsfw_base_connect (fd, (struct sockaddr *) &un, len) < 0) + len = offsetof(struct sockaddr_un, sun_path) +strlen(un.sun_path); /*strlen() can be used */ + if (nsfw_mgr_connect_with_retry + (fd, (struct sockaddr *) &un, len, interval_ms, retry_times) < 0) { - (void) nsfw_base_close (fd); - NSFW_LOGERR - ("create socket err]mgr_fd=%d,type=%u,pid=%u,errno=%d,path=%s", fd, - proc_type, host_pid, errno, un.sun_path); - return -1; + (void) nsfw_base_close(fd); + NSFW_LOGERR + ("connect socket failed]mgr_fd=%d,type=%u,pid=%u,errno=%d,path=%s", + fd, proc_type, host_pid, errno, un.sun_path); + return -1; } - NSFW_LOGINF ("get dst socket]mgr_fd=%d,type=%u,pid=%u", fd, proc_type, - host_pid); - return (fd); + NSFW_LOGINF("get dst socket]mgr_fd=%d,type=%u,pid=%u", fd, proc_type, + host_pid); + return fd; } /***************************************************************************** @@ -528,33 +597,42 @@ nsfw_mgr_get_connect_socket (u8 proc_type, u32 host_pid) * Calls : * Called By : *****************************************************************************/ -NSTACK_STATIC inline u8 -nsfw_mgr_new_socket (i32 fd, u8 proc_type, u32 host_pid) +NSTACK_STATIC inline u8 nsfw_mgr_new_socket(i32 fd, u8 proc_type, + u32 host_pid) { - nsfw_mgr_sock_info *sock_info = NULL; - if (((i32) NSFW_MGR_FD_MAX <= fd) || (fd < 0) || (!g_mgr_socket_map.sock)) + nsfw_mgr_sock_info *sock_info = NULL; + if (((i32) NSFW_MGR_FD_MAX <= fd) || (fd < 0) || (!g_mgr_sockt_map.sock)) { - NSFW_LOGERR ("fd err]mgr_fd=%d, sock=%p", fd, g_mgr_socket_map.sock); - return FALSE; + NSFW_LOGERR("fd err]mgr_fd=%d, sock=%p", fd, g_mgr_sockt_map.sock); + return FALSE; } - sock_info = &g_mgr_socket_map.sock[fd]; - if (host_pid != sock_info->host_pid) + sock_info = &g_mgr_sockt_map.sock[fd]; + if (host_pid != sock_info->host_pid) { - NSFW_LOGDBG - ("update sock info]mgr_fd=%d,old_pid=%u,new_pid=%u,type=%u", fd, - sock_info->host_pid, host_pid, proc_type); + /* Fix mgr fd leak */ + if (g_mgr_com_cfg.proc_type == NSFW_PROC_MAIN + && (proc_type == NSFW_PROC_MAIN || proc_type == NSFW_PROC_MASTER)) + { + NSFW_LOGINF("update sock]fd=%d,opid=%u,npid=%u,type=%u", fd, + sock_info->host_pid, host_pid, proc_type); + } + else + { + NSFW_LOGDBG("update sock]fd=%d,opid=%u,npid=%u,type=%u", fd, + sock_info->host_pid, host_pid, proc_type); + } } - sock_info->host_pid = host_pid; - sock_info->proc_type = proc_type; + sock_info->host_pid = host_pid; + sock_info->proc_type = proc_type; - if (proc_type < NSFW_PROC_MAX) + if (proc_type < NSFW_PROC_MAX) { - g_mgr_socket_map.proc_cache[proc_type] = fd; + g_mgr_sockt_map.proc_cache[proc_type] = fd; } - return TRUE; + return TRUE; } /***************************************************************************** @@ -566,29 +644,28 @@ nsfw_mgr_new_socket (i32 fd, u8 proc_type, u32 host_pid) * Calls : * Called By : *****************************************************************************/ -NSTACK_STATIC inline u8 -nsfw_mgr_del_socket (u32 fd) +NSTACK_STATIC inline u8 nsfw_mgr_del_socket(u32 fd) { - nsfw_mgr_sock_info *sock_info = NULL; - if ((NSFW_MGR_FD_MAX <= fd) || (!g_mgr_socket_map.sock)) + nsfw_mgr_sock_info *sock_info = NULL; + if ((NSFW_MGR_FD_MAX <= fd) || (!g_mgr_sockt_map.sock)) { - NSFW_LOGERR ("fd err]mgr_fd=%u, sock=%p", fd, g_mgr_socket_map.sock); - return FALSE; + NSFW_LOGERR("fd err]mgr_fd=%u,sock=%p", fd, g_mgr_sockt_map.sock); + return FALSE; } - sock_info = &g_mgr_socket_map.sock[fd]; + sock_info = &g_mgr_sockt_map.sock[fd]; - if (sock_info->proc_type < NSFW_PROC_MAX - && fd == g_mgr_socket_map.proc_cache[sock_info->proc_type]) + if (sock_info->proc_type < NSFW_PROC_MAX + && fd == g_mgr_sockt_map.proc_cache[sock_info->proc_type]) { - g_mgr_socket_map.proc_cache[sock_info->proc_type] = 0; + g_mgr_sockt_map.proc_cache[sock_info->proc_type] = 0; } - NSFW_LOGDBG ("del sock]mgr_fd=%u,type=%u,pid=%u", fd, - sock_info->proc_type, sock_info->host_pid); - sock_info->host_pid = 0; - sock_info->proc_type = 0; - return TRUE; + NSFW_LOGDBG("del sock]mgr_fd=%u,type=%u,pid=%u", fd, + sock_info->proc_type, sock_info->host_pid); + sock_info->host_pid = 0; + sock_info->proc_type = 0; + return TRUE; } /***************************************************************************** @@ -601,53 +678,52 @@ nsfw_mgr_del_socket (u32 fd) * Calls : * Called By : *****************************************************************************/ -NSTACK_STATIC inline i32 -nsfw_mgr_get_dst_socket (u8 proc_type, u32 dst_pid) +NSTACK_STATIC inline i32 nsfw_mgr_get_dst_socket(u8 proc_type, u32 dst_pid) { - i32 fd = -1; + i32 fd = -1; - nsfw_mgr_sock_info *sock_info = NULL; + nsfw_mgr_sock_info *sock_info = NULL; - if (proc_type < NSFW_PROC_MAX) + if (proc_type < NSFW_PROC_MAX) { - fd = g_mgr_socket_map.proc_cache[proc_type]; + fd = g_mgr_sockt_map.proc_cache[proc_type]; } - if (!g_mgr_socket_map.sock) + if (!g_mgr_sockt_map.sock) { - return -1; + return -1; } - if (fd > 0 && fd < (i32) NSFW_MGR_FD_MAX) + if (fd > 0 && fd < (i32) NSFW_MGR_FD_MAX) { - sock_info = &g_mgr_socket_map.sock[fd]; - if (sock_info->host_pid != 0) + sock_info = &g_mgr_sockt_map.sock[fd]; + if (sock_info->host_pid != 0) { - if (0 == dst_pid || dst_pid == sock_info->host_pid) + if (0 == dst_pid || dst_pid == sock_info->host_pid) { - return fd; + return fd; } } - else if (proc_type == sock_info->proc_type) + else if (proc_type == sock_info->proc_type) { - return fd; + return fd; } } - i32 i; - for (i = 0; i < (i32) NSFW_MGR_FD_MAX; i++) + i32 i; + for (i = 0; i < (i32) NSFW_MGR_FD_MAX; i++) { - sock_info = &g_mgr_socket_map.sock[i]; - if (sock_info->host_pid != 0 && proc_type == sock_info->proc_type) + sock_info = &g_mgr_sockt_map.sock[i]; + if (sock_info->host_pid != 0 && proc_type == sock_info->proc_type) { - if (0 == dst_pid || dst_pid == sock_info->host_pid) + if (0 == dst_pid || dst_pid == sock_info->host_pid) { - return i; + return i; } } } - return -1; + return -1; } /***************************************************************************** @@ -660,17 +736,16 @@ nsfw_mgr_get_dst_socket (u8 proc_type, u32 dst_pid) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_mgr_get_new_socket (u8 proc_type, u32 dst_pid) +i32 nsfw_mgr_get_new_socket(u8 proc_type, u32 dst_pid) { - i32 fd = 0; - fd = nsfw_mgr_get_connect_socket (proc_type, dst_pid); - if (fd > 0) + i32 fd = 0; + fd = nsfw_mgr_get_connect_socket(proc_type, dst_pid); + if (fd > 0) { - (void) nsfw_mgr_new_socket (fd, proc_type, dst_pid); - (void) nsfw_mgr_reg_sock_fun (fd, nsfw_mgr_new_msg); + (void) nsfw_mgr_new_socket(fd, proc_type, dst_pid); + (void) nsfw_mgr_reg_sock_fun(fd, nsfw_mgr_new_msg); } - return fd; + return fd; } /***************************************************************************** @@ -682,20 +757,19 @@ nsfw_mgr_get_new_socket (u8 proc_type, u32 dst_pid) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_clr_fd_lock () +u8 nsfw_mgr_clr_fd_lock() { - i32 i; - if (!g_mgr_socket_map.sock) + i32 i; + if (!g_mgr_sockt_map.sock) { - NSFW_LOGERR ("clr fd lock fail, sock is null"); - return FALSE; + NSFW_LOGERR("clr fd lock fail, sock is null"); + return FALSE; } - for (i = 0; i < (i32) NSFW_MGR_FD_MAX; i++) + for (i = 0; i < (i32) NSFW_MGR_FD_MAX; i++) { - common_mem_spinlock_init (&(g_mgr_socket_map.sock[i].opr_lock)); + dmm_spin_init(&(g_mgr_sockt_map.sock[i].opr_lock)); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -708,15 +782,14 @@ nsfw_mgr_clr_fd_lock () * Calls : * Called By : *****************************************************************************/ -void -nsfw_mgr_close_dst_proc (u8 proc_type, u32 dst_pid) +void nsfw_mgr_close_dst_proc(u8 proc_type, u32 dst_pid) { - i32 fd = nsfw_mgr_get_dst_socket (proc_type, dst_pid); - if (fd > 0) + i32 fd = nsfw_mgr_get_dst_socket(proc_type, dst_pid); + if (fd > 0) { - (void) nsfw_mgr_del_socket (fd); - (void) nsfw_mgr_unreg_sock_fun (fd); - (void) nsfw_base_close (fd); + (void) nsfw_mgr_del_socket(fd); + (void) nsfw_mgr_unreg_sock_fun(fd); + (void) nsfw_base_close(fd); } } @@ -730,49 +803,49 @@ nsfw_mgr_close_dst_proc (u8 proc_type, u32 dst_pid) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_send_msg_socket (u32 fd, nsfw_mgr_msg * msg) +u8 nsfw_mgr_send_msg_socket(u32 fd, nsfw_mgr_msg * msg) { - i32 send_len = 0; - i32 off_set = 0; + i32 send_len = 0; + i32 off_set = 0; - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("msg nul]mgr_fd=%u", fd); - return FALSE; + NSFW_LOGERR("msg nul]mgr_fd=%u", fd); + return FALSE; } - if (msg->msg_len < sizeof (nsfw_mgr_msg)) + if (msg->msg_len < sizeof(nsfw_mgr_msg)) { - msg->msg_len = sizeof (nsfw_mgr_msg); + msg->msg_len = sizeof(nsfw_mgr_msg); } - if (msg->msg_type == MGR_MSG_LARGE_ALARM_RSP) + /* only need send msg->msg_body */ + if (msg->msg_type == MGR_MSG_LARGE_ALARM_RSP) { - off_set = NSFW_MGR_MSG_HDR_LEN; + off_set = NSFW_MGR_MSG_HDR_LEN; } - do + /*TODO if closed by peer, may send failed, should close this fd */ + do { - off_set += send_len; - send_len = - nsfw_base_send (fd, (char *) msg + off_set, msg->msg_len - off_set, - MSG_NOSIGNAL); - if (send_len <= 0) + off_set += send_len; + send_len = + nsfw_base_send(fd, (char *) msg + off_set, + msg->msg_len - off_set, MSG_NOSIGNAL); + if (send_len <= 0) { - NSFW_LOGERR - ("send error]mgr_fd=%u,send_len=%d,off_set=%d,errno=%d" MSGINFO, - fd, send_len, off_set, errno, PRTMSG (msg)); - return FALSE; + NSFW_LOGERR("send err]mgr_fd=%u,send_len=%d,off_set=%d,errno=%d" + MSGINFO, fd, send_len, off_set, errno, PRTMSG(msg)); + return FALSE; } } - while ((send_len + off_set) < (i32) msg->msg_len); - NSFW_LOGDBG ("send mgr_msg suc]mgr_fd=%u," MSGINFO, fd, PRTMSG (msg)); - g_mgr_stat.msg_send[msg->msg_type]++; - return TRUE; + while ((send_len + off_set) < (i32) msg->msg_len); + NSFW_LOGDBG("send mgr_msg suc]mgr_fd=%u," MSGINFO, fd, PRTMSG(msg)); + g_mgr_stat.msg_send[msg->msg_type]++; + return TRUE; } -#define MAX_RECV_COUNT 100 +#define MAX_RECV_COUNT 2 /***************************************************************************** * Prototype : nsfw_mgr_recv_msg_socket @@ -784,212 +857,289 @@ nsfw_mgr_send_msg_socket (u32 fd, nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_recv_msg_socket (u32 fd, nsfw_mgr_msg * msg, - nsfw_mgr_msg ** large_msg) +u8 nsfw_mgr_recv_msg_socket(u32 fd, nsfw_mgr_msg * msg, + nsfw_mgr_msg ** large_msg) { - i32 recv_len = 0; - i32 off_set = 0; - u32 msg_len = 0; - i32 max_count = 0; - if (NULL == msg) + i32 recv_len = 0; + i32 off_set = 0; + u32 msg_len = 0; + i32 max_count = 0; + if (NULL == msg) { - return FALSE; + return FALSE; } - u8 from_flag = msg->from_mem; - msg_len = msg->msg_len; - do + u8 from_flag = msg->from_mem; + msg_len = msg->msg_len; + do { - off_set += recv_len; - recv_len = - nsfw_base_recv (fd, (char *) msg + off_set, msg_len - off_set, 0); - if (recv_len <= 0) + off_set += recv_len; + recv_len = + nsfw_base_recv(fd, (char *) msg + off_set, msg_len - off_set, 0); + if (recv_len <= 0) { - if ((EINTR == errno || EAGAIN == errno) - && (max_count < MAX_RECV_COUNT)) + if ((EINTR == errno || EAGAIN == errno) + && (max_count < MAX_RECV_COUNT)) { - recv_len = 0; - max_count++; - continue; + recv_len = 0; + max_count++; + continue; } - NSFW_LOGERR - ("recv error]mgr_fd=%u,recv_len=%d,off_set=%d,errno=%d," - MSGINFO, fd, recv_len, off_set, errno, PRTMSG (msg)); - msg->from_mem = from_flag; - return FALSE; + NSFW_LOGERR("recv err]mgr_fd=%u,recv_len=%d,off_set=%d,errno=%d," + MSGINFO, fd, recv_len, off_set, errno, PRTMSG(msg)); + msg->from_mem = from_flag; + return FALSE; } } - while (recv_len + off_set < (i32) msg_len); + while (recv_len + off_set < (i32) msg_len); - msg->from_mem = from_flag; + msg->from_mem = from_flag; - g_mgr_stat.msg_recv[msg->msg_type]++; + g_mgr_stat.msg_recv[msg->msg_type]++; - if (msg->msg_len <= msg_len) + if (msg->msg_len <= msg_len) { - NSFW_LOGDBG ("recv mgr_msg suc]mgr_fd=%u," MSGINFO, fd, PRTMSG (msg)); - return TRUE; + NSFW_LOGDBG("recv mgr_msg suc]mgr_fd=%u," MSGINFO, fd, PRTMSG(msg)); + return TRUE; } - if (large_msg == NULL) + if (large_msg == NULL) { - return TRUE; + return TRUE; } - nsfw_mgr_msg *l_msg = - nsfw_mgr_msg_alloc (msg->msg_type, msg->dst_proc_type); - if (NULL == l_msg) + nsfw_mgr_msg *l_msg = + nsfw_mgr_msg_alloc(msg->msg_type, msg->dst_proc_type); + if (NULL == l_msg) { - return TRUE; + return TRUE; } - if (l_msg->msg_len <= msg_len) + if (l_msg->msg_len <= msg_len) { - NSFW_LOGWAR ("alloc new msg error!]len=%u,org_len=%u,type=%u", - l_msg->msg_len, msg->msg_len, msg->msg_type); - nsfw_mgr_msg_free (l_msg); - return TRUE; + NSFW_LOGWAR("alloc new msg err]len=%u,org_len=%u,type=%u", + l_msg->msg_len, msg->msg_len, msg->msg_type); + nsfw_mgr_msg_free(l_msg); + return TRUE; } - max_count = 0; - (void) nsfw_set_sock_block (fd, FALSE); - from_flag = l_msg->from_mem; - u32 l_msg_len = l_msg->msg_len; - do + max_count = 0; + (void) nsfw_set_sock_block(fd, FALSE); + from_flag = l_msg->from_mem; + u32 l_msg_len = l_msg->msg_len; + do { - off_set += recv_len; - recv_len = - nsfw_base_recv (fd, (char *) l_msg + off_set, l_msg_len - off_set, 0); - if (recv_len <= 0) + off_set += recv_len; + recv_len = + nsfw_base_recv(fd, (char *) l_msg + off_set, l_msg_len - off_set, + 0); + if (recv_len <= 0) { - if ((EINTR == errno || EAGAIN == errno) - && (max_count < MAX_RECV_COUNT)) + if ((EINTR == errno || EAGAIN == errno) + && (max_count < MAX_RECV_COUNT)) { - recv_len = 0; - max_count++; - continue; + recv_len = 0; + max_count++; + continue; } - NSFW_LOGERR - ("recv error]mgr_fd=%u,recv_len=%d,off_set=%d,errno=%d," - MSGINFO, fd, recv_len, off_set, errno, PRTMSG (msg)); - l_msg->from_mem = from_flag; - nsfw_mgr_msg_free (l_msg); - return FALSE; + NSFW_LOGERR("recv err]mgr_fd=%u,recv_len=%d,off_set=%d,errno=%d," + MSGINFO, fd, recv_len, off_set, errno, PRTMSG(msg)); + l_msg->from_mem = from_flag; + nsfw_mgr_msg_free(l_msg); + return FALSE; } } - while (recv_len + off_set < (i32) l_msg_len); - (void) nsfw_set_sock_block (fd, TRUE); - int retVal = MEMCPY_S (l_msg, msg_len, msg, msg_len); - if (EOK != retVal) + while (recv_len + off_set < (i32) l_msg_len); + (void) nsfw_set_sock_block(fd, TRUE); + int retVal = memcpy_s(l_msg, msg_len, msg, msg_len); + if (EOK != retVal) { - NSFW_LOGERR ("MEMCPY_S failed] ret=%d", retVal); - l_msg->from_mem = from_flag; - nsfw_mgr_msg_free (l_msg); - return TRUE; + NSFW_LOGERR("memcpy_s fail]ret=%d", retVal); + l_msg->from_mem = from_flag; + nsfw_mgr_msg_free(l_msg); + return TRUE; } - l_msg->from_mem = from_flag; - l_msg->msg_len = l_msg_len; + l_msg->from_mem = from_flag; + l_msg->msg_len = l_msg_len; - *large_msg = l_msg; - NSFW_LOGDBG ("recv large mgr_msg suc]mgr_fd=%u," MSGINFO, fd, - PRTMSG (l_msg)); - return TRUE; + *large_msg = l_msg; + NSFW_LOGDBG("recv large mgr_msg suc]mgr_fd=%u," MSGINFO, fd, + PRTMSG(l_msg)); + return TRUE; } /***************************************************************************** -* Prototype : nsfw_mgr_send_req_wait_rsp -* Description : send request message and block waiting for it's response - within MGR_COM_RECV_TIMEOUT +* Prototype : nsfw_mgr_get_socket +* Description : try best to return an available dst_socket * Input : nsfw_mgr_msg* req_msg * nsfw_mgr_msg* rsp_msg + i32 dst_socket (origin fd, <=0 to lookup or create, >0 to renew) * Output : None -* Return Value : u8 +* Return Value : i32 * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_send_req_wait_rsp (nsfw_mgr_msg * req_msg, nsfw_mgr_msg * rsp_msg) +i32 nsfw_mgr_get_socket(nsfw_mgr_msg * req_msg, nsfw_mgr_msg * rsp_msg, + i32 dst_socket) { - if (NULL == req_msg) + if (dst_socket <= 0) /* origin fd <= 0, first lookup the eastablished, if none, create a new one */ { - NSFW_LOGERR ("req msg nul!"); - return FALSE; + dst_socket = + nsfw_mgr_get_dst_socket(req_msg->dst_proc_type, req_msg->dst_pid); + if (dst_socket <= 0) + { + dst_socket = + nsfw_mgr_get_new_socket(req_msg->dst_proc_type, + req_msg->dst_pid); + if (dst_socket <= 0) + { + NSFW_LOGERR("send msg get dst_socket_err]" MSGINFO, + PRTMSG(req_msg)); + return -1; + } + } } - - i32 dst_socket = - nsfw_mgr_get_dst_socket (req_msg->dst_proc_type, req_msg->dst_pid); - if (dst_socket <= 0) + else /* origin fd is broken probably because the other end just upgraded, delete the old one and re-create */ { - dst_socket = - nsfw_mgr_get_new_socket (req_msg->dst_proc_type, req_msg->dst_pid); - if (dst_socket <= 0) + (void) nsfw_mgr_del_socket(dst_socket); + (void) nsfw_mgr_unreg_sock_fun(dst_socket); + (void) nsfw_base_close(dst_socket); + UNLOCK_MGR_FD(dst_socket) + dst_socket = + nsfw_mgr_get_new_socket(req_msg->dst_proc_type, req_msg->dst_pid); + if (dst_socket <= 0) { - NSFW_LOGERR ("send msg get dst_socket_error]" MSGINFO, - PRTMSG (req_msg)); - return FALSE; + NSFW_LOGERR("send msg get dst_socket_err]" MSGINFO, + PRTMSG(req_msg)); + return -1; } } + return dst_socket; +} - if ((NULL == rsp_msg) && (req_msg->msg_len == sizeof (nsfw_mgr_msg))) +/***************************************************************************** +* Prototype : nsfw_mgr_do_send_and_recv +* Description : do send and recv work +* Input : nsfw_mgr_msg* req_msg +* nsfw_mgr_msg* rsp_msg +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_mgr_do_send_and_recv(nsfw_mgr_msg * req_msg, nsfw_mgr_msg * rsp_msg, + i32 dst_socket, i32 retry_times_left) +{ + LOCK_MGR_FD(dst_socket) + if ((NULL == rsp_msg) && (req_msg->msg_len == sizeof(nsfw_mgr_msg))) { - LOCK_MGR_FD (dst_socket) - if (FALSE == nsfw_mgr_send_msg_socket (dst_socket, req_msg)) + if (FALSE == nsfw_mgr_send_msg_socket(dst_socket, req_msg)) { - NSFW_LOGERR ("send msg error]" MSGINFO, PRTMSG (req_msg)); - g_mgr_stat.msg_send_failed++; - UNLOCK_MGR_FD (dst_socket) return FALSE; + g_mgr_stat.msg_send_failed++; + goto ERROR_RETURN; } - UNLOCK_MGR_FD (dst_socket) return TRUE; + UNLOCK_MGR_FD(dst_socket) return TRUE; } - LOCK_MGR_FD (dst_socket); - (void) nsfw_mgr_unreg_sock_fun (dst_socket); - if (FALSE == nsfw_mgr_send_msg_socket (dst_socket, req_msg)) + (void) nsfw_mgr_unreg_sock_fun(dst_socket); + if (FALSE == nsfw_mgr_send_msg_socket(dst_socket, req_msg)) { - NSFW_LOGERR ("send msg error]" MSGINFO, PRTMSG (req_msg)); - g_mgr_stat.msg_send_failed++; - (void) nsfw_mgr_reg_sock_fun (dst_socket, nsfw_mgr_new_msg); - UNLOCK_MGR_FD (dst_socket); - return FALSE; + g_mgr_stat.msg_send_failed++; + goto ERROR_RETURN; } - if (NULL == rsp_msg) + if (NULL == rsp_msg) { - (void) nsfw_mgr_reg_sock_fun (dst_socket, nsfw_mgr_new_msg); - UNLOCK_MGR_FD (dst_socket) return TRUE; + (void) nsfw_mgr_reg_sock_fun(dst_socket, nsfw_mgr_new_msg); + UNLOCK_MGR_FD(dst_socket) return TRUE; } - u16 i; - for (i = 0; i < MGR_COM_MAX_DROP_MSG; i++) + u16 i; + for (i = 0; i < MGR_COM_MAX_DROP_MSG; i++) { - if (FALSE == nsfw_mgr_recv_msg_socket (dst_socket, rsp_msg, NULL)) + if (FALSE == nsfw_mgr_recv_msg_socket(dst_socket, rsp_msg, NULL)) { - NSFW_LOGERR ("recv msg error]" MSGINFO, PRTMSG (req_msg)); - (void) nsfw_mgr_reg_sock_fun (dst_socket, nsfw_mgr_new_msg); - UNLOCK_MGR_FD (dst_socket) return FALSE; + goto ERROR_RETURN; } - if ((rsp_msg->seq == req_msg->seq) - && (rsp_msg->msg_type == req_msg->msg_type + MGR_MSG_RSP_BASE)) + if ((rsp_msg->seq == req_msg->seq) + && (rsp_msg->msg_type == req_msg->msg_type + MGR_MSG_RSP_BASE)) { - break; + break; } - NSFW_LOGINF ("recv msg forward]" MSGINFO, PRTMSG (rsp_msg)); - rsp_msg->fw_flag = TRUE; - (void) nsfw_mgr_send_msg (rsp_msg); + NSFW_LOGDBG("recv msg forward]" MSGINFO, PRTMSG(rsp_msg)); + rsp_msg->fw_flag = TRUE; + (void) nsfw_mgr_send_msg(rsp_msg); + } + + (void) nsfw_mgr_reg_sock_fun(dst_socket, nsfw_mgr_new_msg); + if (0 == req_msg->dst_pid) + { + (void) nsfw_mgr_new_socket(dst_socket, rsp_msg->src_proc_type, + rsp_msg->src_pid); + } + UNLOCK_MGR_FD(dst_socket) return TRUE; + + ERROR_RETURN: + if (0 >= retry_times_left) + { + NSFW_LOGERR("send msg err]" MSGINFO, PRTMSG(req_msg)); + (void) nsfw_mgr_reg_sock_fun(dst_socket, nsfw_mgr_new_msg); + UNLOCK_MGR_FD(dst_socket); + } + else + { + NSFW_LOGWAR + ("origin mgr socket=%d is broken, try re-create, %d times left", + dst_socket, retry_times_left); + /* NOTE: no need to re-register sock_fun, will UNLOCK in next call of nsfw_mgr_get_socket */ + } + return FALSE; + +} + +/***************************************************************************** +* Prototype : nsfw_mgr_send_req_wait_rsp +* Description : send request message and block waiting for it's response + within MGR_COM_RECV_TIMEOUT +* Input : nsfw_mgr_msg* req_msg +* nsfw_mgr_msg* rsp_msg +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_mgr_send_req_wait_rsp(nsfw_mgr_msg * req_msg, nsfw_mgr_msg * rsp_msg) +{ + if (NULL == req_msg) + { + NSFW_LOGERR("req msg nul"); + return FALSE; } - (void) nsfw_mgr_reg_sock_fun (dst_socket, nsfw_mgr_new_msg); - if (0 == req_msg->dst_pid) + i32 dst_socket = 0; + i32 retry_times_left = 1; + while (retry_times_left >= 0) { - (void) nsfw_mgr_new_socket (dst_socket, rsp_msg->src_proc_type, - rsp_msg->src_pid); + dst_socket = nsfw_mgr_get_socket(req_msg, rsp_msg, dst_socket); + if (dst_socket <= 0) + { + NSFW_LOGERR("send msg get dst_socket_err]" MSGINFO, + PRTMSG(req_msg)); + return FALSE; + } + u8 ret = nsfw_mgr_do_send_and_recv(req_msg, rsp_msg, dst_socket, + retry_times_left); + if (ret == TRUE) + { + return TRUE; + } + --retry_times_left; } - UNLOCK_MGR_FD (dst_socket) return TRUE; + return FALSE; } /***************************************************************************** @@ -1001,10 +1151,9 @@ nsfw_mgr_send_req_wait_rsp (nsfw_mgr_msg * req_msg, nsfw_mgr_msg * rsp_msg) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_send_msg (nsfw_mgr_msg * msg) +u8 nsfw_mgr_send_msg(nsfw_mgr_msg * msg) { - return nsfw_mgr_send_req_wait_rsp (msg, NULL); + return nsfw_mgr_send_req_wait_rsp(msg, NULL); } /***************************************************************************** @@ -1016,79 +1165,77 @@ nsfw_mgr_send_msg (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_msg_in (i32 fd) +u8 nsfw_mgr_msg_in(i32 fd) { - u32 i = 0; - u8 ret = FALSE; - u8 msg_match = FALSE; - nsfw_mgr_msg *msg = nsfw_mgr_null_rspmsg_alloc (); - nsfw_mgr_msg *large_msg = NULL; + u32 i = 0; + u8 ret = FALSE; + u8 msg_match = FALSE; + nsfw_mgr_msg *msg = nsfw_mgr_null_rspmsg_alloc(); + nsfw_mgr_msg *large_msg = NULL; - LOCK_MGR_FD (fd) ret = nsfw_mgr_recv_msg_socket (fd, msg, &large_msg); - UNLOCK_MGR_FD (fd) if (large_msg != NULL) + LOCK_MGR_FD(fd) ret = nsfw_mgr_recv_msg_socket(fd, msg, &large_msg); + UNLOCK_MGR_FD(fd) if (large_msg != NULL) { - nsfw_mgr_msg_free (msg); - msg = large_msg; + nsfw_mgr_msg_free(msg); + msg = large_msg; } - if (FALSE == ret) + if (FALSE == ret) { - nsfw_mgr_msg_free (msg); - return FALSE; + nsfw_mgr_msg_free(msg); + return FALSE; } - - if (msg->fw_flag != TRUE) + if (msg->fw_flag != TRUE) { - (void) nsfw_mgr_new_socket (fd, msg->src_proc_type, msg->src_pid); + (void) nsfw_mgr_new_socket(fd, msg->src_proc_type, msg->src_pid); } - if (msg->msg_type < MGR_MSG_MAX) + if (msg->msg_type < MGR_MSG_MAX) { - for (i = 0; i < NSFW_MGRCOM_MAX_PROC_FUN; i++) + for (i = 0; i < NSFW_MGRCOM_MAX_PROC_FUN; i++) { - if (NULL == g_mgr_fun[msg->msg_type][i]) + if (NULL == g_mgr_fun[msg->msg_type][i]) { - break; + break; } - (void) g_mgr_fun[msg->msg_type][i] (msg); - msg_match = TRUE; + (void) g_mgr_fun[msg->msg_type][i] (msg); + msg_match = TRUE; } } - if (FALSE != msg_match) + if (FALSE != msg_match) { - nsfw_mgr_msg_free (msg); - return TRUE; + nsfw_mgr_msg_free(msg); + return TRUE; } - if (msg->msg_type < MGR_MSG_RSP_BASE) + if (msg->msg_type < MGR_MSG_RSP_BASE) { - NSFW_LOGERR ("msg match failed! auto rsp]" MSGINFO, PRTMSG (msg)); - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL != rsp_msg) + NSFW_LOGERR("msg match failed! auto rsp]" MSGINFO, PRTMSG(msg)); + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL != rsp_msg) { - rsp_msg->resp_code = NSFW_MGR_MSG_TYPE_ERROR; - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); + rsp_msg->resp_code = NSFW_MGR_MSG_TYPE_ERROR; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); } } - NSFW_LOGERR ("drop msg]" MSGINFO, PRTMSG (msg)); - /* fix "Out-of-bounds write" type codex issue */ - if (msg->msg_type < MGR_MSG_MAX) + NSFW_LOGERR("drop msg]" MSGINFO, PRTMSG(msg)); + /* fix "Out-of-bounds write" */ + if (msg->msg_type < MGR_MSG_MAX) { - g_mgr_stat.recv_drop[msg->msg_type]++; + g_mgr_stat.recv_drop[msg->msg_type]++; } - nsfw_mgr_msg_free (msg); - return FALSE; + nsfw_mgr_msg_free(msg); + return FALSE; } /***************************************************************************** * Prototype : nsfw_mgr_new_msg -* Description : when new mgr message receive from socket, this function +* Description : when new mgr message recive from socket, this funciton will call back * Input : i32 epfd * i32 fd @@ -1098,22 +1245,19 @@ nsfw_mgr_msg_in (i32 fd) * Calls : * Called By : *****************************************************************************/ -int -nsfw_mgr_new_msg (i32 epfd, i32 fd, u32 events) +/*try to get event form all modules */ +int nsfw_mgr_new_msg(i32 epfd, i32 fd, u32 events) { - lint_lock_1 (); - if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) + if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) { - (void) nsfw_mgr_del_socket (fd); - (void) nsfw_mgr_unreg_sock_fun (fd); - (void) nsfw_base_close (fd); - lint_unlock_1 (); - return TRUE; + (void) nsfw_mgr_del_socket(fd); + (void) nsfw_mgr_unreg_sock_fun(fd); + (void) nsfw_base_close(fd); + return TRUE; } - (void) nsfw_mgr_msg_in (fd); - lint_unlock_1 (); - return TRUE; + (void) nsfw_mgr_msg_in(fd); + return TRUE; } /***************************************************************************** @@ -1126,11 +1270,11 @@ nsfw_mgr_new_msg (i32 epfd, i32 fd, u32 events) * Calls : * Called By : *****************************************************************************/ -int -nsfw_mgr_com_rereg_fun (u32 timer_type, void *data) +int nsfw_mgr_com_rereg_fun(u32 timer_type, void *data) { - (void) nsfw_mgr_reg_sock_fun (timer_type, (nsfw_mgr_sock_fun) data); - return TRUE; + + (void) nsfw_mgr_reg_sock_fun(timer_type, (nsfw_mgr_sock_fun) data); + return TRUE; } /***************************************************************************** @@ -1144,18 +1288,18 @@ nsfw_mgr_com_rereg_fun (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -int -nsfw_mgr_com_socket_error (i32 fd, nsfw_mgr_sock_fun fun, i32 timer) +int nsfw_mgr_com_socket_error(i32 fd, nsfw_mgr_sock_fun fun, i32 timer) { - struct timespec time_left = { timer, 0 }; - nsfw_mgr_unreg_sock_fun (fd); - nsfw_timer_reg_timer (fd, (void *) fun, nsfw_mgr_com_rereg_fun, time_left); - return TRUE; + + struct timespec time_left = { timer, 0 }; + nsfw_mgr_unreg_sock_fun(fd); + nsfw_timer_reg_timer(fd, (void *) fun, nsfw_mgr_com_rereg_fun, time_left); + return TRUE; } /***************************************************************************** * Prototype : nsfw_mgr_new_connection -* Description : when new mgr connection in, this function will call back +* Description : when new mgr connection in, this funciton will call back * Input : i32 epfd * i32 fd * u32 events @@ -1164,81 +1308,79 @@ nsfw_mgr_com_socket_error (i32 fd, nsfw_mgr_sock_fun fun, i32 timer) * Calls : * Called By : *****************************************************************************/ -int -nsfw_mgr_new_connection (i32 epfd, i32 fd, u32 events) +int nsfw_mgr_new_connection(i32 epfd, i32 fd, u32 events) { - if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) - { - (void) nsfw_base_close (fd); - NSFW_LOGWAR ("listen disconnect!]epfd=%d,listen=%d,event=0x%x", epfd, - fd, events); - (void) nsfw_mgr_unreg_sock_fun (fd); - i32 listen_fd = nsfw_mgr_get_listen_socket (); - if (listen_fd < 0) + if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) + { + (void) nsfw_base_close(fd); + NSFW_LOGWAR("listen disconnect]epfd=%d,listen=%d,event=0x%x", epfd, + fd, events); + (void) nsfw_mgr_unreg_sock_fun(fd); + i32 listen_fd = nsfw_mgr_get_listen_socket(); + if (listen_fd < 0) { - NSFW_LOGERR - ("get listen_fd failed!]epfd=%d,listen_fd=%d,event=0x%x", epfd, - fd, events); - return FALSE; + NSFW_LOGERR("get listen_fd fail]epfd=%d,listen_fd=%d,event=0x%x", + epfd, fd, events); + return FALSE; } - (void) nsfw_mgr_reg_sock_fun (listen_fd, nsfw_mgr_new_connection); - return TRUE; + (void) nsfw_mgr_reg_sock_fun(listen_fd, nsfw_mgr_new_connection); + return TRUE; } - struct sockaddr in_addr; - socklen_t in_len; - int infd; - in_len = sizeof in_addr; + int infd; + struct sockaddr addr; + socklen_t len = sizeof(addr); + int size, size_len; + u8 accept_flag = FALSE; - int size, size_len; - u8 accept_flag = FALSE; - while (1) + while (1) { - infd = nsfw_base_accept (fd, &in_addr, &in_len); - if (infd == -1) + infd = nsfw_base_accept(fd, &addr, &len); + if (infd == -1) { - if (FALSE == accept_flag) + if (FALSE == accept_flag) { - nsfw_mgr_com_socket_error (fd, nsfw_mgr_new_connection, 1); + nsfw_mgr_com_socket_error(fd, nsfw_mgr_new_connection, 1); } - break; + break; } - if (-1 == nsfw_set_close_on_exec (infd)) + /* close on exec */ + if (-1 == nsfw_set_close_on_exec(infd)) { - (void) nsfw_base_close (infd); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", infd, errno); - break; + (void) nsfw_base_close(infd); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", infd, errno); + break; } - size = MAX_RECV_BUF_DEF; - size_len = sizeof (size); - if (0 > - nsfw_base_setsockopt (infd, SOL_SOCKET, SO_RCVBUF, (void *) &size, - (socklen_t) size_len)) + size = MAX_RECV_BUF_DEF; + size_len = sizeof(size); + if (0 > + nsfw_base_setsockopt(infd, SOL_SOCKET, SO_RCVBUF, (void *) &size, + (socklen_t) size_len)) { - NSFW_LOGERR ("set socket opt err!]error=%d", errno); + NSFW_LOGERR("set socket opt err]error=%d", errno); } - if (0 > - nsfw_base_setsockopt (infd, SOL_SOCKET, SO_SNDBUF, (void *) &size, - (socklen_t) size_len)) + if (0 > + nsfw_base_setsockopt(infd, SOL_SOCKET, SO_SNDBUF, (void *) &size, + (socklen_t) size_len)) { - NSFW_LOGERR ("set socket opt err!]error=%d", errno); + NSFW_LOGERR("set socket opt err]error=%d", errno); } - (void) nsfw_mgr_reg_sock_fun (infd, nsfw_mgr_new_msg); - NSFW_LOGDBG ("accept_flag new fd]new_mgr_fd=%d", infd); - accept_flag = TRUE; + (void) nsfw_mgr_reg_sock_fun(infd, nsfw_mgr_new_msg); + NSFW_LOGDBG("accept_flag new fd]new_mgr_fd=%d", infd); + accept_flag = TRUE; } - return TRUE; + return TRUE; } /***************************************************************************** * Prototype : nsfw_set_sock_block -* Description : set fd block or not for epoll thread +* Description : set fd blok or not for epoll thread * Input : i32 sock * u8 flag * Output : None @@ -1246,45 +1388,45 @@ nsfw_mgr_new_connection (i32 epfd, i32 fd, u32 events) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_set_sock_block (i32 sock, u8 flag) +i32 nsfw_set_sock_block(i32 sock, u8 flag) { - i32 flags; - flags = nsfw_base_fcntl (sock, F_GETFL, 0); - if (flags < 0) + i32 flags; + flags = nsfw_base_fcntl(sock, F_GETFL, 0); + if (flags < 0) { - NSFW_LOGERR ("fcntl err]new_mgr_fd=%d,errno=%d", sock, errno); - return -1; + NSFW_LOGERR("fcntl err]new_mgr_fd=%d,errno=%d", sock, errno); + return -1; } - if (TRUE == flag) + if (TRUE == flag) { - flags = flags | O_NONBLOCK; + flags = flags | O_NONBLOCK; } - else + else { - flags = flags & (~O_NONBLOCK); - struct timeval tv; - tv.tv_sec = MGR_COM_RECV_TIMEOUT; - tv.tv_usec = 0; - if (nsfw_base_setsockopt - (sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof tv)) + flags = flags & (~O_NONBLOCK); + struct timeval tv; + tv.tv_sec = MGR_COM_RECV_TIMEOUT; + tv.tv_usec = 0; + if (nsfw_base_setsockopt + (sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof tv)) { - NSFW_LOGERR ("setsockopt socket err]mgr_fd=%d", sock); - return -1; + NSFW_LOGERR("setsockopt socket err]mgr_fd=%d", sock); + return -1; } } - if (nsfw_base_fcntl (sock, F_SETFL, flags) < 0) + if (nsfw_base_fcntl(sock, F_SETFL, flags) < 0) { - NSFW_LOGERR ("fcntl err]new_mgr_fd=%d,errno=%d,flags=%d", sock, errno, - flags); - return -1; + NSFW_LOGERR("fcntl err]new_mgr_fd=%d,errno=%d,flags=%d", sock, errno, + flags); + return -1; } - return 0; + return 0; } +/* close on exec */ /***************************************************************************** * Prototype : nsfw_set_close_on_exec * Description : close on exec set @@ -1294,26 +1436,25 @@ nsfw_set_sock_block (i32 sock, u8 flag) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_set_close_on_exec (i32 sock) +i32 nsfw_set_close_on_exec(i32 sock) { - i32 flags; - flags = nsfw_base_fcntl (sock, F_GETFD, 0); - if (flags < 0) + i32 flags; + flags = nsfw_base_fcntl(sock, F_GETFD, 0); + if (flags < 0) { - NSFW_LOGERR ("fcntl err]fd=%d,errno=%d", sock, errno); - return -1; + NSFW_LOGERR("fcntl err]fd=%d,errno=%d", sock, errno); + return -1; } - flags |= FD_CLOEXEC; + flags |= FD_CLOEXEC; - if (nsfw_base_fcntl (sock, F_SETFD, flags) < 0) + if (nsfw_base_fcntl(sock, F_SETFD, flags) < 0) { - NSFW_LOGERR ("fcntl err]fd=%d,errno=%d,flags=%d", sock, errno, flags); - return -1; + NSFW_LOGERR("fcntl err]fd=%d,errno=%d,flags=%d", sock, errno, flags); + return -1; } - return 0; + return 0; } /***************************************************************************** @@ -1325,29 +1466,35 @@ nsfw_set_close_on_exec (i32 sock) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_add_sock_to_ep (i32 fd) +u8 nsfw_add_sock_to_ep(i32 fd) { - struct epoll_event event; - event.data.fd = fd; - event.events = EPOLLIN; - if (g_ep_proc.epfd == 0) + struct epoll_event event; + event.data.fd = fd; + event.events = EPOLLIN; + if (g_ep_proc.epfd == 0) { - return TRUE; + return TRUE; } - (void) nsfw_set_sock_block (fd, TRUE); + (void) nsfw_set_sock_block(fd, TRUE); - if (0 > nsfw_base_epoll_ctl (g_ep_proc.epfd, EPOLL_CTL_ADD, fd, &event)) + if (0 > nsfw_base_epoll_ctl(g_ep_proc.epfd, EPOLL_CTL_ADD, fd, &event)) { - NSFW_LOGINF - ("add sock to ep thread failed]mgr_fd=%d,errno=%d,epfd=%d", fd, - errno, g_ep_proc.epfd); - return FALSE; + /*It is possible that multi-threads operate EPOLL_ADD at the same time, + *we allow this case, and return TRUE for it when errno==EEXIST*/ + if (EEXIST == errno) + { + NSFW_LOGDBG + ("add sock to ep thread but exist already, return TRUE directly]mgr_fd=%d,epfd=%d", + fd, g_ep_proc.epfd) return TRUE; + } + NSFW_LOGINF("add sock to ep thread fail]mgr_fd=%d,errno=%d,epfd=%d", + fd, errno, g_ep_proc.epfd); + return FALSE; } - NSFW_LOGDBG ("add sock to ep thread]mgr_fd=%d,epfd=%d", fd, - g_ep_proc.epfd) return TRUE; + NSFW_LOGDBG("add sock to ep thread]mgr_fd=%d,epfd=%d", fd, + g_ep_proc.epfd) return TRUE; } /***************************************************************************** @@ -1359,29 +1506,28 @@ nsfw_add_sock_to_ep (i32 fd) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_rmv_sock_from_ep (i32 fd) +u8 nsfw_rmv_sock_from_ep(i32 fd) { - struct epoll_event event; - event.data.fd = fd; - event.events = EPOLLIN; - if (g_ep_proc.epfd == 0) + struct epoll_event event; + event.data.fd = fd; + event.events = EPOLLIN; + if (g_ep_proc.epfd == 0) { - return TRUE; + //NSFW_LOGINF("rmv sock to ep thread before start]mgr_fd=%d",fd); + return TRUE; } - (void) nsfw_set_sock_block (fd, FALSE); + (void) nsfw_set_sock_block(fd, FALSE); - if (0 > nsfw_base_epoll_ctl (g_ep_proc.epfd, EPOLL_CTL_DEL, fd, &event)) + if (0 > nsfw_base_epoll_ctl(g_ep_proc.epfd, EPOLL_CTL_DEL, fd, &event)) { - NSFW_LOGINF - ("rmv sock to ep thread failed] mgr_fd=%d,errno=%d,epfd=%d", fd, - errno, g_ep_proc.epfd); - return FALSE; + NSFW_LOGINF("rmv sock to ep thread fail]mgr_fd=%d,errno=%d,epfd=%d", + fd, errno, g_ep_proc.epfd); + return FALSE; } - NSFW_LOGDBG ("rmv sock to ep thread] mgr_fd=%d,epfd=%d", fd, - g_ep_proc.epfd) return TRUE; + NSFW_LOGDBG("rmv sock to ep thread]mgr_fd=%d,epfd=%d", fd, + g_ep_proc.epfd) return TRUE; } /***************************************************************************** @@ -1395,33 +1541,28 @@ nsfw_rmv_sock_from_ep (i32 fd) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_reg_sock_fun (i32 fd, nsfw_mgr_sock_fun fun) +/*try to get event form all modules */ +u8 nsfw_mgr_reg_sock_fun(i32 fd, nsfw_mgr_sock_fun fun) { - lint_lock_1 (); - if ((fd >= (i32) NSFW_MGR_FD_MAX) || (fd < 0) || NULL == fun) + if ((fd >= (i32) NSFW_MGR_FD_MAX) || (fd < 0) || NULL == fun) { - NSFW_LOGINF ("reg sock fun error!] mgr_fd=%d,fun=%p", fd, fun); - lint_unlock_1 (); - return FALSE; + NSFW_LOGINF("reg sock fun error]mgr_fd=%d,fun=%p", fd, fun); + return FALSE; } - if ((g_ep_proc.ep_fun) && (NULL == g_ep_proc.ep_fun[fd])) + if ((g_ep_proc.ep_fun) && (NULL == g_ep_proc.ep_fun[fd])) { - g_ep_proc.ep_fun[fd] = fun; - if (FALSE == nsfw_add_sock_to_ep (fd)) + g_ep_proc.ep_fun[fd] = fun; + if (FALSE == nsfw_add_sock_to_ep(fd)) { - g_ep_proc.ep_fun[fd] = NULL; - lint_unlock_1 (); - return FALSE; + g_ep_proc.ep_fun[fd] = NULL; + return FALSE; } - NSFW_LOGDBG ("reg sock fun] mgr_fd=%d,fun=%p", fd, fun); - lint_unlock_1 (); - return TRUE; + NSFW_LOGDBG("reg sock fun]mgr_fd=%d,fun=%p", fd, fun); + return TRUE; } - lint_unlock_1 (); - return FALSE; + return FALSE; } /***************************************************************************** @@ -1433,28 +1574,24 @@ nsfw_mgr_reg_sock_fun (i32 fd, nsfw_mgr_sock_fun fun) * Calls : * Called By : *****************************************************************************/ -void -nsfw_mgr_unreg_sock_fun (i32 fd) +/*try to get event form all modules */ +void nsfw_mgr_unreg_sock_fun(i32 fd) { - lint_lock_1 (); - if (fd >= (i32) NSFW_MGR_FD_MAX) + if (fd >= (i32) NSFW_MGR_FD_MAX) { - NSFW_LOGINF ("unreg sock fun failed!] mgr_fd=%d", fd); - lint_unlock_1 (); - return; + NSFW_LOGINF("unreg sock fun fail]mgr_fd=%d", fd); + return; } - if ((g_ep_proc.ep_fun) && (NULL != g_ep_proc.ep_fun[fd])) + if ((g_ep_proc.ep_fun) && (NULL != g_ep_proc.ep_fun[fd])) { - g_ep_proc.ep_fun[fd] = NULL; - (void) nsfw_rmv_sock_from_ep (fd); - NSFW_LOGDBG ("unreg sock fun] mgr_fd=%d", fd); - lint_unlock_1 (); - return; + g_ep_proc.ep_fun[fd] = NULL; + (void) nsfw_rmv_sock_from_ep(fd); + NSFW_LOGDBG("unreg sock fun]mgr_fd=%d", fd); + return; } - lint_unlock_1 (); - return; + return; } /***************************************************************************** @@ -1468,22 +1605,21 @@ nsfw_mgr_unreg_sock_fun (i32 fd) * Calls : * Called By : *****************************************************************************/ -NSTACK_STATIC inline u8 -nsfw_sock_fun_callback (i32 epfd, i32 fd, u32 events) +NSTACK_STATIC inline u8 nsfw_sock_fun_callback(i32 epfd, i32 fd, u32 events) { - if ((fd < (i32) NSFW_MGR_FD_MAX) - && (g_ep_proc.ep_fun) && (NULL != g_ep_proc.ep_fun[fd])) + if ((fd < (i32) NSFW_MGR_FD_MAX) + && (g_ep_proc.ep_fun) && (NULL != g_ep_proc.ep_fun[fd])) { - (void) g_ep_proc.ep_fun[fd] (epfd, fd, events); - return TRUE; + (void) g_ep_proc.ep_fun[fd] (epfd, fd, events); + return TRUE; } - return FALSE; + return FALSE; } /***************************************************************************** -* Prototype : nsfw_sock_add_to_ep -* Description : add all event process function has ben reg to the epoll +* Prototype : nsfw_add_prestored_sock_to_ep +* Description : add all the socks (whose process function has ben reg) to the epoll thread when thread start * Input : i32 epfd * Output : None @@ -1491,21 +1627,37 @@ nsfw_sock_fun_callback (i32 epfd, i32 fd, u32 events) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_sock_add_to_ep (i32 epfd) +u8 nsfw_add_prestored_sock_to_ep() { - u32 i; + u32 i; + u8 ret; + + if (NULL == g_ep_proc.ep_fun) + { + NSFW_LOGERR("g_ep_proc.ep_fun should not be NULL at this time"); + return FALSE; + } - for (i = 0; i < NSFW_MGR_FD_MAX; i++) + for (i = 0; i < NSFW_MGR_FD_MAX; i++) { - if ((g_ep_proc.ep_fun) && (NULL == g_ep_proc.ep_fun[i])) + if (NULL == g_ep_proc.ep_fun[i]) { - continue; + continue; + } + + /*add return value check */ + ret = nsfw_add_sock_to_ep(i); + if (FALSE == ret) + { + /*here, we add some fd(which belongs to other module and prestore to g_ep_proc) to ep . + must add success. if add fail, stack init should end up */ + NSFW_LOGERR("nsfw_add_sock_to_ep fail]epfd=%d,i=%u", + g_ep_proc.epfd, i); + return FALSE; } - (void) nsfw_add_sock_to_ep (i); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -1517,19 +1669,18 @@ nsfw_sock_add_to_ep (i32 epfd) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_com_start () +u8 nsfw_mgr_com_start() { - i32 listen_fd = nsfw_mgr_get_listen_socket (); - if (listen_fd < 0) + i32 listern_fd = nsfw_mgr_get_listen_socket(); + if (listern_fd < 0) { - NSFW_LOGERR ("get listen_fd failed!"); - return FALSE; + NSFW_LOGERR("get listern_fd fail"); + return FALSE; } - NSFW_LOGINF ("start mgr_com module!] listen_fd=%d", listen_fd); - (void) nsfw_mgr_reg_sock_fun (listen_fd, nsfw_mgr_new_connection); - return TRUE; + NSFW_LOGINF("start mgr_com module]listern_fd=%d", listern_fd); + (void) nsfw_mgr_reg_sock_fun(listern_fd, nsfw_mgr_new_connection); + return TRUE; } /***************************************************************************** @@ -1541,24 +1692,28 @@ nsfw_mgr_com_start () * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_com_start_local (u8 proc_type) +u8 nsfw_mgr_com_start_local(u8 proc_type) { - int fd[2]; - if ((socketpair (AF_UNIX, SOCK_STREAM, 0, fd)) < 0) + int fd[2]; + if ((socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) { - NSFW_LOGERR ("create socket err] type=%u,errno=%d", proc_type, errno); - return FALSE; + NSFW_LOGERR("create socket err]type=%u,errno=%d", proc_type, errno); + return FALSE; } - (void) nsfw_mgr_new_socket (fd[0], proc_type, get_sys_pid ()); - (void) nsfw_mgr_new_socket (fd[1], proc_type, get_sys_pid ()); - (void) nsfw_mgr_reg_sock_fun (fd[0], nsfw_mgr_new_msg); - (void) nsfw_mgr_reg_sock_fun (fd[1], nsfw_mgr_new_msg); - NSFW_LOGINF ("create local socket] fd0=%d,fd1=%d", fd[0], fd[1]); - return TRUE; + (void) nsfw_mgr_new_socket(fd[0], proc_type, get_sys_pid()); + (void) nsfw_mgr_new_socket(fd[1], proc_type, get_sys_pid()); + (void) nsfw_mgr_reg_sock_fun(fd[0], nsfw_mgr_new_msg); + (void) nsfw_mgr_reg_sock_fun(fd[1], nsfw_mgr_new_msg); + if (proc_type != NSFW_PROC_CTRL) + { + NSFW_LOGINF("create local socket]fd0=%d,fd1=%d", fd[0], fd[1]); + } + return TRUE; } +/*try to get event form all modules */ + /***************************************************************************** * Prototype : nsfw_mgr_listen_thread * Description : epoll thread function @@ -1568,115 +1723,40 @@ nsfw_mgr_com_start_local (u8 proc_type) * Calls : * Called By : *****************************************************************************/ -void * -nsfw_mgr_listen_thread (void *arg) +void *nsfw_mgr_listen_thread(void *arg) { - i32 epfd = 0; - //i32 listen_socket = 0; - - lint_lock_1 (); #define MAXEVENTS 10 - epfd = nsfw_base_epoll_create (10); + struct epoll_event events[MAXEVENTS]; + + i32 epfd = g_ep_proc.epfd; - struct epoll_event events[MAXEVENTS]; - if (EOK != MEMSET_S (events, sizeof (events), 0, sizeof (events))) + /* Init log suppression for this thread */ + if (NULL == init_sup_table(LOG_SUP_TABLE_SIZE_FOR_MGR_COM_THREAD)) { - NSFW_LOGERR ("MEMSET_S failed!]epfd=%d", epfd); - lint_unlock_1 (); - return NULL; + NSFW_LOGWAR("log suppression init failed in thread: %s", + NSFW_MGRCOM_THREAD); } - g_ep_proc.epfd = epfd; - g_ep_proc.hbt_count = 0; - (void) nsfw_sock_add_to_ep (epfd); - lint_unlock_1 (); - while (1) + while (1) { - lint_lock_1 (); - int n, i; - n = nsfw_base_epoll_wait (epfd, events, MAXEVENTS, -1); - for (i = 0; i < n; i++) + int n, i; + n = nsfw_base_epoll_wait(epfd, events, MAXEVENTS, -1); + for (i = 0; i < n; i++) { - if (TRUE == - nsfw_sock_fun_callback (epfd, events[i].data.fd, - events[i].events)) + if (TRUE == + nsfw_sock_fun_callback(epfd, events[i].data.fd, + events[i].events)) { - g_ep_proc.hbt_count = 0; - continue; + g_ep_proc.hbt_count = 0; /*, we know here has multi-thread case, but we allow it */ + continue; } - NSFW_LOGERR ("error event recv] fd=%d,event=%d", - events[i].data.fd, events[i].events); + NSFW_LOGERR("error event recv]fd=%d,event=%u", events[i].data.fd, + events[i].events); } - lint_unlock_1 (); - } - -} - -NSTACK_STATIC inline void -get_thread_policy (pthread_attr_t * attr) -{ - int policy; - int rs = pthread_attr_getschedpolicy (attr, &policy); - if (rs != 0) - { - NSFW_LOGERR ("pthread_attr_getschedpolicy failed"); - return; - } - switch (policy) - { - case SCHED_FIFO: - NSFW_LOGINF ("policy= SCHED_FIFO"); - break; - case SCHED_RR: - NSFW_LOGINF ("policy= SCHED_RR"); - break; - case SCHED_OTHER: - NSFW_LOGINF ("policy=SCHED_OTHER"); - break; - default: - NSFW_LOGINF ("policy=UNKNOWN"); - break; - } - - return; -} -NSTACK_STATIC inline void -get_thread_priority (pthread_attr_t * attr) -{ - struct sched_param param; - int rs = pthread_attr_getschedparam (attr, ¶m); - if (rs != 0) - { - NSFW_LOGERR ("pthread_attr_getschedparam failed"); - return; } - NSFW_LOGINF ("get thread priority] pri=%d", param.sched_priority); -} - -/* support thread priority configuration */ -void -set_thread_attr (pthread_attr_t * pattr, int stacksize, int pri, int policy) -{ - struct sched_param param; - (void) pthread_attr_init (pattr); - - if (stacksize > 0) - { - (void) pthread_attr_setstacksize (pattr, stacksize); - } - - param.sched_priority = pri; - if (SCHED_OTHER != policy) - { - (void) pthread_attr_setschedpolicy (pattr, policy); - (void) pthread_attr_setschedparam (pattr, ¶m); - (void) pthread_attr_setinheritsched (pattr, PTHREAD_EXPLICIT_SCHED); - } - get_thread_policy (pattr); - get_thread_priority (pattr); } /***************************************************************************** @@ -1688,66 +1768,71 @@ set_thread_attr (pthread_attr_t * pattr, int stacksize, int pri, int policy) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_mgr_ep_start () +u8 nsfw_mgr_ep_start() { - /* heart beat thread should have the same priority with the tcpip thread */ - pthread_attr_t attr; - pthread_attr_t *pattr = NULL; + pthread_attr_t *pattr = NULL; - if (g_thread_policy != SCHED_OTHER) + /* move this code snippet from nsfw_mgr_listen_thread to here, + * to avoid multi-thread problem when calling nsfw_add_prestored_sock_to_ep in nsfw_mgr_listen_thread*/ + g_ep_proc.epfd = nsfw_base_epoll_create(10); + if (g_ep_proc.epfd <= 0) { - set_thread_attr (&attr, 0, g_thread_pri, g_thread_policy); - pattr = &attr; + NSFW_LOGERR("epoll_create fail]epfd=%d,errno=%d", g_ep_proc.epfd, + errno); + return FALSE; } + g_ep_proc.hbt_count = 0; - if (pthread_create - (&g_ep_proc.ep_thread, pattr, nsfw_mgr_listen_thread, NULL)) + if (FALSE == nsfw_add_prestored_sock_to_ep()) { - return FALSE; + return FALSE; } - NSFW_LOGINF ("start thread] id=%d", g_ep_proc.ep_thread); + if (pthread_create + (&g_ep_proc.ep_thread, pattr, nsfw_mgr_listen_thread, NULL)) + { + return FALSE; + } - if (pthread_setname_np (g_ep_proc.ep_thread, NSFW_MGRCOM_THREAD)) + NSFW_LOGINF("start thread]id=%d", g_ep_proc.ep_thread); + + if (pthread_setname_np(g_ep_proc.ep_thread, NSFW_MGRCOM_THREAD)) { - return TRUE; + return TRUE; } - (void) nsfw_reg_trace_thread (g_ep_proc.ep_thread); - return TRUE; + (void) nsfw_reg_trace_thread(g_ep_proc.ep_thread); + return TRUE; } -int -nsfw_mgr_com_chk_hbt (int v_add) +int nsfw_mgr_com_chk_hbt(int v_add) { - int ret = g_ep_proc.hbt_count; - g_ep_proc.hbt_count += v_add; - return ret; + int ret = g_ep_proc.hbt_count; + g_ep_proc.hbt_count += v_add; + return ret; } /***************************************************************************** * Prototype : nsfw_mgr_comm_fd_destroy -* Description : free the memory +* Description : free the memeory * Input : * Output : None * Return Value : int * Calls : * Called By : *****************************************************************************/ -void -nsfw_mgr_comm_fd_destroy () +void nsfw_mgr_comm_fd_destroy() { - if (g_ep_proc.ep_fun) + if (g_ep_proc.ep_fun) { - free (g_ep_proc.ep_fun); - g_ep_proc.ep_fun = NULL; + free(g_ep_proc.ep_fun); + g_ep_proc.ep_fun = NULL; } - if (g_mgr_socket_map.sock) + if (g_mgr_sockt_map.sock) { - free (g_mgr_socket_map.sock); - g_mgr_socket_map.sock = NULL; + free(g_mgr_sockt_map.sock); + g_mgr_sockt_map.sock = NULL; } - return; + return; } /***************************************************************************** @@ -1759,115 +1844,91 @@ nsfw_mgr_comm_fd_destroy () * Calls : * Called By : *****************************************************************************/ -int -nsfw_mgr_comm_fd_init (u32 proc_type) +int nsfw_mgr_comm_fd_init(u32 proc_type) { - /*only app need to do this */ - if ((g_mgr_socket_map.sock) && (g_ep_proc.ep_fun)) + /*distributed log collect, RANCU multi-nodes senario, nstack fd is limited to 1024, + this leads to DLOG SERVER container can't accept new connection, log can't be record normally. + maxfd limit to 60k begin */ + /*only app need to do this */ + errno_t err_ret = -1; + + if ((g_mgr_sockt_map.sock) && (g_ep_proc.ep_fun)) { - return 0; + return 0; } - if (NSFW_PROC_APP == proc_type) + if (NSFW_PROC_APP == proc_type) { - long sysfdmax = 0; - sysfdmax = sysconf (_SC_OPEN_MAX); - NSFW_LOGINF ("] sys max open files=%d", sysfdmax); - if (sysfdmax > 0) + long sysfdmax = 0; + sysfdmax = sysconf(_SC_OPEN_MAX); + NSFW_LOGINF("sys max open files]fds=%ld", sysfdmax); + if (sysfdmax > 0) { - NSFW_MGR_FD_MAX = - (int) ((sysfdmax <= - NSFW_MGRCOM_MAX_SOCKET * - 60) ? sysfdmax : NSFW_MGRCOM_MAX_SOCKET * 60); + NSFW_MGR_FD_MAX = + (int) ((sysfdmax <= + NSFW_MGRCOM_MAX_SOCKET * + 60) ? sysfdmax : NSFW_MGRCOM_MAX_SOCKET * 60); } - else + else { - NSFW_LOGERR ("get sys max open file fail"); - NSFW_MGR_FD_MAX = NSFW_MGRCOM_MAX_SOCKET; + NSFW_LOGERR("get sys max open file fail"); + NSFW_MGR_FD_MAX = NSFW_MGRCOM_MAX_SOCKET; } } - NSFW_LOGINF ("] final max fd=%d", NSFW_MGR_FD_MAX); - if (!g_mgr_socket_map.sock) + /* distributed log collect, RANCU multi-nodes senario, nstack fd is limited to 1024, + this leads to DLOG SERVER container can't accept new connection, log can't be record normally. + maxfd limit to 60k end */ + if (proc_type != NSFW_PROC_CTRL) { - g_mgr_socket_map.sock = - (nsfw_mgr_sock_info *) malloc (sizeof (nsfw_mgr_sock_info) * - NSFW_MGR_FD_MAX); - if (NULL == g_mgr_socket_map.sock) - { - NSFW_LOGERR ("malloc fail] length=%d", - sizeof (nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX); - return -1; - } - (void) MEMSET_S (g_mgr_socket_map.sock, - sizeof (nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX, 0, - sizeof (nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX); + NSFW_LOGINF("final]max fd=%d", NSFW_MGR_FD_MAX); } - if (!g_ep_proc.ep_fun) + + if (!g_mgr_sockt_map.sock) { - g_ep_proc.ep_fun = - (nsfw_mgr_sock_fun *) malloc (sizeof (nsfw_mgr_sock_fun) * - NSFW_MGR_FD_MAX); - if (NULL == g_ep_proc.ep_fun) + g_mgr_sockt_map.sock = + (nsfw_mgr_sock_info *) malloc(sizeof(nsfw_mgr_sock_info) * + NSFW_MGR_FD_MAX); + if (NULL == g_mgr_sockt_map.sock) { - NSFW_LOGERR ("malloc fail] length=%d ", - sizeof (nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX); - return -1; + NSFW_LOGERR("malloc fail]length=%d", + sizeof(nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX); + return -1; + } + err_ret = + memset_s(g_mgr_sockt_map.sock, + sizeof(nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX, 0, + sizeof(nsfw_mgr_sock_info) * NSFW_MGR_FD_MAX); + if (EOK != err_ret) + { + NSFW_LOGERR("memset_s fail]err_ret=%d", err_ret); + goto error; } - (void) MEMSET_S (g_ep_proc.ep_fun, - sizeof (nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX, 0, - sizeof (nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX); } - return 0; -} - -/***************************************************************************** -* Prototype : nsfw_mgr_com_mkdir_domainpath -* Description : check whether the domain path exist.if not exist, create it. -* Input : char *pathname -* Output : None -* Return Value : void -* Calls : -* Called By : -*****************************************************************************/ -void -nsfw_mgr_com_mkdir_domainpath (char *pathname) -{ - char dirname[NSFW_MGRCOM_PATH_LEN] = { 0 }; - int i, len; - if (NULL == pathname) + if (!g_ep_proc.ep_fun) { - NSFW_LOGERR ("the pathname is null."); - return; - } - - strncpy (dirname, pathname, NSFW_MGRCOM_PATH_LEN - 1); - len = strlen (dirname); - if (dirname[len - 1] != '/') - strncat (dirname, "/", 2); - - if (access (dirname, F_OK) == 0) - return; - - len = strlen (dirname); - - for (i = 1; i < len; i++) - { - if (dirname[i] == '/') + g_ep_proc.ep_fun = + (nsfw_mgr_sock_fun *) malloc(sizeof(nsfw_mgr_sock_fun) * + NSFW_MGR_FD_MAX); + if (NULL == g_ep_proc.ep_fun) { - dirname[i] = 0; - if (access (dirname, F_OK) != 0) - { - if (mkdir (dirname, 0755) == -1) - { - NSFW_LOGERR ("mkdir:%s error", dirname); - return; - } - } - dirname[i] = '/'; + NSFW_LOGERR("malloc fail] length=%d ", + sizeof(nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX); + goto error; + } + err_ret = + memset_s(g_ep_proc.ep_fun, + sizeof(nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX, 0, + sizeof(nsfw_mgr_sock_fun) * NSFW_MGR_FD_MAX); + if (EOK != err_ret) + { + NSFW_LOGERR("memset_s fail]err_ret=%d", err_ret); + goto error; } } - - return; + return 0; + error: + nsfw_mgr_comm_fd_destroy(); + return -1; } /***************************************************************************** @@ -1879,129 +1940,155 @@ nsfw_mgr_com_mkdir_domainpath (char *pathname) * Calls : * Called By : *****************************************************************************/ -int nsfw_mgr_com_module_init (void *param); -int -nsfw_mgr_com_module_init (void *param) +/*try to get event form all modules */ +int nsfw_mgr_com_module_init(void *param); +int nsfw_mgr_com_module_init(void *param) { - lint_lock_1 (); - u32 proc_type = (u32) ((long long) param); - nsfw_mgr_init_cfg *mgr_cfg = &g_mgr_com_cfg; - const char *directory = NSFW_DOMAIN_DIR; - const char *home_dir = getenv ("HOME"); + u32 proc_type = (u32) ((long long) param); + nsfw_mgr_init_cfg *mgr_cfg = &g_mgr_com_cfg; + const char *directory = NSFW_DOMAIN_DIR; + const char *home_dir = get_home_path(); - NSFW_LOGINF ("module mgr init] type=%u", proc_type); + NSFW_LOGINF("module mgr init]type=%u", proc_type); - if (getuid () != 0 && home_dir != NULL) - directory = home_dir; + if (home_dir) + { + directory = home_dir; + } - if (0 != nsfw_mgr_comm_fd_init (proc_type)) + if (0 != nsfw_mgr_comm_fd_init(proc_type)) { - NSFW_LOGERR ("fd init fail] proc_type=%u", proc_type); - lint_unlock_1 (); - return -1; + NSFW_LOGERR("fd init fail]proc_type=%u", proc_type); + return -1; } - switch (proc_type) + switch (proc_type) { - case NSFW_PROC_MAIN: - /* modify destMax, remove "-1" */ - if (EOK != - STRCPY_S (mgr_cfg->domain_path, NSFW_MGRCOM_PATH_LEN, directory)) - { - NSFW_LOGERR ("module mgr init STRCPY_S failed!"); - lint_unlock_1 (); - return -1; - } + case NSFW_PROC_MAIN: + /*modify destMax, remove "-1" */ + if (EOK != + strcpy_s(mgr_cfg->domain_path, NSFW_MGRCOM_PATH_LEN, + directory)) + { + NSFW_LOGERR("module mgr init strcpy_s fail"); + return -1; + } - nsfw_mgr_com_mkdir_domainpath (mgr_cfg->domain_path); + /*modify destMax, remove "-1" */ + if (EOK != + strcat_s(mgr_cfg->domain_path, NSFW_MGRCOM_PATH_LEN, + NSFW_MAIN_FILE)) + { + NSFW_LOGERR("module mgr init strcat_s fail"); + return -1; + } - NSFW_LOGINF ("module mgr init]NSFW_PROC_MAIN domain_path=%s", - mgr_cfg->domain_path); + NSFW_LOGINF("module mgr init]NSFW_PROC_MAIN domain_path=%s", + mgr_cfg->domain_path); - if (TRUE != nsfw_mgr_com_start ()) - { - NSFW_LOGERR ("module mgr nsfw_mgr_com_start failed!"); - lint_unlock_1 (); - return -1; - } + if (TRUE != nsfw_mgr_com_start()) + { + NSFW_LOGERR("module mgr nsfw_mgr_com_start fail"); + return -1; + } - break; + break; + case NSFW_PROC_MASTER: + /* modify destMax, remove "-1" */ + if (EOK != + strcpy_s(mgr_cfg->domain_path, NSFW_MGRCOM_PATH_LEN, + directory)) + { + NSFW_LOGERR("module mgr init strcpy_s fail"); + return -1; + } - case NSFW_PROC_TOOLS: - break; - case NSFW_PROC_CTRL: - if (TRUE != nsfw_mgr_com_start_local (proc_type)) - { - NSFW_LOGERR ("module mgr nsfw_mgr_com_start_local failed!"); - lint_unlock_1 (); - return -1; - } - break; - default: - if (proc_type < NSFW_PROC_MAX) - { - break; - } - lint_unlock_1 (); - return -1; + /* modify destMax, remove "-1" */ + if (EOK != + strcat_s(mgr_cfg->domain_path, NSFW_MGRCOM_PATH_LEN, + NSFW_MASTER_FILE)) + { + NSFW_LOGERR("module mgr init strcat_s fail"); + return -1; + } + + NSFW_LOGINF("module mgr init]NSFW_PROC_MASTER domain_path=%s", + mgr_cfg->domain_path); + + if (TRUE != nsfw_mgr_com_start()) + { + NSFW_LOGERR("module mgr nsfw_mgr_com_start fail"); + return -1; + } + + break; + case NSFW_PROC_TOOLS: + case NSFW_PROC_CTRL: + if (TRUE != nsfw_mgr_com_start_local(proc_type)) + { + NSFW_LOGERR("module mgr nsfw_mgr_com_start_local fail"); + return -1; + } + break; + default: + if (proc_type < NSFW_PROC_MAX) + { + break; + } + return -1; } - mgr_cfg->msg_size = MGR_COM_MSG_COUNT_DEF; - mgr_cfg->max_recv_timeout = MGR_COM_RECV_TIMEOUT_DEF; - mgr_cfg->max_recv_drop_msg = MGR_COM_MAX_DROP_MSG_DEF; + mgr_cfg->msg_size = MGR_COM_MSG_COUNT_DEF; + mgr_cfg->max_recv_timeout = MGR_COM_RECV_TIMEOUT_DEF; + mgr_cfg->max_recv_drop_msg = MGR_COM_MAX_DROP_MSG_DEF; - mgr_cfg->proc_type = proc_type; + mgr_cfg->proc_type = proc_type; - nsfw_mem_sppool pmpinfo; - if (EOK != MEMSET_S (&pmpinfo, sizeof (pmpinfo), 0, sizeof (pmpinfo))) + nsfw_mem_sppool pmpinfo; + if (EOK != memset_s(&pmpinfo, sizeof(pmpinfo), 0, sizeof(pmpinfo))) { - NSFW_LOGERR ("Error to memset!!!"); - nsfw_mgr_comm_fd_destroy (); - lint_unlock_1 (); - return -1; + NSFW_LOGERR("memset fail"); + nsfw_mgr_comm_fd_destroy(); + return -1; } - pmpinfo.enmptype = NSFW_MRING_MPMC; - pmpinfo.usnum = mgr_cfg->msg_size; - pmpinfo.useltsize = sizeof (nsfw_mgr_msg); - pmpinfo.isocket_id = NSFW_SOCKET_ANY; - pmpinfo.stname.entype = NSFW_NSHMEM; - if (-1 == - SPRINTF_S (pmpinfo.stname.aname, sizeof (pmpinfo.stname.aname), "%s", - "MS_MGR_MSGPOOL")) + pmpinfo.enmptype = NSFW_MRING_MPMC; + pmpinfo.usnum = mgr_cfg->msg_size; + pmpinfo.useltsize = sizeof(nsfw_mgr_msg); + pmpinfo.isocket_id = NSFW_SOCKET_ANY; + pmpinfo.stname.entype = NSFW_NSHMEM; + if (-1 == + sprintf_s(pmpinfo.stname.aname, sizeof(pmpinfo.stname.aname), "%s", + "MS_MGR_MSGPOOL")) { - NSFW_LOGERR ("Error to SPRINTF_S!!!"); - nsfw_mgr_comm_fd_destroy (); - lint_unlock_1 (); - return -1; + NSFW_LOGERR("sprintf_s fail"); + nsfw_mgr_comm_fd_destroy(); + return -1; } - mgr_cfg->msg_pool = nsfw_mem_sp_create (&pmpinfo); + mgr_cfg->msg_pool = nsfw_mem_sp_create(&pmpinfo); - if (!mgr_cfg->msg_pool) + if (!mgr_cfg->msg_pool) { - NSFW_LOGERR ("module mgr init msg_pool alloc failed!"); - nsfw_mgr_comm_fd_destroy (); - lint_unlock_1 (); - return -1; + NSFW_LOGERR("module mgr init msg_pool alloc fail"); + nsfw_mgr_comm_fd_destroy(); + return -1; } - (void) MEM_STAT (NSFW_MGR_COM_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, - nsfw_mem_get_len (mgr_cfg->msg_pool, NSFW_MEM_SPOOL)); + (void) MEM_STAT(NSFW_MGR_COM_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, + nsfw_mem_get_len(mgr_cfg->msg_pool, NSFW_MEM_SPOOL)); - if ((NSFW_PROC_TOOLS == proc_type) - || (NSFW_PROC_CTRL == proc_type) || (NSFW_PROC_MAIN == proc_type)) + if ((NSFW_PROC_TOOLS == proc_type) + || (NSFW_PROC_CTRL == proc_type) || (NSFW_PROC_MAIN == proc_type)) { - if (TRUE != nsfw_mgr_ep_start ()) + if (TRUE != nsfw_mgr_ep_start()) { - NSFW_LOGERR ("module mgr nsfw_mgr_ep_start failed!"); - nsfw_mgr_comm_fd_destroy (); - lint_unlock_1 (); - return -1; + NSFW_LOGERR("module mgr nsfw_mgr_ep_start fail"); + nsfw_mgr_comm_fd_destroy(); + return -1; } } - lint_unlock_1 (); - return 0; + return 0; } /***************************************************************************** @@ -2012,37 +2099,36 @@ nsfw_mgr_com_module_init (void *param) * Return Value : int * Calls : * Called By : - *****************************************************************************/ -int -nsfw_mgr_run_script (const char *cmd, char *result, int result_buf_len) +*****************************************************************************/ +int nsfw_mgr_run_script(const char *cmd, char *result, int result_buf_len) { - if (!cmd || !result || result_buf_len <= 1) + if (!cmd || !result || result_buf_len <= 1) { - return -1; + return -1; } - FILE *fp = popen (cmd, "r"); - if (fp != NULL) + FILE *fp = popen(cmd, "r"); + if (fp != NULL) { - size_t n = fread (result, sizeof (char), result_buf_len - 1, fp); - if (n == 0) + size_t n = fread(result, sizeof(char), result_buf_len - 1, fp); + if (n == 0) { - result[0] = '\0'; + result[0] = '\0'; } - else if ('\n' == result[n - 1]) + else if ('\n' == result[n - 1]) { - result[n - 1] = '\0'; + result[n - 1] = '\0'; } - else + else { - result[n] = '\0'; + result[n] = '\0'; } - pclose (fp); - return n; + pclose(fp); + return n; } - return -1; + return -1; } /* *INDENT-OFF* */ diff --git a/src/framework/ipc/mgr_com/mgr_com.h b/src/framework/ipc/mgr_com/mgr_com.h index 03f58c8..0011716 100644 --- a/src/framework/ipc/mgr_com/mgr_com.h +++ b/src/framework/ipc/mgr_com/mgr_com.h @@ -14,23 +14,13 @@ * limitations under the License. */ -/***************************************************************************** -* Prototype : ifndef _NSFW_MGRCOM_MODULE_H -* Description : mgr com module definition -* Input : None -* Output : None -* Return Value : # -* Calls : -* Called By : - *****************************************************************************/ #ifndef _NSFW_MGRCOM_MODULE_H #define _NSFW_MGRCOM_MODULE_H #include "pthread.h" #include "nsfw_mem_api.h" -#include "common_mem_api.h" -#include "common_mem_memzone.h" -#include "common_func.h" +#include "dmm_spinlock.h" +#include "dmm_atomic.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -47,100 +37,96 @@ extern "C"{ #define MGR_COM_MSG_COUNT_DEF 1023 /*g_mgr_com_cfg */ #define MGR_COM_RECV_TIMEOUT_DEF 5 #define MGR_COM_MAX_DROP_MSG_DEF 1024 +#define MGR_COM_SEND_TIMEOUT_DEF 5 #define MGR_COM_MSG_COUNT (g_mgr_com_cfg.msg_size) #define MGR_COM_RECV_TIMEOUT (g_mgr_com_cfg.max_recv_timeout) #define MGR_COM_MAX_DROP_MSG (g_mgr_com_cfg.max_recv_drop_msg) -#define NSFW_MAIN_FILE "nStackMainMgr" -#define NSFW_MASTER_FILE "nStackMasterMgr" +#define NSFW_MAIN_FILE "/ip_module/nStackMainMgr" +#define NSFW_MASTER_FILE "/ip_module/nStackMasterMgr" #define NSFW_ALARM_FILE "/HuskyAlarm.domain" -#define NSFW_MGRCOM_THREAD "nStackMgrCom" +#define NSFW_MGRCOM_THREAD "nstk_mgr_com" typedef struct _nsfw_mgr_init_cfg { - u8 proc_type; /*fw_poc_type */ - u8 max_recv_timeout; - u16 max_recv_drop_msg; - u32 msg_size; - common_mem_atomic32_t cur_idx; - u64 u64reserve; - mring_handle msg_pool; - char domain_path[NSFW_MGRCOM_PATH_LEN]; + u8 proc_type; /*fw_poc_type */ + u8 max_recv_timeout; + u16 max_recv_drop_msg; + u32 msg_size; + dmm_atomic_t cur_idx; + u64 u64reserve; + mring_handle msg_pool; + char domain_path[NSFW_MGRCOM_PATH_LEN]; } nsfw_mgr_init_cfg; typedef struct _nsfw_mgrcom_stat { - u64 msg_send[MGR_MSG_MAX]; - u64 msg_recv[MGR_MSG_MAX]; - u64 recv_drop[MGR_MSG_MAX]; - u64 msg_alloc; - u64 msg_free; - u64 msg_send_failed; - u64 reconnect_count; + u64 msg_send[MGR_MSG_MAX]; + u64 msg_recv[MGR_MSG_MAX]; + u64 recv_drop[MGR_MSG_MAX]; + u64 msg_alloc; + u64 msg_free; + u64 msg_send_failed; + u64 reconnect_count; } nsfw_mgrcom_stat; typedef struct _nsfw_mgr_sock_info { - u8 proc_type; /*_ns_poc_type*/ - u32 host_pid; - common_mem_spinlock_t opr_lock; + u8 proc_type; /*_ns_poc_type*/ + u32 host_pid; + dmm_spinlock_t opr_lock; } nsfw_mgr_sock_info; typedef struct _nsfw_mgr_sock_map { - i32 proc_cache[NSFW_PROC_MAX]; - nsfw_mgr_sock_info *sock; + i32 proc_cache[NSFW_PROC_MAX]; + nsfw_mgr_sock_info *sock; } nsfw_mgr_sock_map; #define NSFW_SOCK_MAX_PROC_FUN 4 typedef struct _nsfw_mgrcom_proc_fun { - i32 fd; - nsfw_mgr_sock_fun fun; + i32 fd; + nsfw_mgr_sock_fun fun; } nsfw_mgrcom_proc_fun; typedef struct _nsfw_mgrcom_proc { - i32 epfd; - u32 hbt_count; - pthread_t ep_thread; - nsfw_mgr_sock_fun *ep_fun; + i32 epfd; + u32 hbt_count; + pthread_t ep_thread; + nsfw_mgr_sock_fun *ep_fun; } nsfw_mgrcom_proc; -i32 nsfw_set_sock_block (i32 sock, u8 flag); +i32 nsfw_set_sock_block(i32 sock, u8 flag); -u8 nsfw_rmv_sock_from_ep (i32 fd); -u8 nsfw_add_sock_to_ep (i32 fd); +u8 nsfw_rmv_sock_from_ep(i32 fd); +u8 nsfw_add_sock_to_ep(i32 fd); -int nsfw_mgr_new_msg (i32 epfd, i32 socket, u32 events); +int nsfw_mgr_new_msg(i32 epfd, i32 socket, u32 events); -u8 nsfw_mgr_ep_start (); -u8 nsfw_mgr_stop (); +u8 nsfw_mgr_ep_start(); +u8 nsfw_mgr_stop(); #define LOCK_MGR_FD(_fd){\ - if ((i32)NSFW_MGR_FD_MAX > _fd)\ + if ((i32)NSFW_MGR_FD_MAX > _fd && g_mgr_sockt_map.sock)\ {\ - common_mem_spinlock_lock(&g_mgr_socket_map.sock[_fd].opr_lock);\ + dmm_spin_lock(&g_mgr_sockt_map.sock[_fd].opr_lock);\ }\ } #define UNLOCK_MGR_FD(_fd){\ - if ((i32)NSFW_MGR_FD_MAX > _fd)\ + if ((i32)NSFW_MGR_FD_MAX > _fd && g_mgr_sockt_map.sock)\ {\ - common_mem_spinlock_unlock(&g_mgr_socket_map.sock[_fd].opr_lock);\ + dmm_spin_unlock(&g_mgr_sockt_map.sock[_fd].opr_lock);\ }\ } #define NSFW_MGR_FD_MAX g_mgr_sockfdmax -extern void set_thread_attr (pthread_attr_t * pattr, int stacksize, int pri, - int policy); - -extern void nsfw_com_attr_set (int policy, int pri); - #ifdef __cplusplus /* *INDENT-OFF* */ } diff --git a/src/framework/ipc/ps/nsfw_fd_timer.c b/src/framework/ipc/ps/nsfw_fd_timer.c index cea2486..fc71748 100644 --- a/src/framework/ipc/ps/nsfw_fd_timer.c +++ b/src/framework/ipc/ps/nsfw_fd_timer.c @@ -22,10 +22,8 @@ #include "types.h" #include "list.h" -#include "common_mem_common.h" - #include "nstack_securec.h" -#include "nsfw_init.h" +#include "nsfw_init_api.h" #include "nsfw_mgr_com_api.h" #include "nsfw_mem_api.h" #include "nstack_log.h" @@ -42,11 +40,10 @@ extern "C"{ #define NSFW_TIMER_CYCLE 1 #define NSFW_TIMER_INFO_MAX_COUNT_DEF 8191 #define NSFW_TIMER_INFO_MAX_COUNT (g_timer_cfg.timer_info_size) -/* *INDENT-OFF* */ + nsfw_timer_init_cfg g_timer_cfg; u8 g_hbt_switch = FALSE; -/* *INDENT-ON* */ /***************************************************************************** * Prototype : nsfw_timer_reg_timer @@ -59,38 +56,39 @@ u8 g_hbt_switch = FALSE; * Return Value : nsfw_timer_info* * Calls : * Called By : -* *****************************************************************************/ -nsfw_timer_info * -nsfw_timer_reg_timer (u32 timer_type, void *data, - nsfw_timer_proc_fun fun, struct timespec time_left) +nsfw_timer_info *nsfw_timer_reg_timer(u32 timer_type, void *data, + nsfw_timer_proc_fun fun, + struct timespec time_left) { - nsfw_timer_info *tm_info = NULL; - if (0 == - nsfw_mem_ring_dequeue (g_timer_cfg.timer_info_pool, (void *) &tm_info)) + nsfw_timer_info *tm_info = NULL; + if (0 == + nsfw_mem_ring_dequeue(g_timer_cfg.timer_info_pool, (void *) &tm_info)) { - NSFW_LOGERR ("dequeue error]data=%p,fun=%p", data, fun); - return NULL; + NSFW_LOGERR("dequeue error]data=%p,fun=%p", data, fun); + return NULL; } - if (EOK != MEMSET_S (tm_info, sizeof (*tm_info), 0, sizeof (*tm_info))) + if (EOK != memset_s(tm_info, sizeof(*tm_info), 0, sizeof(*tm_info))) { - if (0 == nsfw_mem_ring_enqueue (g_timer_cfg.timer_info_pool, tm_info)) + if (0 == nsfw_mem_ring_enqueue(g_timer_cfg.timer_info_pool, tm_info)) { - NSFW_LOGERR ("enqueue error]data=%p,fun=%p", data, fun); + NSFW_LOGERR("enqueue error]data=%p,fun=%p", data, fun); } - NSFW_LOGERR ("mem set error]data=%p,fun=%p", data, fun); - return NULL; + NSFW_LOGERR("mem set error]data=%p,fun=%p", data, fun); + return NULL; } - tm_info->fun = fun; - tm_info->argv = data; - tm_info->time_left = time_left; - //tm_info->time_left.tv_sec += NSFW_TIMER_CYCLE; - tm_info->timer_type = timer_type; - list_add_tail (&tm_info->node, &g_timer_cfg.timer_head); - tm_info->alloc_flag = TRUE; - return tm_info; + tm_info->fun = fun; + tm_info->argv = data; + tm_info->time_left = time_left; + tm_info->timer_type = timer_type; + tm_info->alloc_flag = TRUE; + /* it can start timer after only finish all timer reg, or else it have multi-thread issue */ + dmm_spin_lock(&g_timer_cfg.timer_lock); + list_add_tail(&tm_info->node, &g_timer_cfg.timer_head); + dmm_spin_unlock(&g_timer_cfg.timer_lock); + return tm_info; } /***************************************************************************** @@ -101,32 +99,34 @@ nsfw_timer_reg_timer (u32 timer_type, void *data, * Return Value : void * Calls : * Called By : -* *****************************************************************************/ -void -nsfw_timer_rmv_timer (nsfw_timer_info * tm_info) +void nsfw_timer_rmv_timer(nsfw_timer_info * tm_info) { - if (NULL == tm_info) + if (NULL == tm_info) { - NSFW_LOGWAR ("tm_info nul"); - return; + NSFW_LOGWAR("tm_info nul"); + return; } + /* it can start timer after only finish all timer reg, or else it have multi-thread issue */ + dmm_spin_lock(&g_timer_cfg.timer_lock); - if (FALSE == tm_info->alloc_flag) + if (FALSE == tm_info->alloc_flag) { - NSFW_LOGERR ("tm_info refree]tm_info=%p,argv=%p,fun=%p", tm_info, - tm_info->argv, tm_info->fun); - return; + dmm_spin_unlock(&g_timer_cfg.timer_lock); + NSFW_LOGERR("tm_info refree]tm_info=%p,argv=%p,fun=%p", tm_info, + tm_info->argv, tm_info->fun); + return; } - tm_info->alloc_flag = FALSE; - list_del (&tm_info->node); - if (0 == nsfw_mem_ring_enqueue (g_timer_cfg.timer_info_pool, tm_info)) + tm_info->alloc_flag = FALSE; + list_del(&tm_info->node); + if (0 == nsfw_mem_ring_enqueue(g_timer_cfg.timer_info_pool, tm_info)) { - NSFW_LOGERR ("tm_info free failed]tm_info=%p,argv=%p,fun=%p", tm_info, - tm_info->argv, tm_info->fun); + NSFW_LOGERR("tm_info free failed]tm_info=%p,argv=%p,fun=%p", tm_info, + tm_info->argv, tm_info->fun); } - return; + dmm_spin_unlock(&g_timer_cfg.timer_lock); + return; } /***************************************************************************** @@ -137,41 +137,59 @@ nsfw_timer_rmv_timer (nsfw_timer_info * tm_info) * Return Value : u8 * Calls : * Called By : -* *****************************************************************************/ -void -nsfw_timer_exp (u64 count) +void nsfw_timer_exp(u64 count) { - nsfw_timer_info *tm_info = NULL; - struct list_head *tNode; - struct list_head *tPretNode; - - LINT_LIST ()list_for_each_entry (tm_info, tNode, (&g_timer_cfg.timer_head), - node) - { - tPretNode = tm_info->node.prev; - if (tm_info->time_left.tv_sec > (long) count * NSFW_TIMER_CYCLE) - { - tm_info->time_left.tv_sec -= count * NSFW_TIMER_CYCLE; - continue; - } - - list_del (&tm_info->node); - list_add_tail (&tm_info->node, &g_timer_cfg.exp_timer_head); - tNode = tPretNode; - } - - u32 i = 0; - while (!list_empty (&g_timer_cfg.exp_timer_head) - && i++ < NSFW_TIMER_INFO_MAX_COUNT) + nsfw_timer_info *tm_info = NULL; + struct list_head *tNode; + struct list_head *tPretNode; + + /* it can start timer after only finish all timer reg, or else it have multi-thread issue */ + dmm_spin_lock(&g_timer_cfg.timer_lock); + + list_for_each_entry(tm_info, tNode, (&g_timer_cfg.timer_head), node) + { + + tPretNode = tm_info->node.prev; + if (tm_info->time_left.tv_sec > (long) count * NSFW_TIMER_CYCLE) + { + tm_info->time_left.tv_sec -= count * NSFW_TIMER_CYCLE; + continue; + } + + list_del(&tm_info->node); + list_add_tail(&tm_info->node, &g_timer_cfg.exp_timer_head); + tNode = tPretNode; + } + dmm_spin_unlock(&g_timer_cfg.timer_lock); + + u32 i = 0; + while (!list_empty(&g_timer_cfg.exp_timer_head) + && i++ < NSFW_TIMER_INFO_MAX_COUNT) { - tm_info = - (nsfw_timer_info *) list_get_first (&g_timer_cfg.exp_timer_head); - if (NULL != tm_info->fun) + dmm_spin_lock(&g_timer_cfg.timer_lock); + tm_info = + (nsfw_timer_info *) list_get_first(&g_timer_cfg.exp_timer_head); + if (NULL == tm_info) + { + dmm_spin_unlock(&g_timer_cfg.timer_lock); + continue; + } + tm_info->alloc_flag = FALSE; + list_del(&tm_info->node); + dmm_spin_unlock(&g_timer_cfg.timer_lock); + /* here can't lock that it is possible that the tm_info->fun call reg timer or remove timer, which will cause deadlock */ + if (NULL != tm_info->fun) + { + (void) tm_info->fun(tm_info->timer_type, tm_info->argv); + } + /* only after finish handle tm_info->fun, it can put it into timer_info_pool, avoid that it is applied by other timer */ + if (0 == nsfw_mem_ring_enqueue(g_timer_cfg.timer_info_pool, tm_info)) { - (void) tm_info->fun (tm_info->timer_type, tm_info->argv); + NSFW_LOGERR("tm_info free failed]tm_info=%p,argv=%p,fun=%p", + tm_info, tm_info->argv, tm_info->fun); } - nsfw_timer_rmv_timer (tm_info); + } } @@ -185,38 +203,32 @@ nsfw_timer_exp (u64 count) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_get_timer_socket () +i32 nsfw_get_timer_socket() { - i32 tfd = timerfd_create (CLOCK_MONOTONIC, TFD_NONBLOCK); - if (tfd == -1) + + i32 tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); + if (tfd == -1) { - NSFW_LOGERR ("timerfd_create failed!]errno=%d\n", errno); - return -1; + NSFW_LOGERR("timerfd_create failed!]errno=%d\n", errno); + return -1; } - /* close on exe */ - if (-1 == nsfw_set_close_on_exec (tfd)) + /* close on exec */ + if (-1 == nsfw_set_close_on_exec(tfd)) { - (void) nsfw_base_close (tfd); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", tfd, errno); - return -1; + (void) nsfw_base_close(tfd); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", tfd, errno); + return -1; } - struct itimerspec ts; - ts.it_interval.tv_sec = NSFW_TIMER_CYCLE; - ts.it_interval.tv_nsec = 0; - ts.it_value.tv_sec = 0; - ts.it_value.tv_nsec = NSFW_TIMER_CYCLE; - - if (timerfd_settime (tfd, 0, &ts, NULL) < 0) + if (timerfd_settime(tfd, 0, &g_timer_cfg.ts, NULL) < 0) { - NSFW_LOGERR ("timerfd_settime failed] errno=%d", errno); - close (tfd); - return -1; + NSFW_LOGERR("timerfd_settime failed] errno=%d", errno); + close(tfd); + return -1; } - return tfd; + return tfd; } /***************************************************************************** @@ -230,53 +242,52 @@ nsfw_get_timer_socket () * Calls : * Called By : *****************************************************************************/ -int -nsfw_timer_notify_fun (i32 epfd, i32 fd, u32 events) +int nsfw_timer_notify_fun(i32 epfd, i32 fd, u32 events) { - i32 rc; + i32 rc; - if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) + if ((events & EPOLLERR) || (events & EPOLLHUP) || (!(events & EPOLLIN))) { - (void) nsfw_base_close (fd); - NSFW_LOGWAR ("timer disconnect!]epfd=%d,timer=%d,event=0x%x", epfd, - fd, events); + (void) nsfw_base_close(fd); + NSFW_LOGWAR("timer disconnect!]epfd=%d,timer=%d,event=0x%x", epfd, + fd, events); - (void) nsfw_mgr_unreg_sock_fun (fd); - i32 timer_fd = nsfw_get_timer_socket (); - if (timer_fd < 0) + (void) nsfw_mgr_unreg_sock_fun(fd); + i32 timer_fd = nsfw_get_timer_socket(); + if (timer_fd < 0) { - NSFW_LOGERR ("get timer_fd failed!]epfd=%d,timer_fd=%d,event=0x%x", - epfd, fd, events); - return FALSE; + NSFW_LOGERR("get timer_fd faied!]epfd=%d,timer_fd=%d,event=0x%x", + epfd, fd, events); + return FALSE; } - (void) nsfw_mgr_reg_sock_fun (timer_fd, nsfw_timer_notify_fun); - return TRUE; + (void) nsfw_mgr_reg_sock_fun(timer_fd, nsfw_timer_notify_fun); + return TRUE; } - u64 data; - while (1) + u64 data; + while (1) { - rc = nsfw_base_read (fd, &data, sizeof (data)); - if (rc == 0) + rc = nsfw_base_read(fd, &data, sizeof(data)); + if (rc == 0) { - NSFW_LOGERR ("timer_fd recv 0]timer_fd=%d,errno=%d", fd, errno); - break; + NSFW_LOGERR("timer_fd recv 0]timer_fd=%d,errno=%d", fd, errno); + break; } - else if (rc == -1) + else if (rc == -1) { - if (errno == EINTR || errno == EAGAIN) + if (errno == EINTR || errno == EAGAIN) { - break; + break; } - NSMON_LOGERR ("timer_fd recv]timer_fd=%d,errno=%d", fd, errno); - break; + NSMON_LOGERR("timer_fd recv]timer_fd=%d,errno=%d", fd, errno); + break; } - nsfw_timer_exp (data); + nsfw_timer_exp(data); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -287,21 +298,19 @@ nsfw_timer_notify_fun (i32 epfd, i32 fd, u32 events) * Return Value : u8 * Calls : * Called By : -* *****************************************************************************/ -u8 -nsfw_timer_start () +u8 nsfw_timer_start() { - i32 timer_fd = nsfw_get_timer_socket (); - if (timer_fd < 0) + i32 timer_fd = nsfw_get_timer_socket(); + if (timer_fd < 0) { - NSFW_LOGERR ("get timer_fd failed!"); - return FALSE; + NSFW_LOGERR("get timer_fd fail"); + return FALSE; } - NSFW_LOGINF ("start timer_fd module!]timer_fd=%d", timer_fd); - (void) nsfw_mgr_reg_sock_fun (timer_fd, nsfw_timer_notify_fun); - return TRUE; + NSFW_LOGINF("start timer_fd module]timer_fd=%d", timer_fd); + (void) nsfw_mgr_reg_sock_fun(timer_fd, nsfw_timer_notify_fun); + return TRUE; } /***************************************************************************** @@ -312,64 +321,79 @@ nsfw_timer_start () * Return Value : int * Calls : * Called By : -* *****************************************************************************/ -int -nsfw_timer_module_init (void *param) +int nsfw_timer_module_init(void *param) { - u32 proc_type = (u32) ((long long) param); - nsfw_timer_init_cfg *timer_cfg = &g_timer_cfg; - NSFW_LOGINF ("ps module init]type=%u", proc_type); - switch (proc_type) + u32 proc_type = (u32) ((long long) param); + nsfw_timer_init_cfg *timer_cfg = &g_timer_cfg; + if (proc_type != NSFW_PROC_CTRL) { - case NSFW_PROC_MAIN: - (void) NSFW_REG_SOFT_INT (NSFW_DBG_MODE_PARAM, g_hbt_switch, 0, 1); - break; - case NSFW_PROC_TOOLS: - case NSFW_PROC_CTRL: - break; - default: - return 0; + NSFW_LOGINF("ps module init]type=%u", proc_type); } - timer_cfg->timer_info_size = NSFW_TIMER_INFO_MAX_COUNT_DEF; - - nsfw_mem_sppool pmpinfo; - pmpinfo.enmptype = NSFW_MRING_MPMC; - pmpinfo.usnum = timer_cfg->timer_info_size; - pmpinfo.useltsize = sizeof (nsfw_timer_info); - pmpinfo.isocket_id = NSFW_SOCKET_ANY; - pmpinfo.stname.entype = NSFW_NSHMEM; - if (-1 == - SPRINTF_S (pmpinfo.stname.aname, NSFW_MEM_NAME_LENGTH, "%s", - "MS_TM_INFOPOOL")) + /* The first expiration should be the same as the cyclic interval. This fixs the bug of skipping one beat */ + timer_cfg->ts.it_interval.tv_sec = NSFW_TIMER_CYCLE; + timer_cfg->ts.it_interval.tv_nsec = 0; + timer_cfg->ts.it_value.tv_sec = timer_cfg->ts.it_interval.tv_sec; + timer_cfg->ts.it_value.tv_nsec = timer_cfg->ts.it_interval.tv_nsec; + + switch (proc_type) { - NSFW_LOGERR ("SPRINTF_S failed"); - return -1; + case NSFW_PROC_MASTER: + /** For nMaster, we call nsfw_mgr_ep_start() after every other module is inited, + ** so the first expiration is set to 1 nanosecond for nMaster to bring up nMain ASAP */ + timer_cfg->ts.it_value.tv_sec = 0; + timer_cfg->ts.it_value.tv_nsec = 1; + case NSFW_PROC_MAIN: + (void) NSFW_REG_SOFT_INT(NSFW_DBG_MODE_PARAM, g_hbt_switch, 0, 1); + break; + case NSFW_PROC_TOOLS: + case NSFW_PROC_CTRL: + break; + default: + return 0; } - timer_cfg->timer_info_pool = nsfw_mem_sp_create (&pmpinfo); - if (!timer_cfg->timer_info_pool) + timer_cfg->timer_info_size = NSFW_TIMER_INFO_MAX_COUNT_DEF; + + nsfw_mem_sppool pmpinfo; + pmpinfo.enmptype = NSFW_MRING_MPMC; + pmpinfo.usnum = timer_cfg->timer_info_size; + pmpinfo.useltsize = sizeof(nsfw_timer_info); + pmpinfo.isocket_id = NSFW_SOCKET_ANY; + pmpinfo.stname.entype = NSFW_NSHMEM; + if (-1 == + sprintf_s(pmpinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + "MS_TM_INFOPOOL")) { - NSFW_LOGERR ("alloc timer info pool_err"); - return -1; + NSFW_LOGERR("sprintf_s fail"); + return -1; } + timer_cfg->timer_info_pool = nsfw_mem_sp_create(&pmpinfo); + + if (!timer_cfg->timer_info_pool) + { + NSFW_LOGERR("alloc timer info pool_err"); + return -1; + } + + MEM_STAT(NSFW_TIMER_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, + nsfw_mem_get_len(timer_cfg->timer_info_pool, NSFW_MEM_SPOOL)); - MEM_STAT (NSFW_TIMER_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, - nsfw_mem_get_len (timer_cfg->timer_info_pool, NSFW_MEM_SPOOL)); + INIT_LIST_HEAD(&(timer_cfg->timer_head)); + INIT_LIST_HEAD(&(timer_cfg->exp_timer_head)); - INIT_LIST_HEAD (&(timer_cfg->timer_head)); - INIT_LIST_HEAD (&(timer_cfg->exp_timer_head)); + dmm_spin_init(&g_timer_cfg.timer_lock); + (void) nsfw_timer_start(); - (void) nsfw_timer_start (); - return 0; + return 0; } /* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_TIMER_MODULE) -NSFW_MODULE_PRIORITY (10) -NSFW_MODULE_DEPENDS (NSFW_MGR_COM_MODULE) -NSFW_MODULE_INIT (nsfw_timer_module_init) +NSFW_MODULE_NAME(NSFW_TIMER_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_DEPENDS(NSFW_MGR_COM_MODULE) +NSFW_MODULE_INIT(nsfw_timer_module_init) /* *INDENT-ON* */ #ifdef __cplusplus diff --git a/src/framework/ipc/ps/nsfw_ps_mem_module.c b/src/framework/ipc/ps/nsfw_ps_mem_module.c index 55af158..57662f9 100644 --- a/src/framework/ipc/ps/nsfw_ps_mem_module.c +++ b/src/framework/ipc/ps/nsfw_ps_mem_module.c @@ -17,7 +17,7 @@ #include <stdlib.h> #include "types.h" #include "nstack_securec.h" -#include "nsfw_init.h" +#include "nsfw_init_api.h" #include "nsfw_ps_module.h" #include "nsfw_mgr_com_api.h" @@ -37,31 +37,30 @@ extern "C"{ ns_mem_mng_init_cfg g_mem_cfg; -int mem_ps_exiting (void *pps_info, void *argv); +int mem_ps_exiting(void *pps_info, void *argv); -int -nsfw_mem_ps_exit_resend_timeout (u32 timer_type, void *data) +int nsfw_mem_ps_exit_resend_timeout(u32 timer_type, void *data) { - nsfw_ps_info *ps_info = data; - if (NULL == ps_info) + nsfw_ps_info *ps_info = data; + if (NULL == ps_info) { - NSFW_LOGERR ("ps_info nul!"); - return FALSE; + NSFW_LOGERR("ps_info nul!"); + return FALSE; } - if (NSFW_PROC_APP != ps_info->proc_type) + if (NSFW_PROC_APP != ps_info->proc_type) { - return FALSE; + return FALSE; } - if (NSFW_PS_EXITING != ps_info->state) + if (NSFW_PS_EXITING != ps_info->state) { - return FALSE; + return FALSE; } - ps_info->resend_timer_ptr = NULL; - (void) mem_ps_exiting (ps_info, NULL); - return TRUE; + ps_info->resend_timer_ptr = NULL; + (void) mem_ps_exiting(ps_info, NULL); + return TRUE; } /***************************************************************************** @@ -74,143 +73,128 @@ nsfw_mem_ps_exit_resend_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -int -mem_ps_exiting (void *pps_info, void *argv) +int mem_ps_exiting(void *pps_info, void *argv) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("ps_info nul!"); - return FALSE; + NSFW_LOGERR("ps_info nul!"); + return FALSE; } - if (TRUE == NSFW_SRV_STATE_SUSPEND) + if (TRUE == NSFW_SRV_STATE_SUSPEND) { - NSFW_LOGERR ("main suspend]ps_info=%d,pid=%u", pps_info, - ((nsfw_ps_info *) pps_info)->host_pid); - return FALSE; + NSFW_LOGERR("main suspend]ps_info=%p,pid=%u", pps_info, + ((nsfw_ps_info *) pps_info)->host_pid); + return FALSE; } - nsfw_mgr_msg *msg = - nsfw_mgr_msg_alloc (MGR_MSG_APP_EXIT_REQ, NSFW_PROC_MAIN); - if (NULL == msg) + nsfw_mgr_msg *msg = + nsfw_mgr_msg_alloc(MGR_MSG_APP_EXIT_REQ, NSFW_PROC_MAIN); + if (NULL == msg) { - NSFW_LOGERR ("ps_exit alloc msg failed]ps_info=%p,pid=%u", pps_info, - ((nsfw_ps_info *) pps_info)->host_pid); - return FALSE; + NSFW_LOGERR("ps_exit alloc msg failed]ps_info=%p,pid=%u", pps_info, + ((nsfw_ps_info *) pps_info)->host_pid); + return FALSE; } - nsfw_ps_info_msg *ps_msg = GET_USER_MSG (nsfw_ps_info_msg, msg); - ps_msg->host_pid = ((nsfw_ps_info *) pps_info)->host_pid; + nsfw_ps_info_msg *ps_msg = GET_USER_MSG(nsfw_ps_info_msg, msg); + ps_msg->host_pid = ((nsfw_ps_info *) pps_info)->host_pid; - (void) nsfw_mgr_send_msg (msg); - NSFW_LOGINF ("ps_exiting send msg]ps_info=%p,pid=%u", pps_info, - ps_msg->host_pid); - nsfw_mgr_msg_free (msg); - return TRUE; + (void) nsfw_mgr_send_msg(msg); + NSFW_LOGINF("ps_exiting send msg]ps_info=%p,pid=%u", pps_info, + ps_msg->host_pid); + nsfw_mgr_msg_free(msg); + + return TRUE; } -/***************************************************************************** -* Prototype : mem_alloc_ps_info -* Description : alloc ps_info -* Input : u32 pid -* u8 proc_type -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -mem_alloc_ps_info (u32 pid, u8 proc_type) +u8 mem_alloc_ps_info(u32 pid, u8 proc_type) { - nsfw_ps_info *pps_info = NULL; - pps_info = nsfw_ps_info_get (pid); - if (NULL != pps_info) + nsfw_ps_info *pps_info = NULL; + pps_info = nsfw_ps_info_get(pid); + if (NULL != pps_info) { - return TRUE; + return TRUE; } - pps_info = nsfw_ps_info_alloc (pid, proc_type); - if (NULL == pps_info) + pps_info = nsfw_ps_info_alloc(pid, proc_type, 0); + if (NULL == pps_info) { - NSFW_LOGERR ("alloc ps_info failed!]pid=%u,proc_type=%u", pid, - proc_type); - return FALSE; + NSFW_LOGERR("alloc ps_info falied!]pid=%u,proc_type=%u", pid, + proc_type); + return FALSE; } - NSFW_LOGINF ("alloc new ps_info]pps_info=%p,pid=%u", pps_info, pid); - return TRUE; + NSFW_LOGINF("alloc new ps_info]pps_info=%p,pid=%u", pps_info, pid); + return TRUE; } /*mem alloc by msg begin*/ -void * -mem_item_zone_create (void *mem_info) +void *mem_item_zone_create(void *mem_info) { - return (void *) nsfw_mem_zone_create ((nsfw_mem_zone *) mem_info); + return (void *) nsfw_mem_zone_create((nsfw_mem_zone *) mem_info); } -void * -mem_item_mbfmp_create (void *mem_info) +void *mem_item_mbfmp_create(void *mem_info) { - return (void *) nsfw_mem_mbfmp_create ((nsfw_mem_mbfpool *) mem_info); + return (void *) nsfw_mem_mbfmp_create((nsfw_mem_mbfpool *) mem_info); } -void * -mem_item_sp_create (void *mem_info) +void *mem_item_sp_create(void *mem_info) { - return (void *) nsfw_mem_sp_create ((nsfw_mem_sppool *) mem_info); + return (void *) nsfw_mem_sp_create((nsfw_mem_sppool *) mem_info); } -void * -mem_item_ring_create (void *mem_info) +void *mem_item_ring_create(void *mem_info) { - return (void *) nsfw_mem_ring_create ((nsfw_mem_mring *) mem_info); + return (void *) nsfw_mem_ring_create((nsfw_mem_mring *) mem_info); } nsfw_ps_mem_item_cfg g_ps_mem_map[] = { - { - NSFW_RESERV_REQ_MSG, - sizeof (nsfw_shmem_reserv_req), - NSFW_MEM_MZONE, - mem_item_zone_create, - mem_item_get_callargv} - , - - { - NSFW_MBUF_REQ_MSG, - sizeof (nsfw_shmem_mbuf_req), - NSFW_MEM_MBUF, - mem_item_mbfmp_create, - mem_item_get_callargv} - , - { - NSFW_SPPOOL_REQ_MSG, - sizeof (nsfw_shmem_sppool_req), - NSFW_MEM_SPOOL, - mem_item_sp_create, - mem_item_get_callargv} - , - { - NSFW_RING_REQ_MSG, - sizeof (nsfw_shmem_ring_req), - NSFW_MEM_RING, - mem_item_ring_create, - mem_item_get_callargv} - , - { - NSFW_RELEASE_REQ_MSG, - sizeof (nsfw_shmem_free_req), - 0xFFFF, - mem_item_free, - mem_item_get_callargv, - } - , - { - NSFW_MEM_LOOKUP_REQ_MSG, - sizeof (nsfw_shmem_lookup_req), - 0xFFFF, - mem_item_lookup, - mem_item_get_callargv, - } + { + NSFW_RESERV_REQ_MSG, + sizeof(nsfw_shmem_reserv_req), + NSFW_MEM_MZONE, + mem_item_zone_create, + mem_item_get_callargv} + , + + { + NSFW_MBUF_REQ_MSG, + sizeof(nsfw_shmem_mbuf_req), + NSFW_MEM_MBUF, + mem_item_mbfmp_create, + mem_item_get_callargv} + , + { + NSFW_SPPOOL_REQ_MSG, + sizeof(nsfw_shmem_sppool_req), + NSFW_MEM_SPOOL, + mem_item_sp_create, + mem_item_get_callargv} + , + { + NSFW_RING_REQ_MSG, + sizeof(nsfw_shmem_ring_req), + NSFW_MEM_RING, + mem_item_ring_create, + mem_item_get_callargv} + , + { + NSFW_RELEASE_REQ_MSG, + sizeof(nsfw_shmem_free_req), + 0xFFFF, + mem_item_free, + mem_item_get_callargv, + } + , + { + NSFW_MEM_LOOKUP_REQ_MSG, + sizeof(nsfw_shmem_lookup_req), + 0xFFFF, + mem_item_lookup, + mem_item_get_callargv, + } }; /***************************************************************************** @@ -222,25 +206,25 @@ nsfw_ps_mem_item_cfg g_ps_mem_map[] = { * Calls : * Called By : *****************************************************************************/ -nsfw_ps_mem_item_cfg * -mem_item_get_cfg_from_msg (u16 msg_type) +nsfw_ps_mem_item_cfg *mem_item_get_cfg_from_msg(u16 msg_type) { - int idx; - int map_count = sizeof (g_ps_mem_map) / sizeof (nsfw_ps_mem_item_cfg); - for (idx = 0; idx < map_count; idx++) + int idx; + int map_count = sizeof(g_ps_mem_map) / sizeof(nsfw_ps_mem_item_cfg); + for (idx = 0; idx < map_count; idx++) { - if (g_ps_mem_map[idx].usmsg_type == msg_type) + if (g_ps_mem_map[idx].usmsg_type == msg_type) { - return &g_ps_mem_map[idx]; + + return &g_ps_mem_map[idx]; } } - return NULL; + return NULL; } /***************************************************************************** * Prototype : mem_item_get_callargv -* Description : change the message value to structure value +* Description : change the message value to structur value * Input : u16 msg_type * char* msg_body * char *memstr_buf @@ -250,163 +234,143 @@ mem_item_get_cfg_from_msg (u16 msg_type) * Calls : * Called By : *****************************************************************************/ -u8 -mem_item_get_callargv (u16 msg_type, char *msg_body, char *memstr_buf, - i32 buf_len) +u8 mem_item_get_callargv(u16 msg_type, char *msg_body, char *memstr_buf, + i32 buf_len) { - switch (msg_type) - { - case NSFW_RESERV_REQ_MSG: - MEM_GET_CALLARGV (length, length, nsfw_mem_zone, nsfw_shmem_reserv_req, - memstr_buf, msg_body); - MEM_GET_CALLARGV (isocket_id, isocket_id, nsfw_mem_zone, - nsfw_shmem_reserv_req, memstr_buf, msg_body); - break; - case NSFW_MBUF_REQ_MSG: - MEM_GET_CALLARGV (usnum, usnum, nsfw_mem_mbfpool, nsfw_shmem_mbuf_req, - memstr_buf, msg_body); - MEM_GET_CALLARGV (uscash_size, uscash_size, nsfw_mem_mbfpool, - nsfw_shmem_mbuf_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (uspriv_size, uspriv_size, nsfw_mem_mbfpool, - nsfw_shmem_mbuf_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (usdata_room, usdata_room, nsfw_mem_mbfpool, - nsfw_shmem_mbuf_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (enmptype, enmptype, nsfw_mem_mbfpool, - nsfw_shmem_mbuf_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (isocket_id, isocket_id, nsfw_mem_mbfpool, - nsfw_shmem_mbuf_req, memstr_buf, msg_body); - break; - case NSFW_SPPOOL_REQ_MSG: - MEM_GET_CALLARGV (usnum, usnum, nsfw_mem_sppool, - nsfw_shmem_sppool_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (useltsize, useltsize, nsfw_mem_sppool, - nsfw_shmem_sppool_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (enmptype, enmptype, nsfw_mem_sppool, - nsfw_shmem_sppool_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (isocket_id, isocket_id, nsfw_mem_sppool, - nsfw_shmem_sppool_req, memstr_buf, msg_body); - break; - case NSFW_RING_REQ_MSG: - MEM_GET_CALLARGV (usnum, usnum, nsfw_mem_mring, nsfw_shmem_ring_req, - memstr_buf, msg_body); - MEM_GET_CALLARGV (enmptype, enmptype, nsfw_mem_mring, - nsfw_shmem_ring_req, memstr_buf, msg_body); - MEM_GET_CALLARGV (isocket_id, isocket_id, nsfw_mem_mring, - nsfw_shmem_ring_req, memstr_buf, msg_body); - break; - case NSFW_RELEASE_REQ_MSG: - MEM_GET_CALLARGV (ustype, ustype, nsfw_mem_type_info, - nsfw_shmem_free_req, memstr_buf, msg_body); - break; - case NSFW_MEM_LOOKUP_REQ_MSG: - MEM_GET_CALLARGV (ustype, ustype, nsfw_mem_type_info, - nsfw_shmem_lookup_req, memstr_buf, msg_body); - break; - default: - NSFW_LOGERR ("error msg]type=%u", msg_type); - return FALSE; - } - if (EOK != - STRCPY_S (((nsfw_mem_zone *) memstr_buf)->stname.aname, - NSFW_MEM_NAME_LENGTH, - ((nsfw_shmem_reserv_req *) msg_body)->aname)) - { - NSFW_LOGERR ("STRCPY_S failed]msg_type=%u", msg_type); - return FALSE; - } - - ((nsfw_mem_zone *) memstr_buf)->stname.entype = NSFW_SHMEM; - - return TRUE; + switch (msg_type) + { + case NSFW_RESERV_REQ_MSG: + MEM_GET_CALLARGV(lenth, lenth, nsfw_mem_zone, + nsfw_shmem_reserv_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(isocket_id, isocket_id, nsfw_mem_zone, + nsfw_shmem_reserv_req, memstr_buf, msg_body); + break; + case NSFW_MBUF_REQ_MSG: + MEM_GET_CALLARGV(usnum, usnum, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(uscash_size, uscash_size, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(uspriv_size, uspriv_size, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(usdata_room, usdata_room, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(enmptype, enmptype, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(isocket_id, isocket_id, nsfw_mem_mbfpool, + nsfw_shmem_mbuf_req, memstr_buf, msg_body); + break; + case NSFW_SPPOOL_REQ_MSG: + MEM_GET_CALLARGV(usnum, usnum, nsfw_mem_sppool, + nsfw_shmem_sppool_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(useltsize, useltsize, nsfw_mem_sppool, + nsfw_shmem_sppool_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(enmptype, enmptype, nsfw_mem_sppool, + nsfw_shmem_sppool_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(isocket_id, isocket_id, nsfw_mem_sppool, + nsfw_shmem_sppool_req, memstr_buf, msg_body); + break; + case NSFW_RING_REQ_MSG: + MEM_GET_CALLARGV(usnum, usnum, nsfw_mem_mring, + nsfw_shmem_ring_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(enmptype, enmptype, nsfw_mem_mring, + nsfw_shmem_ring_req, memstr_buf, msg_body); + MEM_GET_CALLARGV(isocket_id, isocket_id, nsfw_mem_mring, + nsfw_shmem_ring_req, memstr_buf, msg_body); + break; + case NSFW_RELEASE_REQ_MSG: + MEM_GET_CALLARGV(ustype, ustype, nsfw_mem_type_info, + nsfw_shmem_free_req, memstr_buf, msg_body); + break; + case NSFW_MEM_LOOKUP_REQ_MSG: + MEM_GET_CALLARGV(ustype, ustype, nsfw_mem_type_info, + nsfw_shmem_lookup_req, memstr_buf, msg_body); + break; + default: + NSFW_LOGERR("error msg]type=%u", msg_type); + return FALSE; + } + /*copy string should use strcpy_s */ + if (EOK != + strcpy_s(((nsfw_mem_zone *) memstr_buf)->stname.aname, + NSFW_MEM_NAME_LENTH, + ((nsfw_shmem_reserv_req *) msg_body)->aname)) + { + NSFW_LOGERR("strcpy_s failed]msg_type=%u", msg_type); + return FALSE; + } + + ((nsfw_mem_zone *) memstr_buf)->stname.entype = NSFW_SHMEM; + + return TRUE; } -/***************************************************************************** -* Prototype : mem_item_free -* Description : free memory item -* Input : void *pdata -* Output : None -* Return Value : void* -* Calls : -* Called By : -*****************************************************************************/ -void * -mem_item_free (void *pdata) +void *mem_item_free(void *pdata) { - nsfw_mem_type_info *mem_free = (nsfw_mem_type_info *) pdata; - i32 ret; - NSFW_LOGINF ("free mem]type=%u,name=%s", mem_free->ustype, - mem_free->stname.aname); - switch (mem_free->ustype) - { - case NSFW_MEM_MZONE: - ret = nsfw_mem_zone_release (&mem_free->stname); - break; - case NSFW_MEM_MBUF: - ret = nsfw_mem_mbfmp_release (&mem_free->stname); - break; - case NSFW_MEM_SPOOL: - ret = nsfw_mem_sp_release (&mem_free->stname); - break; - case NSFW_MEM_RING: - ret = nsfw_mem_ring_release (&mem_free->stname); - break; - default: - NSFW_LOGERR ("free mem err type]type=%u", mem_free->ustype); - return NULL; - } - - if (NSFW_MEM_OK != ret) - { - NSFW_LOGERR ("mem free failed!]ret=%d", ret); - return NULL; - } - - return pdata; + nsfw_mem_type_info *mem_free = (nsfw_mem_type_info *) pdata; + i32 ret; + NSFW_LOGINF("free mem]type=%u,name=%s", mem_free->ustype, + mem_free->stname.aname); + switch (mem_free->ustype) + { + case NSFW_MEM_MZONE: + ret = nsfw_mem_zone_release(&mem_free->stname); + break; + case NSFW_MEM_MBUF: + ret = nsfw_mem_mbfmp_release(&mem_free->stname); + break; + case NSFW_MEM_SPOOL: + ret = nsfw_mem_sp_release(&mem_free->stname); + break; + case NSFW_MEM_RING: + ret = nsfw_mem_ring_release(&mem_free->stname); + break; + default: + NSFW_LOGERR("free mem err type]type=%u", mem_free->ustype); + return NULL; + } + + if (NSFW_MEM_OK != ret) + { + NSFW_LOGERR("mem free failed!]ret=%d", ret); + return NULL; + } + + return pdata; } -/***************************************************************************** -* Prototype : mem_item_lookup -* Description : lookup memory item -* Input : void *pdata -* Output : None -* Return Value : void* -* Calls : -* Called By : -*****************************************************************************/ -void * -mem_item_lookup (void *pdata) +void *mem_item_lookup(void *pdata) { - nsfw_mem_type_info *mem_lookup = (nsfw_mem_type_info *) pdata; - void *ret; - NSFW_LOGDBG ("lookup mem]type=%u,name=%s", mem_lookup->ustype, - mem_lookup->stname.aname); - switch (mem_lookup->ustype) - { - case NSFW_MEM_MZONE: - ret = nsfw_mem_zone_lookup (&mem_lookup->stname); - break; - case NSFW_MEM_MBUF: - ret = nsfw_mem_mbfmp_lookup (&mem_lookup->stname); - break; - case NSFW_MEM_SPOOL: - ret = nsfw_mem_sp_lookup (&mem_lookup->stname); - break; - case NSFW_MEM_RING: - ret = nsfw_mem_ring_lookup (&mem_lookup->stname); - break; - default: - NSFW_LOGERR ("lookup mem err type]type=%d", mem_lookup->ustype); - return NULL; - } - - if (NULL == ret) - { - NSFW_LOGERR ("mem lookup failed!]ret=%p,name=%s", ret, - mem_lookup->stname.aname); - return NULL; - } - - return ret; + nsfw_mem_type_info *mem_lookup = (nsfw_mem_type_info *) pdata; + void *ret; + NSFW_LOGDBG("lookup mem]type=%u,name=%s", mem_lookup->ustype, + mem_lookup->stname.aname); + switch (mem_lookup->ustype) + { + case NSFW_MEM_MZONE: + ret = nsfw_mem_zone_lookup(&mem_lookup->stname); + break; + case NSFW_MEM_MBUF: + ret = nsfw_mem_mbfmp_lookup(&mem_lookup->stname); + break; + case NSFW_MEM_SPOOL: + ret = nsfw_mem_sp_lookup(&mem_lookup->stname); + break; + case NSFW_MEM_RING: + ret = nsfw_mem_ring_lookup(&mem_lookup->stname); + break; + default: + NSFW_LOGERR("lookup mem err type]type=%d", mem_lookup->ustype); + return NULL; + } + + if (NULL == ret) + { + NSFW_LOGERR("mem lookup failed!]ret=%p,name=%s", ret, + mem_lookup->stname.aname); + return NULL; + } + + return ret; } /***************************************************************************** @@ -419,234 +383,191 @@ mem_item_lookup (void *pdata) * Calls : * Called By : *****************************************************************************/ -void * -mem_item_proc_by_msg (void *pdata, nsfw_ps_mem_item_cfg * item_cfg) +void *mem_item_proc_by_msg(void *pdata, nsfw_ps_mem_item_cfg * item_cfg) { - char argv_buf[NSFW_MEM_CALL_ARG_BUF] = { 0 }; + char argv_buf[NSFW_MEM_CALL_ARG_BUF] = { 0 }; - if ((NULL == item_cfg->change_fun) || (NULL == item_cfg->create_fun)) + if ((NULL == item_cfg->change_fun) || (NULL == item_cfg->create_fun)) { - NSFW_LOGERR ("item error]change_fun=%p,create_fun=%p", - item_cfg->change_fun, item_cfg->create_fun); - return NULL; + NSFW_LOGERR("item error]change_fun=%p,create_fun=%p", + item_cfg->change_fun, item_cfg->create_fun); + return NULL; } - if (FALSE == - item_cfg->change_fun (item_cfg->usmsg_type, pdata, argv_buf, - NSFW_MEM_CALL_ARG_BUF)) + if (FALSE == + item_cfg->change_fun(item_cfg->usmsg_type, pdata, argv_buf, + NSFW_MEM_CALL_ARG_BUF)) { - NSFW_LOGERR ("call change_fun failed!]type=%u", item_cfg->usmsg_type); - return NULL; + NSFW_LOGERR("call change_fun failed!]type=%u", item_cfg->usmsg_type); + return NULL; } - void *pdataret = NULL; - pdataret = (item_cfg->create_fun) ((void *) argv_buf); - return pdataret; + void *pdataret = NULL; + pdataret = (item_cfg->create_fun) ((void *) argv_buf); + return pdataret; } -/***************************************************************************** -* Prototype : mem_init_rsp_msg -* Description : init the rsp message -* Input : nsfw_shmem_msg_head* msg -* nsfw_shmem_msg_head *rsp -* Output : None -* Return Value : u8 -* Calls : -* Called By : -* -*****************************************************************************/ -u8 -mem_init_rsp_msg (nsfw_shmem_msg_head * msg, nsfw_shmem_msg_head * rsp) +u8 mem_init_rsp_msg(nsfw_shmem_msg_head * msg, nsfw_shmem_msg_head * rsp) { - nsfw_ps_mem_item_cfg *item_cfg = - mem_item_get_cfg_from_msg (msg->usmsg_type); - if (NULL == item_cfg) + nsfw_ps_mem_item_cfg *item_cfg = + mem_item_get_cfg_from_msg(msg->usmsg_type); + if (NULL == item_cfg) { - NSFW_LOGERR ("get item cfg failed!]msg_type=%u", msg->usmsg_type); - return FALSE; + NSFW_LOGERR("get item cfg failed!]msg_type=%u", msg->usmsg_type); + return FALSE; } - int idx; - int mem_count = msg->uslength / item_cfg->item_size; + int idx; + int mem_count = msg->uslenth / item_cfg->item_size; - rsp->usmsg_type = msg->usmsg_type + 1; - rsp->uslength = mem_count * sizeof (nsfw_shmem_ack); - nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); - char *pdata = NULL; - for (idx = 0; idx < mem_count; idx++) + rsp->usmsg_type = msg->usmsg_type + 1; + rsp->uslenth = mem_count * sizeof(nsfw_shmem_ack); + nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); + char *pdata = NULL; + for (idx = 0; idx < mem_count; idx++) { - pdata = (char *) msg->aidata + idx * item_cfg->item_size; - pack->pbase_addr = NULL; - pack->usseq = ((nsfw_shmem_reserv_req *) pdata)->usseq; - pack->cstate = NSFW_MEM_ALLOC_FAIL; - pack++; + + pdata = (char *) msg->aidata + idx * item_cfg->item_size; + pack->pbase_addr = NULL; + pack->usseq = ((nsfw_shmem_reserv_req *) pdata)->usseq; + pack->cstate = NSFW_MEM_ALLOC_FAIL; + pack++; } - NSFW_LOGDBG ("init all rsp ack]mem_count=%d,msg_type=%u", mem_count, - msg->usmsg_type); - return TRUE; + NSFW_LOGDBG("init all rsp ack]mem_count=%d,msg_type=%u", mem_count, + msg->usmsg_type); + return TRUE; } -/***************************************************************************** -* Prototype : mem_rel_mem_by_msg -* Description : release memory by message -* Input : nsfw_shmem_msg_head* req_msg -* nsfw_shmem_msg_head *rsp -* u32 pid -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -mem_rel_mem_by_msg (nsfw_shmem_msg_head * req_msg, - nsfw_shmem_msg_head * rsp, u32 pid) +u8 mem_rel_mem_by_msg(nsfw_shmem_msg_head * req_msg, + nsfw_shmem_msg_head * rsp, u32 pid) { - u32 i; - nsfw_ps_mem_item_cfg *item_cfg = - mem_item_get_cfg_from_msg (req_msg->usmsg_type); - if (NULL == item_cfg) + u32 i; + nsfw_ps_mem_item_cfg *item_cfg = + mem_item_get_cfg_from_msg(req_msg->usmsg_type); + if (NULL == item_cfg) { - NSFW_LOGERR ("get item cfg failed!]msg_type=%u", req_msg->usmsg_type); - return FALSE; + NSFW_LOGERR("get item cfg failed!]msg_type=%u", req_msg->usmsg_type); + return FALSE; } - unsigned int mem_count = req_msg->uslength / item_cfg->item_size; - char *pdata = NULL; - nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); - for (i = 0; i < mem_count; i++) + unsigned int mem_count = req_msg->uslenth / item_cfg->item_size; + char *pdata = NULL; + nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); + for (i = 0; i < mem_count; i++) { - pdata = (char *) req_msg->aidata + i * item_cfg->item_size; - if (NULL != mem_item_proc_by_msg ((void *) pdata, item_cfg)) + + pdata = (char *) req_msg->aidata + i * item_cfg->item_size; + if (NULL != mem_item_proc_by_msg((void *) pdata, item_cfg)) { - pack->cstate = NSFW_MEM_ALLOC_SUCC; - pack->pbase_addr = NULL; + pack->cstate = NSFW_MEM_ALLOC_SUCC; + pack->pbase_addr = NULL; } - pack++; + pack++; } - return TRUE; + return TRUE; } -/***************************************************************************** -* Prototype : mem_lookup_mem_by_msg -* Description : lookup memory by message -* Input : nsfw_shmem_msg_head* mgr_msg -* nsfw_shmem_msg_head *rsp -* u32 pid -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -mem_lookup_mem_by_msg (nsfw_shmem_msg_head * mgr_msg, - nsfw_shmem_msg_head * rsp, u32 pid) +u8 mem_lookup_mem_by_msg(nsfw_shmem_msg_head * mgr_msg, + nsfw_shmem_msg_head * rsp, u32 pid) { - i32 idx; - nsfw_ps_mem_item_cfg *item_cfg = - mem_item_get_cfg_from_msg (mgr_msg->usmsg_type); - if (NULL == item_cfg) + i32 idx; + nsfw_ps_mem_item_cfg *item_cfg = + mem_item_get_cfg_from_msg(mgr_msg->usmsg_type); + if (NULL == item_cfg) { - NSFW_LOGERR ("get item cfg failed!]msg_type=%u", mgr_msg->usmsg_type); - return FALSE; + NSFW_LOGERR("get item cfg failed!]msg_type=%u", mgr_msg->usmsg_type); + return FALSE; } - int mem_count = mgr_msg->uslength / item_cfg->item_size; - char *pdata = NULL; - void *paddr = NULL; - nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); + int mem_count = mgr_msg->uslenth / item_cfg->item_size; + char *pdata = NULL; + void *paddr = NULL; + nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); - for (idx = 0; idx < mem_count; idx++) + for (idx = 0; idx < mem_count; idx++) { - pdata = (char *) mgr_msg->aidata + idx * item_cfg->item_size; - paddr = mem_item_proc_by_msg ((void *) pdata, item_cfg); - if (NULL != paddr) + + pdata = (char *) mgr_msg->aidata + idx * item_cfg->item_size; + paddr = mem_item_proc_by_msg((void *) pdata, item_cfg); + if (NULL != paddr) { - pack->cstate = NSFW_MEM_ALLOC_SUCC; - pack->pbase_addr = paddr; + pack->cstate = NSFW_MEM_ALLOC_SUCC; + pack->pbase_addr = paddr; } - pack++; + pack++; } - return TRUE; + return TRUE; } -/***************************************************************************** -* Prototype : mem_alloc_mem_by_msg -* Description : alloc memory by message -* Input : nsfw_shmem_msg_head* mem_msg -* nsfw_shmem_msg_head *rsp -* Output : None -* Return Value : ns_mem_info* -* Calls : -* Called By : -*****************************************************************************/ -void * -mem_alloc_mem_by_msg (nsfw_shmem_msg_head * mem_msg, - nsfw_shmem_msg_head * rsp) +void *mem_alloc_mem_by_msg(nsfw_shmem_msg_head * mem_msg, + nsfw_shmem_msg_head * rsp) { - nsfw_ps_mem_item_cfg *item_cfg = - mem_item_get_cfg_from_msg (mem_msg->usmsg_type); - if (NULL == item_cfg) + nsfw_ps_mem_item_cfg *item_cfg = + mem_item_get_cfg_from_msg(mem_msg->usmsg_type); + if (NULL == item_cfg) { - NSFW_LOGERR ("get item cfg failed!]msg_type=%u", mem_msg->usmsg_type); - return NULL; + NSFW_LOGERR("get item cfg fail]msg_type=%u", mem_msg->usmsg_type); + return NULL; } - int i; - int j; - nsfw_mem_type_info mem_free; - char *pdata = NULL; - void *p_addr = NULL; + int i; + int j; + nsfw_mem_type_info mem_free; + char *pdata = NULL; + void *p_addr = NULL; - int mem_count = mem_msg->uslength / item_cfg->item_size; - nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); - for (i = 0; i < mem_count; i++) + int mem_count = mem_msg->uslenth / item_cfg->item_size; + nsfw_shmem_ack *pack = (nsfw_shmem_ack *) & (rsp->aidata[0]); + for (i = 0; i < mem_count; i++) { - pdata = (char *) mem_msg->aidata + i * item_cfg->item_size; - p_addr = mem_item_proc_by_msg ((void *) pdata, item_cfg); - if (NULL == p_addr) + + pdata = (char *) mem_msg->aidata + i * item_cfg->item_size; + p_addr = mem_item_proc_by_msg((void *) pdata, item_cfg); + if (NULL == p_addr) { - NSFW_LOGERR - ("alloc mem failed!]type=%u,mem_count=%d,item=%d,name=%s", - mem_msg->usmsg_type, mem_count, i, - ((nsfw_shmem_reserv_req *) pdata)->aname); - goto fail_free_mem; + NSFW_LOGERR + ("alloc mem fail]type=%u,mem_count=%d,item=%d,name=%s", + mem_msg->usmsg_type, mem_count, i, + ((nsfw_shmem_reserv_req *) pdata)->aname); + goto fail_free_mem; } - pack->cstate = NSFW_MEM_ALLOC_SUCC; - pack->pbase_addr = p_addr; - NSFW_LOGINF - ("alloc mem suc!]addr=%p,type=%u,mem_count=%d,item=%d,name=%s", - p_addr, mem_msg->usmsg_type, mem_count, i, - ((nsfw_shmem_reserv_req *) pdata)->aname); - pack++; + pack->cstate = NSFW_MEM_ALLOC_SUCC; + pack->pbase_addr = p_addr; + NSFW_LOGINF("alloc suc]addr=%p,type=%u,mem_count=%d,item=%d,name=%s", + p_addr, mem_msg->usmsg_type, mem_count, i, + ((nsfw_shmem_reserv_req *) pdata)->aname); + pack++; } - return p_addr; + return p_addr; -fail_free_mem: - for (j = 0; j < i; j++) + fail_free_mem: + for (j = 0; j < i; j++) { - pdata = (char *) mem_msg->aidata + j * item_cfg->item_size; - if (EOK != - STRCPY_S (mem_free.stname.aname, NSFW_MEM_NAME_LENGTH, - ((nsfw_shmem_reserv_req *) pdata)->aname)) + + pdata = (char *) mem_msg->aidata + j * item_cfg->item_size; + /*copy string should use strcpy_s */ + if (EOK != + strcpy_s(mem_free.stname.aname, NSFW_MEM_NAME_LENTH, + ((nsfw_shmem_reserv_req *) pdata)->aname)) { - NSFW_LOGERR ("STRCPY_S failed]j=%d", j); - continue; + NSFW_LOGERR("strcpy_s fail]j=%d", j); + continue; } - mem_free.ustype = item_cfg->mem_type; - mem_free.stname.entype = NSFW_SHMEM; - (void) mem_item_free (&mem_free); - NSFW_LOGINF ("free mem]addr=%p,type=%u,mem_count=%d,item=%d,name=%s", - p_addr, mem_msg->usmsg_type, mem_count, j, - ((nsfw_shmem_reserv_req *) pdata)->aname); - pack++; + mem_free.ustype = item_cfg->mem_type; + mem_free.stname.entype = NSFW_SHMEM; + (void) mem_item_free(&mem_free); + NSFW_LOGINF("free mem]addr=%p,type=%u,mem_count=%d,item=%d,name=%s", + p_addr, mem_msg->usmsg_type, mem_count, j, + ((nsfw_shmem_reserv_req *) pdata)->aname); + pack++; } - return NULL; + return NULL; } @@ -659,75 +580,75 @@ fail_free_mem: * Calls : * Called By : *****************************************************************************/ -int -mem_alloc_req_proc (nsfw_mgr_msg * msg) +int mem_alloc_req_proc(nsfw_mgr_msg * msg) { - void *mem_addr = NULL; - - if (NULL == msg) - { - NSFW_LOGERR ("msg nul"); - return FALSE; - } - - nsfw_shmem_msg_head *mem_msg = GET_USER_MSG (nsfw_shmem_msg_head, msg); - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL == rsp_msg) - { - NSFW_LOGERR ("alloc rsp msg failed]msg_type=%u", mem_msg->usmsg_type); - return FALSE; - } - - nsfw_shmem_msg_head *mem_rsp_msg = - GET_USER_MSG (nsfw_shmem_msg_head, rsp_msg); - - if (!mem_init_rsp_msg (mem_msg, mem_rsp_msg)) - { - NSFW_LOGERR ("init rsp msg failed]msg_type=%u", mem_msg->usmsg_type); - nsfw_mgr_msg_free (rsp_msg); - return FALSE; - } - - switch (mem_msg->usmsg_type) - { - case NSFW_MEM_LOOKUP_REQ_MSG: - if (!mem_lookup_mem_by_msg (mem_msg, mem_rsp_msg, msg->src_pid)) - { - NSFW_LOGERR ("lookup mem msg failed]msg_type=%u", - mem_msg->usmsg_type); - goto sendrspmsg; - } - (void) mem_alloc_ps_info (msg->src_pid, msg->src_proc_type); - break; - case NSFW_RESERV_REQ_MSG: - case NSFW_MBUF_REQ_MSG: - case NSFW_SPPOOL_REQ_MSG: - case NSFW_RING_REQ_MSG: - mem_addr = mem_alloc_mem_by_msg (mem_msg, mem_rsp_msg); - if (NULL == mem_addr) - { - NSFW_LOGERR ("alloc mem msg failed]msg_type=%u", - mem_msg->usmsg_type); - (void) mem_init_rsp_msg (mem_msg, mem_rsp_msg); - goto sendrspmsg; - } - (void) mem_alloc_ps_info (msg->src_pid, msg->src_proc_type); - break; - case NSFW_RELEASE_REQ_MSG: - if (!mem_rel_mem_by_msg (mem_msg, mem_rsp_msg, msg->src_pid)) - { - NSFW_LOGERR ("rel mem msg failed]msg_type=%u", mem_msg->usmsg_type); - goto sendrspmsg; - } - break; - default: - break; - } - -sendrspmsg: - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); - return TRUE; + void *mem_addr = NULL; + + if (NULL == msg) + { + NSFW_LOGERR("msg nul"); + return FALSE; + } + + nsfw_shmem_msg_head *mem_msg = GET_USER_MSG(nsfw_shmem_msg_head, msg); + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp msg failed]msg_type=%u", mem_msg->usmsg_type); + return FALSE; + } + + nsfw_shmem_msg_head *mem_rsp_msg = + GET_USER_MSG(nsfw_shmem_msg_head, rsp_msg); + + if (!mem_init_rsp_msg(mem_msg, mem_rsp_msg)) + { + NSFW_LOGERR("init rsp msg failed]msg_type=%u", mem_msg->usmsg_type); + nsfw_mgr_msg_free(rsp_msg); + return FALSE; + } + + switch (mem_msg->usmsg_type) + { + case NSFW_MEM_LOOKUP_REQ_MSG: + if (!mem_lookup_mem_by_msg(mem_msg, mem_rsp_msg, msg->src_pid)) + { + NSFW_LOGERR("lookup mem msg failed]msg_type=%u", + mem_msg->usmsg_type); + goto sendrspmsg; + } + (void) mem_alloc_ps_info(msg->src_pid, msg->src_proc_type); + break; + case NSFW_RESERV_REQ_MSG: + case NSFW_MBUF_REQ_MSG: + case NSFW_SPPOOL_REQ_MSG: + case NSFW_RING_REQ_MSG: + mem_addr = mem_alloc_mem_by_msg(mem_msg, mem_rsp_msg); + if (NULL == mem_addr) + { + NSFW_LOGERR("alloc mem msg failed]msg_type=%u", + mem_msg->usmsg_type); + (void) mem_init_rsp_msg(mem_msg, mem_rsp_msg); + goto sendrspmsg; + } + (void) mem_alloc_ps_info(msg->src_pid, msg->src_proc_type); + break; + case NSFW_RELEASE_REQ_MSG: + if (!mem_rel_mem_by_msg(mem_msg, mem_rsp_msg, msg->src_pid)) + { + NSFW_LOGERR("rel mem msg failed]msg_type=%u", + mem_msg->usmsg_type); + goto sendrspmsg; + } + break; + default: + break; + } + + sendrspmsg: + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + return TRUE; } /***************************************************************************** @@ -740,47 +661,64 @@ sendrspmsg: * Calls : * Called By : *****************************************************************************/ -int -mem_ps_exiting_resend (void *pps_info, void *argv) +int mem_ps_exiting_resend(void *pps_info, void *argv) { - u32 *count = argv; - nsfw_ps_info *ps_info = pps_info; - if (NULL == ps_info) + u32 *count = argv; + nsfw_ps_info *ps_info = pps_info; + if (NULL == ps_info) { - NSFW_LOGERR ("ps_info nul!"); - return FALSE; + NSFW_LOGERR("ps_info nul!"); + return FALSE; } - if (NSFW_PROC_APP != ps_info->proc_type) + if (NSFW_PROC_APP != ps_info->proc_type) { - return FALSE; + return FALSE; } - if (NSFW_PS_EXITING != ps_info->state) + if (NSFW_PS_EXITING != ps_info->state) { - return FALSE; + return FALSE; } - if (NULL != count) + if (NULL != count) { - NSFW_LOGINF ("send count]count=%u,pid=%u", *count, ps_info->host_pid); - if (NSFW_PS_SEND_PER_TIME < (*count)++) + NSFW_LOGINF("send count]count=%u,pid=%u", *count, ps_info->host_pid); + if (NSFW_PS_SEND_PER_TIME < (*count)++) { - struct timespec time_left = - { NSFW_PS_MEM_RESEND_TVLAUE + + struct timespec time_left = + { NSFW_PS_MEM_RESEND_TVLAUE + ((*count) / NSFW_PS_SEND_PER_TIME), 0 - }; - ps_info->resend_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_PS_MEM_RESEND_TIMER, - pps_info, - nsfw_mem_ps_exit_resend_timeout, - time_left); - return TRUE; + }; + ps_info->resend_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_PS_MEM_RESEND_TIMER, + pps_info, + nsfw_mem_ps_exit_resend_timeout, + time_left); + return TRUE; } } - (void) mem_ps_exiting (ps_info, NULL); - return TRUE; + (void) mem_ps_exiting(ps_info, NULL); + return TRUE; +} + +/***************************************************************************** +* Prototype : mem_ps_exiting +* Description : Send exiting message when a single ps_info is exiting. +* If there have been more than NSFW_PS_SEND_PER_TIME apps +* in EXITING state, register a resend timer. +* Input : void *pps_info +* void* argv +* Output : None +* Return Value : int +* Calls : +* Called By : See NSFW_PS_EXITING msg +*****************************************************************************/ +int mem_ps_exiting_send(void *pps_info, void *argv) +{ + u32 count = get_ps_exiting_cnt(); + return mem_ps_exiting_resend(pps_info, (void *) &count); } /***************************************************************************** @@ -793,18 +731,17 @@ mem_ps_exiting_resend (void *pps_info, void *argv) * Calls : * Called By : *****************************************************************************/ -int -nsfw_mem_srv_restore_timeout (u32 timer_type, void *data) +int nsfw_mem_srv_restore_timeout(u32 timer_type, void *data) { - u32 max_count = 0; + u32 max_count = 0; - g_mem_cfg.p_restore_timer = NULL; - if (TRUE == NSFW_SRV_STATE_SUSPEND) + g_mem_cfg.p_restore_timer = NULL; + if (TRUE == NSFW_SRV_STATE_SUSPEND) { - NSFW_SRV_STATE_SUSPEND = FALSE; - (void) nsfw_ps_iterator (mem_ps_exiting_resend, &max_count); + NSFW_SRV_STATE_SUSPEND = FALSE; + (void) nsfw_ps_iterator(mem_ps_exiting_resend, &max_count); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -816,105 +753,100 @@ nsfw_mem_srv_restore_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -int -mem_srv_ctrl_proc (nsfw_mgr_msg * msg) +int mem_srv_ctrl_proc(nsfw_mgr_msg * msg) { - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("msg nul"); - return FALSE; + NSFW_LOGERR("msg nul"); + return FALSE; } - nsfw_srv_ctrl_msg *ctrl_msg = GET_USER_MSG (nsfw_srv_ctrl_msg, msg); - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL == rsp_msg) + nsfw_srv_ctrl_msg *ctrl_msg = GET_USER_MSG(nsfw_srv_ctrl_msg, msg); + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) { - NSFW_LOGERR ("alloc rsp msg failed]msg=%p", msg); - return FALSE; + NSFW_LOGERR("alloc rsp msg failed]msg=%p", msg); + return FALSE; } - nsfw_srv_ctrl_msg *ctrl_rsp_msg = GET_USER_MSG (nsfw_srv_ctrl_msg, rsp_msg); - NSFW_LOGINF ("get srv ctrl state] state=%d", ctrl_msg->srv_state); + nsfw_srv_ctrl_msg *ctrl_rsp_msg = + GET_USER_MSG(nsfw_srv_ctrl_msg, rsp_msg); + NSFW_LOGINF("get srv ctrl state] state=%d", ctrl_msg->srv_state); - ctrl_rsp_msg->rsp_code = NSFW_MGR_SUCCESS; + ctrl_rsp_msg->rsp_code = NSFW_MGR_SUCESS; - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); - if (NSFW_SRV_CTRL_RESUME == ctrl_msg->srv_state) + if (NSFW_SRV_CTRL_RESUME == ctrl_msg->srv_state) { - if (TRUE == NSFW_SRV_STATE_SUSPEND) + if (TRUE == NSFW_SRV_STATE_SUSPEND) { - NSFW_SRV_STATE_SUSPEND = FALSE; + NSFW_SRV_STATE_SUSPEND = FALSE; } - u32 max_count = 0; - (void) nsfw_ps_iterator (mem_ps_exiting_resend, &max_count); - if (NULL != g_mem_cfg.p_restore_timer) + u32 max_count = 0; + (void) nsfw_ps_iterator(mem_ps_exiting_resend, &max_count); + if (NULL != g_mem_cfg.p_restore_timer) { - nsfw_timer_rmv_timer ((nsfw_timer_info *) - g_mem_cfg.p_restore_timer); - g_mem_cfg.p_restore_timer = NULL; + nsfw_timer_rmv_timer((nsfw_timer_info *) + g_mem_cfg.p_restore_timer); + g_mem_cfg.p_restore_timer = NULL; } } - else + else { - NSFW_SRV_STATE_SUSPEND = TRUE; - struct timespec time_left = { NSFW_SRV_RESTORE_TVALUE, 0 }; - g_mem_cfg.p_restore_timer = - (void *) nsfw_timer_reg_timer (0, NULL, - nsfw_mem_srv_restore_timeout, - time_left); + NSFW_SRV_STATE_SUSPEND = TRUE; + struct timespec time_left = { NSFW_SRV_RESTORE_TVALUE, 0 }; + g_mem_cfg.p_restore_timer = + (void *) nsfw_timer_reg_timer(0, NULL, + nsfw_mem_srv_restore_timeout, + time_left); } - return TRUE; + return TRUE; } -/***************************************************************************** -* Prototype : nsfw_ps_mem_module_init -* Description : module init -* Input : void* param -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -int -nsfw_ps_mem_module_init (void *param) +int nsfw_ps_mem_module_init(void *param) { - u32 proc_type = (u32) ((long long) param); - NSFW_LOGINF ("ps_mem module init]type=%u", proc_type); - switch (proc_type) - { - case NSFW_PROC_MAIN: - (void) nsfw_ps_reg_global_fun (NSFW_PROC_APP, NSFW_PS_EXITING, - mem_ps_exiting, NULL); - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_MEM_ALLOC_REQ, mem_alloc_req_proc); - (void) NSFW_REG_SOFT_INT (NSFW_SRV_RESTORE_TIMER, - NSFW_SRV_RESTORE_TVALUE, 1, 0xFFFF); - (void) NSFW_REG_SOFT_INT (NSFW_APP_RESEND_TIMER, - NSFW_PS_MEM_RESEND_TVLAUE, 1, 0xFFFF); - (void) NSFW_REG_SOFT_INT (NSFW_APP_SEND_PER_TIME, - NSFW_PS_SEND_PER_TIME, 1, 0xFFFF); - break; - default: - if (proc_type < NSFW_PROC_MAX) - { - return 0; - } - return -1; - } - - g_mem_cfg.srv_restore_tvalue = NSFW_SRV_RESTORE_TVALUE_DEF; - g_mem_cfg.ps_exit_resend_tvalue = NSFW_PS_MEM_RESEND_TVLAUE_DEF; - g_mem_cfg.ps_send_per_time = NSFW_PS_SEND_PER_TIME_DEF; - - return 0; + u32 proc_type = (u32) ((long long) param); + NSFW_LOGINF("ps_mem module init]type=%u", proc_type); + switch (proc_type) + { + case NSFW_PROC_MASTER: + (void) nsfw_ps_reg_global_fun(NSFW_PROC_APP, NSFW_PS_EXITING, + mem_ps_exiting_send, NULL); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_MEM_ALLOC_REQ, + mem_alloc_req_proc); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_SRV_CTL_REQ, + mem_srv_ctrl_proc); + (void) NSFW_REG_SOFT_INT(NSFW_SRV_RESTORE_TIMER, + NSFW_SRV_RESTORE_TVALUE, 1, 0xFFFF); + (void) NSFW_REG_SOFT_INT(NSFW_APP_RESEND_TIMER, + NSFW_PS_MEM_RESEND_TVLAUE, 1, 0xFFFF); + (void) NSFW_REG_SOFT_INT(NSFW_APP_SEND_PER_TIME, + NSFW_PS_SEND_PER_TIME, 1, 0xFFFF); + break; + default: + if (proc_type < NSFW_PROC_MAX) + { + return 0; + } + return -1; + } + + g_mem_cfg.srv_restore_tvalue = NSFW_SRV_RESTORE_TVALUE_DEF; + g_mem_cfg.ps_exit_resend_tvalue = NSFW_PS_MEM_RESEND_TVLAUE_DEF; + g_mem_cfg.ps_send_per_time = NSFW_PS_SEND_PER_TIME_DEF; + g_mem_cfg.srv_suspend = 0; + g_mem_cfg.p_restore_timer = NULL; + + return 0; } /* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_PS_MEM_MODULE) -NSFW_MODULE_PRIORITY (10) -NSFW_MODULE_DEPENDS (NSFW_PS_MODULE) -NSFW_MODULE_INIT (nsfw_ps_mem_module_init) +NSFW_MODULE_NAME(NSFW_PS_MEM_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_DEPENDS(NSFW_PS_MODULE) +NSFW_MODULE_INIT(nsfw_ps_mem_module_init) /* *INDENT-ON* */ #ifdef __cplusplus diff --git a/src/framework/ipc/ps/nsfw_ps_mem_module.h b/src/framework/ipc/ps/nsfw_ps_mem_module.h index 6b2b3c9..337b578 100644 --- a/src/framework/ipc/ps/nsfw_ps_mem_module.h +++ b/src/framework/ipc/ps/nsfw_ps_mem_module.h @@ -19,6 +19,7 @@ #include "list.h" #include "pidinfo.h" +#include "nsfw_mem_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -42,18 +43,18 @@ extern "C"{ typedef struct _ns_mem_mng_init_cfg { - u16 srv_restore_tvalue; - u16 ps_exit_resend_tvalue; - u16 ps_send_per_time; - u16 srv_suspend; - void *p_restore_timer; + u16 srv_restore_tvalue; + u16 ps_exit_resend_tvalue; + u16 ps_send_per_time; + u16 srv_suspend; + void *p_restore_timer; } ns_mem_mng_init_cfg; /*mem alloc by msg begin*/ typedef struct { - nsfw_mem_name stname; - u16 ustype; + nsfw_mem_name stname; + u16 ustype; } nsfw_mem_type_info; #define NSFW_MEM_CALL_ARG_BUF 256 @@ -61,22 +62,22 @@ typedef struct ((_dst_type*)(void*)_dst_buf)->_dst_member = ((_srctype*)(void*)_src_buf)->_src_member typedef void *(*nsfw_ps_mem_create_fun) (void *memstr); -typedef u8 (*nsfw_ps_mem_msg_to_memstr) (u16 msg_type, char *msg_body, - char *memstr_buf, i32 buf_len); +typedef u8(*nsfw_ps_mem_msg_to_memstr) (u16 msg_type, char *msg_body, + char *memstr_buf, i32 buf_len); typedef struct __nsfw_ps_mem_item_cfg { - u16 usmsg_type; - u16 item_size; - u16 mem_type; - nsfw_ps_mem_create_fun create_fun; - nsfw_ps_mem_msg_to_memstr change_fun; + u16 usmsg_type; + u16 item_size; + u16 mem_type; + nsfw_ps_mem_create_fun create_fun; + nsfw_ps_mem_msg_to_memstr change_fun; } nsfw_ps_mem_item_cfg; -void *mem_item_free (void *pdata); -void *mem_item_lookup (void *pdata); -u8 mem_item_get_callargv (u16 msg_type, char *msg_body, char *memstr_buf, - i32 buf_len); +void *mem_item_free(void *pdata); +void *mem_item_lookup(void *pdata); +u8 mem_item_get_callargv(u16 msg_type, char *msg_body, char *memstr_buf, + i32 buf_len); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/ipc/ps/nsfw_ps_module.c b/src/framework/ipc/ps/nsfw_ps_module.c index 6e03e11..6d11c5f 100644 --- a/src/framework/ipc/ps/nsfw_ps_module.c +++ b/src/framework/ipc/ps/nsfw_ps_module.c @@ -17,9 +17,11 @@ #include <stdlib.h> #include "types.h" #include "nstack_securec.h" -#include "nsfw_init.h" +#include "nsfw_init_api.h" #include "nsfw_mgr_com_api.h" +#include "mgr_com.h" +#include "nsfw_alarm_api.h" #include "nsfw_ps_api.h" #include "nsfw_ps_module.h" #include "nsfw_mem_api.h" @@ -39,7 +41,6 @@ #include <linux/netlink.h> #include <dirent.h> #include <fnmatch.h> -#include "common_mem_common.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -57,8 +58,454 @@ struct list_head g_ps_runing_list; nsfw_ps_callback g_ps_init_callback[NSFW_PROC_MAX][NSFW_PS_MAX_CALLBACK]; nsfw_ps_info g_main_ps_info; +extern nsfw_mgr_init_cfg g_mgr_com_cfg; + void *g_ps_chk_timer = NULL; +/* keep count of processes being in EXITING state */ +u32 g_ps_exiting_cnt = 0; +NSTACK_STATIC void inc_ps_exiting_cnt(); +NSTACK_STATIC void dec_ps_exiting_cnt(); + +typedef struct _omc_alarm_status +{ + char send_succ_flag; + alarm_flag current_alarm_state; + nsfw_timer_info *resend_timer; +} omc_alarm_stat; + +#define SCRIPT_NS_CTL_SND_NSMAIN_NOR_ALM "./nStackCtrl --module alm -n nsMain -t normal" +#define SCRIPT_NS_CTL_SND_NSMAIN_ABNOR_ALM "./nStackCtrl --module alm -n nsMain -t abnormal" +#define SCRIPT_NS_CTL_SND_NSMAIN_START "./nStackCtrl --module alm -n nsMain -t normalStart" +#define SCRIPT_NS_CTL_SND_NSMAIN_EXIT "./nStackCtrl --module alm -n nsMain -t abnormalExit" + +#define MASTER_RESEND_NSMAIN_TIMER 1 + +omc_alarm_stat g_omc_alm_state[ALARM_EVENT_MAX]; + +typedef struct _omc_hf_alarm_status +{ + nsfw_timer_info *resend_timer; + hotfix_res res; +} omc_hf_alarm_stat; +omc_hf_alarm_stat g_omc_hf_alm_state; +#define MASTER_RESEND_HOTFIX_TIMER 1 + +const char *omc_get_nstackctrl_alarm_string(enum_alarm_id alarm_id, + alarm_flag alarm_state) +{ + const char *alarm_script = NULL; + + switch (alarm_id) + { + case ALARM_EVENT_NSTACK_MAIN_ABNORMAL_RESTART_FAIL: + + if (ALARM_PRODUCT == alarm_state) + { + alarm_script = SCRIPT_NS_CTL_SND_NSMAIN_ABNOR_ALM; + } + else + { + alarm_script = SCRIPT_NS_CTL_SND_NSMAIN_NOR_ALM; + } + + break; + case ALARM_EVENT_NSTACK_MAIN_EXIT_CAUSE_FD_FAIL: + + if (ALARM_PRODUCT == alarm_state) + { + alarm_script = SCRIPT_NS_CTL_SND_NSMAIN_EXIT; + } + else + { + alarm_script = SCRIPT_NS_CTL_SND_NSMAIN_START; + } + + break; + default: + NSAM_LOGERR("alarm_id is invalid"); + break; + } + + return alarm_script; + +} + +/* should send restore alarm when daemon-stack restart successfully*/ +int omc_resend_nsmain_alarm(u32 timer_type, void *argv) +{ +#define TMP_RESULT_BUF_LEN 128 + + int retval; + char result[TMP_RESULT_BUF_LEN] = { 0 }; + int rt_len; + const char *alarm_script = NULL; + enum_alarm_id tmp_alarm_id = (enum_alarm_id) argv; + omc_alarm_stat *tmp_alarm_stat = NULL; + + if (ALARM_ID_NOT_VALID(tmp_alarm_id)) + { + NSAM_LOGERR("alarm_id is invalid"); + return 0; + } + + tmp_alarm_stat = &g_omc_alm_state[tmp_alarm_id]; + + /* when timeout, need clear */ + tmp_alarm_stat->resend_timer = NULL; + + alarm_script = + omc_get_nstackctrl_alarm_string(tmp_alarm_id, + tmp_alarm_stat->current_alarm_state); + + if (NULL == alarm_script) + { + NSAM_LOGERR("get alarm_script fail"); + return 0; + } + + if (0 != tmp_alarm_stat->send_succ_flag) + { + rt_len = + nsfw_mgr_run_script(alarm_script, result, TMP_RESULT_BUF_LEN); + if (0 == rt_len || -1 == rt_len || (!nsfw_isdigitstr(result))) //also check return -1 + { + retval = -1; + } + else + { + retval = atoi(result); + } + tmp_alarm_stat->send_succ_flag = retval; + + if (0 == tmp_alarm_stat->send_succ_flag) + { + NSAM_LOGINF("send alarm success]alarm_id=%u,alarm_status=%u", + tmp_alarm_id + ALARM_ID_BASE_VALUE, + tmp_alarm_stat->current_alarm_state); + } + else + { + NSAM_LOGINF("send alarm fail]alarm_id=%u,alarm_status=%u", + tmp_alarm_id + ALARM_ID_BASE_VALUE, + tmp_alarm_stat->current_alarm_state); + /* only when send fail, start resend timer */ + struct timespec alarm_resend_time = + { ALARM_RESEND_TIMER_LENGTH, 0 }; + tmp_alarm_stat->resend_timer = + nsfw_timer_reg_timer(MASTER_RESEND_NSMAIN_TIMER, + (void *) tmp_alarm_id, + omc_resend_nsmain_alarm, + alarm_resend_time); + if (NULL == tmp_alarm_stat->resend_timer) + { + NSFW_LOGERR("start alarm resend timer fail"); + } + } + + } + + return 0; + +} + +/***************************************************************************** +* Prototype : omc_remove_resend_timer_inner +* Description : remove alarm resend timer if exist +* Input : None +* Output : None +* Return Value : None +* Calls : +* Called By : omc_send_nsmain_alarm_inner +*****************************************************************************/ +NSTACK_STATIC void omc_remove_resend_timer_inner(enum_alarm_id alarm_id) +{ + omc_alarm_stat *tmp_alarm_stat = NULL; + if (ALARM_ID_NOT_VALID(alarm_id)) + { + NSAM_LOGERR("alarm_id is invalid"); + return; + } + + tmp_alarm_stat = &g_omc_alm_state[alarm_id]; + + if (NULL == tmp_alarm_stat->resend_timer) + { + return; + } + + nsfw_timer_rmv_timer(tmp_alarm_stat->resend_timer); + tmp_alarm_stat->resend_timer = NULL; + +} + +/***************************************************************************** +* Prototype : omc_send_nsmain_alarm_inner +* Description : omc_send_nsmain_alarm_inner process function +* Input : init_status_flag ; alarm_flag alm_flag +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +void omc_send_nsmain_alarm_inner(char init_status_flag, + enum_alarm_id alarm_id, alarm_flag alm_flag) +{ +#define TMP_RESULT_BUF_LEN 128 + int retval; + char result[TMP_RESULT_BUF_LEN] = { 0 }; + int rt_len; + omc_alarm_stat *tmp_alarm_stat = NULL; + + const char *alarm_script = NULL; + + if (ALARM_ID_NOT_VALID(alarm_id)) + { + NSAM_LOGDBG("alarm_id is invalid"); + return; + } + + tmp_alarm_stat = &g_omc_alm_state[alarm_id]; + + if (1 != init_status_flag) + { + /* only for alarm status change, can send alarm */ + if (alm_flag == tmp_alarm_stat->current_alarm_state) + { + NSAM_LOGDBG("same status, can't send alarm"); + return; + } + } + else + { + /* init alarm, use current alarm state stored */ + alm_flag = tmp_alarm_stat->current_alarm_state; + } + + alarm_script = omc_get_nstackctrl_alarm_string(alarm_id, alm_flag); + + if (NULL == alarm_script) + { + NSAM_LOGERR("get alarm_script fail"); + return; + } + + rt_len = nsfw_mgr_run_script(alarm_script, result, TMP_RESULT_BUF_LEN); + + if (0 == rt_len || -1 == rt_len || (!nsfw_isdigitstr(result))) + { + retval = -1; + } + else + { + retval = atoi(result); + } + tmp_alarm_stat->current_alarm_state = alm_flag; + tmp_alarm_stat->send_succ_flag = retval; + + if (0 == tmp_alarm_stat->send_succ_flag) + { + NSAM_LOGINF("send alarm success]alarm_id=%d,alarm_status=%d", + alarm_id + ALARM_ID_BASE_VALUE, + tmp_alarm_stat->current_alarm_state); + + /* when send success, then stop resend timer */ + omc_remove_resend_timer_inner(alarm_id); + } + else + { + NSAM_LOGINF("send alarm fail]alarm_id=%d,alarm_status=%d", + alarm_id + ALARM_ID_BASE_VALUE, + tmp_alarm_stat->current_alarm_state); + struct timespec alarm_resend_time = { ALARM_RESEND_TIMER_LENGTH, 0 }; + + /* should clear the old timer before register a new one */ + omc_remove_resend_timer_inner(alarm_id); + + /* only start resend time when send failed */ + tmp_alarm_stat->resend_timer = + nsfw_timer_reg_timer(MASTER_RESEND_NSMAIN_TIMER, + (void *) (alarm_id), + omc_resend_nsmain_alarm, alarm_resend_time); + if (NULL == tmp_alarm_stat->resend_timer) + { + NSFW_LOGERR("start alarm resend timer fail"); + } + } + +} + +void omc_send_init_nsmain_alarm(enum_alarm_id alarm_id) +{ + omc_send_nsmain_alarm_inner(1, alarm_id, ALARM_CLEAN); +} + +void omc_send_nsmain_alarm(enum_alarm_id alarm_id, alarm_flag alm_flag) +{ + omc_send_nsmain_alarm_inner(0, alarm_id, alm_flag); +} + +/***************************************************************************** +* Prototype : omc_remove_hf_resend_timer_inner +* Description : remove hotfix alarm resend timer if exist +* Input : None +* Output : None +* Return Value : None +* Calls : +* Called By : omc_send_nsmain_alarm_inner +*****************************************************************************/ +NSTACK_STATIC void omc_remove_hf_resend_timer_inner() +{ + if (NULL != g_omc_hf_alm_state.resend_timer) + { + nsfw_timer_rmv_timer(g_omc_hf_alm_state.resend_timer); + g_omc_hf_alm_state.resend_timer = NULL; + } +} + +/***************************************************************************** +* Prototype : omc_send_hotfix_alarm_inner +* Description : +* Input : void +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int omc_send_hotfix_alarm_inner() +{ + int retval; + int rt_len; + char alarm_script[512] = { 0 }; + char res_buffer[128] = { 0 }; + + retval = sprintf_s(alarm_script, sizeof(alarm_script), + "./nStackCtrl --module alm -n hotfix -a %d -r %d -v\"%s\" -p %d", + g_omc_hf_alm_state.res.action, + g_omc_hf_alm_state.res.result, + g_omc_hf_alm_state.res.patch_version, + g_omc_hf_alm_state.res.proc_type); + if (-1 == retval) + { + NSAM_LOGERR("sprintf_s fail]ret=%d", retval); + return -1; + } + + rt_len = + nsfw_mgr_run_script(alarm_script, res_buffer, sizeof(res_buffer)); + if (0 == rt_len || -1 == rt_len || (!nsfw_isdigitstr(res_buffer))) + { + retval = -1; + } + else + { + retval = atoi(res_buffer); + } + + if (0 == retval) + { + NSAM_LOGINF("send hotfix alarm success]alarm_id=4"); + /* when send success, then stop resend timer */ + omc_remove_hf_resend_timer_inner(); + } + else + { + NSAM_LOGINF("send hotfix alarm fail]alarm_id=4"); + /* should clear the old timer before register a new one */ + omc_remove_hf_resend_timer_inner(); + + struct timespec alarm_resend_time = { ALARM_RESEND_TIMER_LENGTH, 0 }; + /* only start resend time when send failed */ + g_omc_hf_alm_state.resend_timer = + nsfw_timer_reg_timer(MASTER_RESEND_HOTFIX_TIMER, NULL, + omc_send_hotfix_alarm_inner, + alarm_resend_time); + if (NULL == g_omc_hf_alm_state.resend_timer) + { + NSFW_LOGERR("start hotfix alarm resend timer fail"); + } + } + + return 0; + +} + +/***************************************************************************** +* Prototype : omc_send_hotfix_alarm +* Description : called by hotfix module +* Input : void +* Output : None +* Return Value : void +* Calls : +* Called By : +*****************************************************************************/ +void omc_send_hotfix_alarm(int proc_type, int action, int result, + const char *version) +{ + g_omc_hf_alm_state.res.proc_type = (fw_poc_type) proc_type; + g_omc_hf_alm_state.res.action = (hotfix_optype) action; + g_omc_hf_alm_state.res.result = result; + int ret = strcpy_s(g_omc_hf_alm_state.res.patch_version, + sizeof(g_omc_hf_alm_state.res.patch_version), + version); + if (EOK != ret) + { + NSFW_LOGERR("strcpy_s failed]ret=%d", ret); + } + + (void) omc_send_hotfix_alarm_inner(); +} + +/* API for another module to get the global */ +u32 get_ps_exiting_cnt() +{ + return g_ps_exiting_cnt; +} + +/***************************************************************************** +* Prototype : inc_ps_exiting_cnt +* Description : g_ps_exiting_cnt++ +* Input : None +* Output : None +* Return Value : None +* Calls : +* Called By : nsfw_sw_ps_state( ,NSFW_PS_EXITING) ONLY! +*****************************************************************************/ +NSTACK_STATIC void inc_ps_exiting_cnt() +{ + if (g_ps_exiting_cnt < NSFW_MAX_PID) + { + g_ps_exiting_cnt++; + } + else + { + NSFW_LOGERR("g_ps_exiting_cnt would exceed NSFW_MAX_PID! now is %u", + g_ps_exiting_cnt); + } +} + +/***************************************************************************** +* Prototype : dec_ps_exiting_cnt +* Description : g_ps_exiting_cnt-- +* Input : None +* Output : None +* Return Value : None +* Calls : +* Called By : nsfw_sw_ps_state( ,NSFW_PS_EXIT) ONLY! +*****************************************************************************/ +NSTACK_STATIC void dec_ps_exiting_cnt() +{ + if (g_ps_exiting_cnt > 0) + { + g_ps_exiting_cnt--; + } + else + { + NSFW_LOGERR("g_ps_exiting_cnt would drop below zero! now is %u", + g_ps_exiting_cnt); + } +} + /***************************************************************************** * Prototype : nsfw_ps_reg_fun * Description : reg the callback fun when process state change @@ -71,34 +518,33 @@ void *g_ps_chk_timer = NULL; * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_reg_fun (nsfw_ps_info * pps_info, u8 ps_state, - nsfw_ps_proc_fun fun, void *argv) +u8 nsfw_ps_reg_fun(nsfw_ps_info * pps_info, u8 ps_state, + nsfw_ps_proc_fun fun, void *argv) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("reg pps_info nul]state=%d,fun=%p", ps_state, fun); - return FALSE; + NSFW_LOGERR("reg pps_info nul]state=%d,fun=%p", ps_state, fun); + return FALSE; } - u32 i; - for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) + u32 i; + for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) { - if (NULL == pps_info->callback[i].fun) + if (NULL == pps_info->callback[i].fun) { - pps_info->callback[i].fun = fun; - pps_info->callback[i].argv = argv; - pps_info->callback[i].state = ps_state; - NSFW_LOGDBG - ("reg fun suc]ps_info=%p,state=%d,fun=%p,argv=%p,i=%d", - pps_info, ps_state, fun, argv, i); - return TRUE; + pps_info->callback[i].fun = fun; + pps_info->callback[i].argv = argv; + pps_info->callback[i].state = ps_state; + NSFW_LOGDBG + ("reg fun suc]ps_info=%p,state=%d,fun=%p,argv=%p,i=%u", + pps_info, ps_state, fun, argv, i); + return TRUE; } } - NSFW_LOGERR ("reg fun failed]ps_info=%p,state=%d,fun=%p,argv=%p,i=%d", - pps_info, ps_state, fun, argv, i); - return FALSE; + NSFW_LOGERR("reg fun failed]ps_info=%p,state=%d,fun=%p,argv=%p,i=%u", + pps_info, ps_state, fun, argv, i); + return FALSE; } /***************************************************************************** @@ -114,35 +560,34 @@ nsfw_ps_reg_fun (nsfw_ps_info * pps_info, u8 ps_state, * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_reg_global_fun (u8 proc_type, u8 ps_state, nsfw_ps_proc_fun fun, - void *argv) +u8 nsfw_ps_reg_global_fun(u8 proc_type, u8 ps_state, nsfw_ps_proc_fun fun, + void *argv) { - if (NSFW_PROC_MAX <= proc_type) + if (NSFW_PROC_MAX <= proc_type) { - NSFW_LOGERR ("proc_type err]state=%u,fun=%p,type=%u", ps_state, fun, - proc_type); - return FALSE; + NSFW_LOGERR("proc_type err]state=%u,fun=%p,type=%u", ps_state, fun, + proc_type); + return FALSE; } - nsfw_ps_callback *cb_fun = g_ps_init_callback[proc_type]; - u32 i; - for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) + nsfw_ps_callback *cb_fun = g_ps_init_callback[proc_type]; + u32 i; + for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) { - if (NULL == cb_fun[i].fun) + if (NULL == cb_fun[i].fun) { - cb_fun[i].fun = fun; - cb_fun[i].argv = argv; - cb_fun[i].state = ps_state; - NSFW_LOGINF ("reg fun suc]type=%u,state=%u,fun=%p,argv=%p,i=%u", - proc_type, ps_state, fun, argv, i); - return TRUE; + cb_fun[i].fun = fun; + cb_fun[i].argv = argv; + cb_fun[i].state = ps_state; + NSFW_LOGINF("reg fun suc]type=%u,state=%u,fun=%p,argv=%p,i=%u", + proc_type, ps_state, fun, argv, i); + return TRUE; } } - NSFW_LOGERR ("reg fun ful failed]type=%u,state=%u,fun=%p,argv=%p,i=%u", - proc_type, ps_state, fun, argv, i); - return FALSE; + NSFW_LOGERR("reg fun ful failed]type=%u,state=%u,fun=%p,argv=%p,i=%u", + proc_type, ps_state, fun, argv, i); + return FALSE; } /***************************************************************************** @@ -155,28 +600,27 @@ nsfw_ps_reg_global_fun (u8 proc_type, u8 ps_state, nsfw_ps_proc_fun fun, * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_exit (nsfw_mgr_msg * msg) +int nsfw_ps_exit(nsfw_mgr_msg * msg) { - nsfw_ps_info *pps_info; - if (NULL == msg) + nsfw_ps_info *pps_info; + if (NULL == msg) { - NSFW_LOGERR ("msg nul!"); - return FALSE; + NSFW_LOGERR("msg nul!"); + return FALSE; } - nsfw_ps_info_msg *ps_msg = GET_USER_MSG (nsfw_ps_info_msg, msg); - pps_info = nsfw_ps_info_get (ps_msg->host_pid); - NSFW_LOGINF ("recv ps exit]host_pid=%d,ps_info=%p", ps_msg->host_pid, - pps_info); + nsfw_ps_info_msg *ps_msg = GET_USER_MSG(nsfw_ps_info_msg, msg); + pps_info = nsfw_ps_info_get(ps_msg->host_pid); + NSFW_LOGINF("recv ps exit]host_pid=%u,ps_info=%p", ps_msg->host_pid, + pps_info); - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("error msg pps_info nul]host_pid=%d", ps_msg->host_pid); - return true; + NSFW_LOGERR("error msg pps_info nul]host_pid=%u", ps_msg->host_pid); + return true; } - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_EXIT); - return TRUE; + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_EXIT); + return TRUE; } /***************************************************************************** @@ -189,60 +633,60 @@ nsfw_ps_exit (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -nsfw_ps_info * -nsfw_ps_info_fork_alloc (u32 parent_pid, u32 child_pid) +nsfw_ps_info *nsfw_ps_info_fork_alloc(u32 parent_pid, u32 child_pid) { - nsfw_ps_info *pps_info = NULL; - nsfw_ps_info *pps_info_parent = NULL; - pps_info_parent = nsfw_ps_info_get (parent_pid); - if (NULL == pps_info_parent) + nsfw_ps_info *pps_info = NULL; + nsfw_ps_info *pps_info_parent = NULL; + pps_info_parent = nsfw_ps_info_get(parent_pid); + if (NULL == pps_info_parent) { - NSFW_LOGERR ("pps_info_parent nul"); - return NULL; + NSFW_LOGERR("pps_info_parent nul"); + return NULL; } - pps_info = nsfw_ps_info_get (child_pid); - if (NULL == pps_info) + pps_info = nsfw_ps_info_get(child_pid); + if (NULL == pps_info) { - pps_info = nsfw_ps_info_alloc (child_pid, pps_info_parent->proc_type); - if (NULL == pps_info) + pps_info = + nsfw_ps_info_alloc(child_pid, pps_info_parent->proc_type, 0); + if (NULL == pps_info) { - NSFW_LOGERR - ("alloc ps_info failed!]ps_info=%p,host_pid=%u,child_pid=%u", - pps_info_parent, pps_info_parent->host_pid, child_pid); - return NULL; + NSFW_LOGERR + ("alloc ps_info failed!]ps_info=%p,host_pid=%u,child_pid=%u", + pps_info_parent, pps_info_parent->host_pid, child_pid); + return NULL; } } - else + else { - NSFW_LOGWAR - ("fork alloc mem before!]ps_info=%p,host_pid=%u,child_pid=%u", - pps_info_parent, pps_info_parent->host_pid, child_pid); + NSFW_LOGWAR + ("fork alloc mem before!]ps_info=%p,host_pid=%u,child_pid=%u", + pps_info_parent, pps_info_parent->host_pid, child_pid); } - NSFW_LOGWAR ("ps_info fork]ps_info=%p,host_pid=%u,child_pid=%u", - pps_info_parent, pps_info_parent->host_pid, child_pid); - pps_info->parent_pid = parent_pid; - if (EOK != - MEMCPY_S (pps_info->callback, sizeof (pps_info->callback), - pps_info_parent->callback, - sizeof (pps_info_parent->callback))) + NSFW_LOGWAR("ps_info fork]ps_info=%p,host_pid=%u,child_pid=%u", + pps_info_parent, pps_info_parent->host_pid, child_pid); + pps_info->parent_pid = parent_pid; + if (EOK != + memcpy_s(pps_info->callback, sizeof(pps_info->callback), + pps_info_parent->callback, + sizeof(pps_info_parent->callback))) { - nsfw_ps_info_free (pps_info); - NSFW_LOGERR ("ps_info set_failed"); - return NULL; + nsfw_ps_info_free(pps_info); + NSFW_LOGERR("ps_info set_failed"); + return NULL; } - if (EOK != - MEMCPY_S (pps_info->value, sizeof (pps_info->value), - pps_info_parent->value, sizeof (pps_info_parent->value))) + if (EOK != + memcpy_s(pps_info->value, sizeof(pps_info->value), + pps_info_parent->value, sizeof(pps_info_parent->value))) { - nsfw_ps_info_free (pps_info); - NSFW_LOGERR ("ps_info cpy_failed"); - return NULL; + nsfw_ps_info_free(pps_info); + NSFW_LOGERR("ps_info cpy_failed"); + return NULL; } - return pps_info; + return pps_info; } /***************************************************************************** @@ -255,64 +699,71 @@ nsfw_ps_info_fork_alloc (u32 parent_pid, u32 child_pid) * Calls : * Called By : *****************************************************************************/ -nsfw_ps_info * -nsfw_ps_info_alloc (u32 pid, u8 proc_type) +nsfw_ps_info *nsfw_ps_info_alloc(u32 pid, u8 proc_type, u8 realloc_flg) { - nsfw_ps_info *pps_info = NULL; - if (0 == nsfw_mem_ring_dequeue (g_ps_cfg.ps_info_pool, (void *) &pps_info)) + nsfw_ps_info *pps_info = NULL; + if (0 == nsfw_mem_ring_dequeue(g_ps_cfg.ps_info_pool, (void *) &pps_info)) { - NSFW_LOGERR ("alloc ps_info failed]pid=%u,type=%u", pid, proc_type); - return NULL; + NSFW_LOGERR("alloc ps_info falied]pid=%u,type=%u", pid, proc_type); + return NULL; } - if (NULL == pps_info) + if (NULL == pps_info) { - if (NSFW_PROC_MAIN != proc_type || TRUE == g_main_ps_info.alloc_flag) + if (NSFW_PROC_MAIN != proc_type || TRUE == g_main_ps_info.alloc_flag) { - NSFW_LOGERR ("alloc ps_info nul]pid=%u,type=%u", pid, proc_type); - return NULL; + NSFW_LOGERR("alloc ps_info nul]pid=%u,type=%u", pid, proc_type); + return NULL; } - pps_info = &g_main_ps_info; + pps_info = &g_main_ps_info; } - if (EOK != - MEMSET_S (pps_info, sizeof (nsfw_ps_info), 0, sizeof (nsfw_ps_info))) + if (EOK != + memset_s(pps_info, sizeof(nsfw_ps_info), 0, sizeof(nsfw_ps_info))) { - nsfw_ps_info_free (pps_info); - NSFW_LOGERR ("set failed"); - return NULL; + NSFW_LOGERR("memset_s failed"); + goto error; } - pps_info->proc_type = proc_type; - pps_info->host_pid = pid; - - if (proc_type < NSFW_PROC_MAX) + if (proc_type < NSFW_PROC_MAX) { - int retval; - retval = - MEMCPY_S (pps_info->callback, sizeof (pps_info->callback), - g_ps_init_callback[proc_type], sizeof (pps_info->callback)); - if (EOK != retval) + int retval = memcpy_s(pps_info->callback, sizeof(pps_info->callback), + g_ps_init_callback[proc_type], + sizeof(pps_info->callback)); + if (EOK != retval) { - NSFW_LOGERR ("Failed to MEMCPY_S]retval=%d", retval); - nsfw_ps_info_free (pps_info); - return NULL; + NSFW_LOGERR("memcpy failed]retval=%d", retval); + goto error; } } - list_add_tail (&pps_info->node, &g_ps_runing_list); - pps_info->alloc_flag = TRUE; + pps_info->proc_type = proc_type; + pps_info->host_pid = pid; + + list_add_tail(&pps_info->node, &g_ps_runing_list); - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_RUNNING); - if (pid < NSFW_MAX_PID) + pps_info->alloc_flag = TRUE; + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_RUNNING); + + if (pid < NSFW_MAX_PID) { - g_ps_info[pid].ps_info = pps_info; - g_ps_info[pid].proc_type = proc_type; + g_ps_info[pid].ps_info = pps_info; + if (!realloc_flg) /* If re-alloced, should keep the same as stored */ + { + g_ps_info[pid].proc_type = proc_type; + g_ps_info[pid].starttime = + (u32) (nsfw_ps_get_starttime_from_file(pid) & 0xFFFFFFFF); + } } - NSFW_LOGINF ("ps_info alloc]ps_info=%p,pid=%u,type=%u", pps_info, pid, - proc_type); - return pps_info; - + NSFW_LOGINF("ps_info alloc]ps_info=%p,pid=%u,type=%u", pps_info, pid, + proc_type); + return pps_info; + error: + if (1 != nsfw_mem_ring_enqueue(g_ps_cfg.ps_info_pool, pps_info)) + { + NSFW_LOGERR("nsfw_mem_ring_enqueue failed]ps_info=%p", pps_info); + } + return NULL; } /***************************************************************************** @@ -324,94 +775,83 @@ nsfw_ps_info_alloc (u32 pid, u8 proc_type) * Calls : * Called By : *****************************************************************************/ -inline nsfw_ps_info * -nsfw_ps_info_get (u32 pid) +inline nsfw_ps_info *nsfw_ps_info_get(u32 pid) { - if (pid < NSFW_MAX_PID) + if (pid < NSFW_MAX_PID) { - return g_ps_info[pid].ps_info; + return g_ps_info[pid].ps_info; } - return NULL; + return NULL; } -nsfw_ps_info * -nsfw_share_ps_info_get (u32 pid) +nsfw_ps_info *nsfw_share_ps_info_get(u32 pid) { - if (pid < NSFW_MAX_PID) + if (pid < NSFW_MAX_PID) { - return g_master_ps_info[pid].ps_info; + return g_master_ps_info[pid].ps_info; } - return NULL; + return NULL; } -/***************************************************************************** -* Prototype : nsfw_ps_info_free -* Description : free ps_info -* Input : nsfw_ps_info *ps_info -* Output : None -* Return Value : void -* Calls : -* Called By : -*****************************************************************************/ -void -nsfw_ps_info_free (nsfw_ps_info * ps_info) +void nsfw_ps_info_free(nsfw_ps_info * ps_info) { - if (NULL == ps_info) + if (NULL == ps_info) { - NSFW_LOGERR ("ps_info nul"); - return; + NSFW_LOGERR("ps_info nul"); + return; } - if (FALSE == ps_info->alloc_flag) + if (FALSE == ps_info->alloc_flag) { - NSFW_LOGERR ("ps_info refree]ps_info=%p,pid=%u,state=%u", ps_info, - ps_info->host_pid, ps_info->state); - return; + NSFW_LOGERR("ps_info refree]ps_info=%p,pid=%u,state=%u", ps_info, + ps_info->host_pid, ps_info->state); + return; } - if (NULL != ps_info->exit_timer_ptr) + if (NULL != ps_info->exit_timer_ptr) { - nsfw_timer_rmv_timer ((nsfw_timer_info *) ps_info->exit_timer_ptr); - ps_info->exit_timer_ptr = NULL; + nsfw_timer_rmv_timer((nsfw_timer_info *) ps_info->exit_timer_ptr); + ps_info->exit_timer_ptr = NULL; } - if (NULL != ps_info->resend_timer_ptr) + if (NULL != ps_info->resend_timer_ptr) { - nsfw_timer_rmv_timer ((nsfw_timer_info *) ps_info->resend_timer_ptr); - ps_info->resend_timer_ptr = NULL; + nsfw_timer_rmv_timer((nsfw_timer_info *) ps_info->resend_timer_ptr); + ps_info->resend_timer_ptr = NULL; } - if (NULL != ps_info->hbt_timer_ptr) + if (NULL != ps_info->hbt_timer_ptr) { - nsfw_timer_rmv_timer ((nsfw_timer_info *) ps_info->hbt_timer_ptr); - ps_info->hbt_timer_ptr = NULL; + nsfw_timer_rmv_timer((nsfw_timer_info *) ps_info->hbt_timer_ptr); + ps_info->hbt_timer_ptr = NULL; } - list_del (&ps_info->node); + list_del(&ps_info->node); - ps_info->alloc_flag = FALSE; + ps_info->alloc_flag = FALSE; - NSFW_LOGINF ("ps_info free]ps_info=%p,pid=%u,state=%u", ps_info, - ps_info->host_pid, ps_info->state); - if (ps_info != &g_main_ps_info) + NSFW_LOGINF("ps_info free]ps_info=%p,pid=%u,state=%u", ps_info, + ps_info->host_pid, ps_info->state); + if (ps_info != &g_main_ps_info) { - if (0 == nsfw_mem_ring_enqueue (g_ps_cfg.ps_info_pool, ps_info)) + if (0 == nsfw_mem_ring_enqueue(g_ps_cfg.ps_info_pool, ps_info)) { - NSFW_LOGERR ("ps_info free failed]ps_info=%p,pid=%u,state=%u", - ps_info, ps_info->host_pid, ps_info->state); - return; + NSFW_LOGERR("ps_info free failed]ps_info=%p,pid=%u,state=%u", + ps_info, ps_info->host_pid, ps_info->state); + return; } } - if (ps_info->host_pid < NSFW_MAX_PID) + if (ps_info->host_pid < NSFW_MAX_PID) { - g_ps_info[ps_info->host_pid].proc_type = 0; - g_ps_info[ps_info->host_pid].ps_info = NULL; + g_ps_info[ps_info->host_pid].proc_type = 0; + g_ps_info[ps_info->host_pid].ps_info = NULL; + g_ps_info[ps_info->host_pid].starttime = 0; } - return; + return; } /***************************************************************************** @@ -424,35 +864,35 @@ nsfw_ps_info_free (nsfw_ps_info * ps_info) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_exiting_timeout (u32 timer_type, void *data) +int nsfw_ps_exiting_timeout(u32 timer_type, void *data) { - nsfw_ps_info *pps_info = (nsfw_ps_info *) data; - NSFW_LOGINF ("ps_info timerout]pps_info=%p,pid=%u", pps_info, - pps_info->host_pid); - if (NULL == pps_info) + nsfw_ps_info *pps_info = (nsfw_ps_info *) data; + + if (NULL == pps_info) { - return TRUE; + return TRUE; } + NSFW_LOGINF("ps_info timerout]pps_info=%p,pid=%u", pps_info, + pps_info->host_pid); - pps_info->exit_timer_ptr = NULL; + pps_info->exit_timer_ptr = NULL; - if (TRUE == g_hbt_switch) + if (TRUE == g_hbt_switch) { - NSFW_LOGINF ("hbt off"); - struct timespec time_left = { NSFW_PS_WEXIT_TVLAUE, 0 }; - pps_info->exit_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_PS_WEXIT_TIMER, pps_info, - nsfw_ps_exiting_timeout, time_left); - return TRUE; + NSFW_LOGINF("hbt off"); + struct timespec time_left = { NSFW_PS_WEXIT_TVLAUE, 0 }; + pps_info->exit_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_PS_WEXIT_TIMER, pps_info, + nsfw_ps_exiting_timeout, time_left); + return TRUE; } - if (NSFW_PS_EXITING == pps_info->state) + if (NSFW_PS_EXITING == pps_info->state) { - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_EXIT); + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_EXIT); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -464,23 +904,22 @@ nsfw_ps_exiting_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_exit_end_notify (u32 pid) +u8 nsfw_ps_exit_end_notify(u32 pid) { - nsfw_mgr_msg *rsp_msg = - nsfw_mgr_msg_alloc (MGR_MSG_APP_EXIT_RSP, NSFW_PROC_MAIN); - if (NULL == rsp_msg) + nsfw_mgr_msg *rsp_msg = + nsfw_mgr_msg_alloc(MGR_MSG_APP_EXIT_RSP, g_mgr_com_cfg.proc_type); + if (NULL == rsp_msg) { - NSFW_LOGERR ("alloc rsp msg failed]pid=%u", pid); - return FALSE; + NSFW_LOGERR("alloc rsp msg failed]pid=%u", pid); + return FALSE; } - nsfw_ps_info_msg *ps_msg = GET_USER_MSG (nsfw_ps_info_msg, rsp_msg); - ps_msg->host_pid = pid; - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); - NSFW_LOGINF ("send exit rsp msg]pid=%u", pid); - return TRUE; + nsfw_ps_info_msg *ps_msg = GET_USER_MSG(nsfw_ps_info_msg, rsp_msg); + ps_msg->host_pid = pid; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + NSFW_LOGINF("send exit rsp msg]pid=%u", pid); + return TRUE; } /***************************************************************************** @@ -493,57 +932,63 @@ nsfw_ps_exit_end_notify (u32 pid) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_sw_ps_state (nsfw_ps_info * pps_info, u8 new_state) +u8 nsfw_sw_ps_state(nsfw_ps_info * pps_info, u8 new_state) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("pps_info nul!"); - return FALSE; + NSFW_LOGERR("pps_info nul!"); + return FALSE; } - NSFW_LOGINF ("sw]ps_info=%p,pid=%u,type=%u,old_state=%u,newstate=%u", - pps_info, pps_info->host_pid, pps_info->proc_type, - pps_info->state, new_state); + u8 old_state = pps_info->state; + NSFW_LOGINF("sw]ps_info=%p,pid=%u,type=%u,old_state=%u,newstate=%u", + pps_info, pps_info->host_pid, pps_info->proc_type, old_state, + new_state); + + if (NSFW_PS_HBT_FAILED != new_state) + { + pps_info->state = new_state; + } - i32 i, ret; - for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) + i32 i, ret; + for (i = 0; i < NSFW_PS_MAX_CALLBACK; i++) { - if (NULL == pps_info->callback[i].fun) + if (NULL == pps_info->callback[i].fun) { - /* NULL should be the last fun */ - break; + /* NULL should be the last fun */ + break; } - if (new_state == pps_info->callback[i].state) + if (new_state == pps_info->callback[i].state) { - ret = - pps_info->callback[i].fun (pps_info, pps_info->callback[i].argv); - NSFW_LOGINF ("callback fun]ps_info=%p,i=%d,fun=%p,argv=%p,ret=%d", - pps_info, i, pps_info->callback[i].fun, - pps_info->callback[i].argv, ret); + ret = + pps_info->callback[i].fun(pps_info, + pps_info->callback[i].argv); + NSFW_LOGINF("callback fun]ps_info=%p,i=%d,fun=%p,argv=%p,ret=%d", + pps_info, i, pps_info->callback[i].fun, + pps_info->callback[i].argv, ret); } } - if (NSFW_PS_HBT_FAILED != new_state) + if (NSFW_PS_EXIT == new_state) { - pps_info->state = new_state; - } - - if (NSFW_PS_EXIT == new_state) - { - nsfw_ps_info_free (pps_info); + nsfw_ps_info_free(pps_info); + if (NSFW_PS_EXITING == old_state) + { + dec_ps_exiting_cnt(); + } } - if (NSFW_PS_EXITING == new_state) + if (NSFW_PS_EXITING == new_state) { - struct timespec time_left = { NSFW_PS_WEXIT_TVLAUE, 0 }; - pps_info->exit_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_PS_WEXIT_TIMER, pps_info, - nsfw_ps_exiting_timeout, time_left); + struct timespec time_left = { NSFW_PS_WEXIT_TVLAUE, 0 }; + pps_info->exit_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_PS_WEXIT_TIMER, pps_info, + nsfw_ps_exiting_timeout, time_left); + inc_ps_exiting_cnt(); } - return TRUE; + return TRUE; } /***************************************************************************** @@ -555,108 +1000,112 @@ nsfw_sw_ps_state (nsfw_ps_info * pps_info, u8 new_state) * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_ps_get_netlink_socket () +i32 nsfw_ps_get_netlink_socket() { - int rc; - int nl_sock; - int size, size_len; - struct sockaddr_nl sa_nl; + int rc; + int nl_sock; + int size, size_len; + struct sockaddr_nl sockad_nl; - nl_sock = nsfw_base_socket (PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); - if (nl_sock == -1) + nl_sock = nsfw_base_socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); + if (nl_sock == -1) { - NSFW_LOGERR ("get netlink socket err]errno=%d", errno); - return -1; + NSFW_LOGERR("get netlink socket err]errno=%d", errno); + return -1; } - rc = nsfw_set_close_on_exec (nl_sock); - if (rc == -1) + /* close on exec */ + rc = nsfw_set_close_on_exec(nl_sock); + if (rc == -1) { - (void) nsfw_base_close (nl_sock); - NSFW_LOGERR ("set exec err]fd=%d, errno=%d", nl_sock, errno); - return -1; + (void) nsfw_base_close(nl_sock); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", nl_sock, errno); + return -1; } - sa_nl.nl_family = AF_NETLINK; - sa_nl.nl_groups = CN_IDX_PROC; - sa_nl.nl_pid = getpid (); + sockad_nl.nl_family = AF_NETLINK; + sockad_nl.nl_groups = CN_IDX_PROC; + sockad_nl.nl_pid = getpid(); - rc = nsfw_base_bind (nl_sock, (struct sockaddr *) &sa_nl, sizeof (sa_nl)); - if (rc == -1) + rc = nsfw_base_bind(nl_sock, (struct sockaddr *) &sockad_nl, + sizeof(sockad_nl)); + if (rc == -1) { - (void) nsfw_base_close (nl_sock); - NSFW_LOGERR ("netlink bind err]netlink_fd=%d, errno=%d", nl_sock, - errno); - return -1; + (void) nsfw_base_close(nl_sock); + NSFW_LOGERR("netlink bind err]netlink_fd=%d, errno=%d", nl_sock, + errno); + return -1; } - struct __attribute__ ((aligned (NLMSG_ALIGNTO))) - { - struct nlmsghdr nl_hdr; - struct __attribute__ ((__packed__)) + /* this struct will be use */ + struct __attribute__ ((aligned(NLMSG_ALIGNTO))) { - struct cn_msg cn_msg; - enum proc_cn_mcast_op cn_mcast; - }; - } nlcn_msg; - if (EOK != MEMSET_S (&nlcn_msg, sizeof (nlcn_msg), 0, sizeof (nlcn_msg))) + struct nlmsghdr nl_msg_hdr; + struct __attribute__ ((__packed__)) + { + struct cn_msg c_msg; + enum proc_cn_mcast_op c_mcast; + }; + } nlc_msg; + + if (EOK != memset_s(&nlc_msg, sizeof(nlc_msg), 0, sizeof(nlc_msg))) { - (void) nsfw_base_close (nl_sock); - NSFW_LOGERR ("netlink set failed]netlink_fd=%d", nl_sock); - return -1; + (void) nsfw_base_close(nl_sock); + NSFW_LOGERR("netlink set failed]netlink_fd=%d", nl_sock); + return -1; } - nlcn_msg.nl_hdr.nlmsg_len = sizeof (nlcn_msg); - nlcn_msg.nl_hdr.nlmsg_pid = getpid (); - nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE; + nlc_msg.nl_msg_hdr.nlmsg_len = sizeof(nlc_msg); + nlc_msg.nl_msg_hdr.nlmsg_pid = getpid(); + nlc_msg.nl_msg_hdr.nlmsg_type = NLMSG_DONE; - nlcn_msg.cn_msg.id.idx = CN_IDX_PROC; - nlcn_msg.cn_msg.id.val = CN_VAL_PROC; - nlcn_msg.cn_msg.len = sizeof (enum proc_cn_mcast_op); + nlc_msg.c_msg.id.idx = CN_IDX_PROC; + nlc_msg.c_msg.id.val = CN_VAL_PROC; + nlc_msg.c_msg.len = sizeof(enum proc_cn_mcast_op); - nlcn_msg.cn_mcast = PROC_CN_MCAST_LISTEN; - rc = nsfw_base_send (nl_sock, &nlcn_msg, sizeof (nlcn_msg), 0); - if (rc == -1) + nlc_msg.c_mcast = PROC_CN_MCAST_LISTEN; + rc = nsfw_base_send(nl_sock, &nlc_msg, sizeof(nlc_msg), 0); + if (rc == -1) { - (void) nsfw_base_close (nl_sock); - NSFW_LOGERR ("netlink send err]netlink_fd=%d, errno=%d", nl_sock, - errno); - return -1; + (void) nsfw_base_close(nl_sock); + NSFW_LOGERR("netlink send err]netlink_fd=%d, errno=%d", nl_sock, + errno); + return -1; } - NSFW_LOGINF ("netlink connect]netlink_fd=%d", nl_sock); - int val, len; - len = sizeof (val); - if (0 > - nsfw_base_getsockopt (nl_sock, SOL_SOCKET, SO_RCVBUF, &val, - (socklen_t *) & len)) + NSFW_LOGINF("netlink connect]netlink_fd=%d", nl_sock); + + int val = 0; + int len = sizeof(val); + if (0 > + nsfw_base_getsockopt(nl_sock, SOL_SOCKET, SO_RCVBUF, &val, + (socklen_t *) & len)) { - NSFW_LOGERR ("get socket opt err!]error=%d", errno); + NSFW_LOGERR("get socket opt err]error=%d", errno); } - else + else { - NSFW_LOGINF ("] SO_RCVBUF=0x%x", val); + NSFW_LOGINF("]SO_RCVBUF=0x%x", val); } - size = MAX_NET_LINK_BUF; - size_len = sizeof (size); - if (0 > - nsfw_base_setsockopt (nl_sock, SOL_SOCKET, SO_RCVBUFFORCE, - (void *) &size, (socklen_t) size_len)) + size = MAX_NET_LINK_BUF; + size_len = sizeof(size); + if (0 > + nsfw_base_setsockopt(nl_sock, SOL_SOCKET, SO_RCVBUFFORCE, + (void *) &size, (socklen_t) size_len)) { - NSFW_LOGERR ("set socket opt err!]error=%d", errno); + NSFW_LOGERR("set socket opt err]error=%d", errno); } - size_len = sizeof (size); - if (0 > - nsfw_base_getsockopt (nl_sock, SOL_SOCKET, SO_RCVBUF, (void *) &size, - (socklen_t *) & size_len)) + size_len = sizeof(size); + if (0 > + nsfw_base_getsockopt(nl_sock, SOL_SOCKET, SO_RCVBUF, (void *) &size, + (socklen_t *) & size_len)) { - NSFW_LOGERR ("get socket opt err!]error=%d", errno); + NSFW_LOGERR("get socket opt err]error=%d", errno); } - NSFW_LOGINF ("] SO_RCVBUF=0x%x", size); - return nl_sock; + NSFW_LOGINF("]SO_RCVBUF=0x%x", size); + return nl_sock; } /***************************************************************************** @@ -670,81 +1119,81 @@ nsfw_ps_get_netlink_socket () * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_change_fun (i32 epfd, i32 fd, u32 events) +int nsfw_ps_change_fun(i32 epfd, i32 fd, u32 events) { - i32 rc; - u32 host_pid; - nsfw_ps_info *pps_info = NULL; + i32 rc; + u32 host_pid; + nsfw_ps_info *pps_info = NULL; - struct __attribute__ ((aligned (NLMSG_ALIGNTO))) - { - struct nlmsghdr nl_hdr; - struct __attribute__ ((__packed__)) + /*this struct will be used */ + struct __attribute__ ((aligned(NLMSG_ALIGNTO))) { - struct cn_msg cn_msg; - struct proc_event proc_ev; - }; - } nlcn_msg; + struct nlmsghdr nl_msg_hdr; + struct __attribute__ ((__packed__)) + { + struct cn_msg c_msg; + struct proc_event p_ev; + }; + } nlc_msg; - if (!(events & EPOLLIN)) + if (!(events & EPOLLIN)) { - return TRUE; + return TRUE; } - while (1) + while (1) { - rc = nsfw_base_recv (fd, &nlcn_msg, sizeof (nlcn_msg), 0); - if (rc == 0) + rc = nsfw_base_recv(fd, &nlc_msg, sizeof(nlc_msg), 0); + if (rc == 0) { - NSFW_LOGWAR ("netlink recv 0]netlink_fd=%d,errno=%d", fd, errno); - break; + NSFW_LOGWAR("netlink recv 0]netlink_fd=%d,errno=%d", fd, errno); + break; } - else if (rc == -1) + else if (rc == -1) { - if (errno == EINTR || errno == EAGAIN) + if (errno == EINTR || errno == EAGAIN) { - break; + break; } - NSMON_LOGERR ("netlink recv]netlink_fd=%d,errno=%d", fd, errno); - if (errno == ENOBUFS) + NSMON_LOGERR("netlink recv]netlink_fd=%d,errno=%d", fd, errno); + if (errno == ENOBUFS) { - struct timespec time_left = { NSFW_PS_FIRST_CHK_TVLAUE, 0 }; - g_ps_chk_timer = - (void *) nsfw_timer_reg_timer (NSFW_PS_CHK_TIMER, - (void *) FALSE, - nsfw_ps_chk_timeout, - time_left); + struct timespec time_left = { NSFW_PS_FIRST_CHK_TVLAUE, 0 }; + g_ps_chk_timer = + (void *) nsfw_timer_reg_timer(NSFW_PS_CHK_TIMER, + (void *) FALSE, + nsfw_ps_chk_timeout, + time_left); } - break; + break; } - switch (nlcn_msg.proc_ev.what) + switch (nlc_msg.p_ev.what) { - case PROC_EVENT_EXIT: - host_pid = nlcn_msg.proc_ev.event_data.exit.process_pid; - pps_info = nsfw_ps_info_get (host_pid); - if (NULL == pps_info) - { - NSFW_LOGDBG ("pps info is null]host pid=%d", host_pid); - break; - } - - if (NSFW_PS_EXITING == pps_info->state) - { - NSFW_LOGERR ("double pid info]ps_info=%p,pid=%d", pps_info, - host_pid); - break; - } - - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_EXITING); - break; - default: - break; + case PROC_EVENT_EXIT: /*enum or int no effect here */ + host_pid = nlc_msg.p_ev.event_data.exit.process_pid; + pps_info = nsfw_ps_info_get(host_pid); + if (NULL == pps_info) + { + /*too many useless debug log, del NSFW_LOGDBG("pps info is null]host pid=%u", host_pid); */ + break; + } + + if (NSFW_PS_EXITING == pps_info->state) + { + NSFW_LOGERR("double pid info]ps_info=%p,pid=%u", + pps_info, host_pid); + break; + } + + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_EXITING); + break; + default: + break; } } - return TRUE; + return TRUE; } /***************************************************************************** @@ -755,22 +1204,21 @@ nsfw_ps_change_fun (i32 epfd, i32 fd, u32 events) * Return Value : u8 * Calls : * Called By : -* *****************************************************************************/ -u8 -nsfw_ps_start_netlink () +u8 nsfw_ps_start_netlink() { - i32 netlink_fd = nsfw_ps_get_netlink_socket (); - if (netlink_fd < 0) + + i32 netlink_fd = nsfw_ps_get_netlink_socket(); + if (netlink_fd < 0) { - NSFW_LOGERR ("get netlink failed!"); - return FALSE; + NSFW_LOGERR("get netlink failed!"); + return FALSE; } - NSFW_LOGINF ("start ps_info module!]netlink_fd=%d", netlink_fd); - (void) nsfw_mgr_reg_sock_fun (netlink_fd, nsfw_ps_change_fun); - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_APP_EXIT_RSP, nsfw_ps_exit); - return TRUE; + NSFW_LOGINF("start ps_info module!]netlink_fd=%d", netlink_fd); + (void) nsfw_mgr_reg_sock_fun(netlink_fd, nsfw_ps_change_fun); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_APP_EXIT_RSP, nsfw_ps_exit); + return TRUE; } /* for heartbeat check*/ @@ -786,26 +1234,32 @@ nsfw_thread_dogs g_thread_dogs[NSFW_MAX_THREAD_DOGS_COUNT]; * Calls : * Called By : *****************************************************************************/ -i32 -nsfw_all_thread_chk () +i32 nsfw_all_thread_chk() { - i32 count = -1; - u32 i; - for (i = 0; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) + i32 count = -1; + u32 i; + for (i = 0; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) { - if (FALSE == g_thread_dogs[i].alloc_flag) + if (FALSE == g_thread_dogs[i].alloc_flag) { - continue; + continue; } - if (count < g_thread_dogs[i].count) + if (count < g_thread_dogs[i].count) { - count = g_thread_dogs[i].count; + count = g_thread_dogs[i].count; } - g_thread_dogs[i].count++; + /* only if the thread abnormal, then output log */ + if (g_thread_dogs[i].count > 0) + { /* print thread_id, know which thread is abnormal */ + NSFW_LOGINF("hb_timeout]count=%d,thread_id=%u", + g_thread_dogs[i].count, g_thread_dogs[i].thread_id); + } + + g_thread_dogs[i].count++; } - return count; + return count; } /***************************************************************************** @@ -817,17 +1271,16 @@ nsfw_all_thread_chk () * Calls : * Called By : *****************************************************************************/ -inline u8 -nsfw_thread_chk_unreg () +inline u8 nsfw_thread_chk_unreg() { - if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) + if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) { - g_thread_dogs[t_val_idx].alloc_flag = FALSE; - g_thread_dogs[t_val_idx].count = 0; - g_thread_dogs[t_val_idx].thread_id = 0; - t_val_idx = 0; + g_thread_dogs[t_val_idx].alloc_flag = FALSE; + g_thread_dogs[t_val_idx].count = 0; + g_thread_dogs[t_val_idx].thread_id = 0; + t_val_idx = 0; } - return TRUE; + return TRUE; } /***************************************************************************** @@ -840,86 +1293,86 @@ nsfw_thread_chk_unreg () * Calls : * Called By : *****************************************************************************/ -inline u8 -nsfw_thread_chk () +inline u8 nsfw_thread_chk() { - u32 i; - if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) + u32 i; + if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) { - g_thread_dogs[t_val_idx].count = 0; - return TRUE; + g_thread_dogs[t_val_idx].count = 0; + return TRUE; } - for (i = 1; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) + for (i = 1; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) { - if ((FALSE == g_thread_dogs[i].alloc_flag) - && __sync_bool_compare_and_swap (&g_thread_dogs[i].alloc_flag, - FALSE, TRUE)) + /* + (1) use some fixed value but no effect (e506) + (2) it don't contain any extra commas (e505) + */ + if ((FALSE == g_thread_dogs[i].alloc_flag) + && __sync_bool_compare_and_swap(&g_thread_dogs[i].alloc_flag, + FALSE, TRUE)) { - t_val_idx = i; - break; + t_val_idx = i; + break; } } - if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) + if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) { - g_thread_dogs[t_val_idx].count = 0; - g_thread_dogs[t_val_idx].thread_id = syscall (SYS_gettid); + g_thread_dogs[t_val_idx].count = 0; + g_thread_dogs[t_val_idx].thread_id = syscall(SYS_gettid); } - return TRUE; + return TRUE; } -/***************************************************************** -Parameters : None -Return : -Description : -*****************************************************************/ -nsfw_thread_dogs * -nsfw_thread_getDog () +nsfw_thread_dogs *nsfw_thread_get_dog() { - u32 i; - nsfw_thread_dogs *retPtr = NULL; - if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) + u32 i; + nsfw_thread_dogs *retPtr = NULL; + if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) { - return &g_thread_dogs[t_val_idx]; + return &g_thread_dogs[t_val_idx]; } - for (i = 1; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) + for (i = 1; i < NSFW_MAX_THREAD_DOGS_COUNT; i++) { - if ((FALSE == g_thread_dogs[i].alloc_flag) - && __sync_bool_compare_and_swap (&g_thread_dogs[i].alloc_flag, - FALSE, TRUE)) + /* + (1) use some fixed value but no effect (e506) + (2) it don't contain any extra commas (e505) + */ + if ((FALSE == g_thread_dogs[i].alloc_flag) + && __sync_bool_compare_and_swap(&g_thread_dogs[i].alloc_flag, + FALSE, TRUE)) { - t_val_idx = i; - break; + t_val_idx = i; + break; } } - if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) + if (t_val_idx > 0 && t_val_idx < NSFW_MAX_THREAD_DOGS_COUNT) { - g_thread_dogs[t_val_idx].count = 0; - g_thread_dogs[t_val_idx].thread_id = syscall (SYS_gettid); - retPtr = &g_thread_dogs[t_val_idx]; + g_thread_dogs[t_val_idx].count = 0; + g_thread_dogs[t_val_idx].thread_id = syscall(SYS_gettid); + retPtr = &g_thread_dogs[t_val_idx]; } - return retPtr; + return retPtr; } pthread_t g_all_thread[MAX_THREAD] = { 0 }; -u8 -nsfw_reg_trace_thread (pthread_t tid) +u8 nsfw_reg_trace_thread(pthread_t tid) { - int i; - for (i = 0; i < MAX_THREAD; i++) + int i; + for (i = 0; i < MAX_THREAD; i++) { - if ((0 == g_all_thread[i]) - && __sync_bool_compare_and_swap (&g_all_thread[i], 0, tid)) + if ((0 == g_all_thread[i]) + && __sync_bool_compare_and_swap(&g_all_thread[i], 0, tid)) { - return TRUE; + return TRUE; } } - return FALSE; + return FALSE; } /***************************************************************************** @@ -931,75 +1384,73 @@ nsfw_reg_trace_thread (pthread_t tid) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_check_dst_init (u8 dst_proc_type) +u8 nsfw_ps_check_dst_init(u8 dst_proc_type) { - u8 ps_state = FALSE; - nsfw_mgr_msg *msg = - nsfw_mgr_msg_alloc (MGR_MSG_CHK_INIT_REQ, dst_proc_type); - if (NULL == msg) + u8 ps_state = FALSE; + nsfw_mgr_msg *msg = + nsfw_mgr_msg_alloc(MGR_MSG_CHK_INIT_REQ, dst_proc_type); + if (NULL == msg) { - NSFW_LOGERR ("alloc msg failed]dst_typ=%d", dst_proc_type); - return FALSE; + NSFW_LOGERR("alloc msg failed]dst_typ=%d", dst_proc_type); + return FALSE; } - nsfw_ps_chk_msg *ps_msg = GET_USER_MSG (nsfw_ps_chk_msg, msg); - ps_msg->ps_state = TRUE; + nsfw_ps_chk_msg *ps_msg = GET_USER_MSG(nsfw_ps_chk_msg, msg); + ps_msg->ps_state = TRUE; - nsfw_mgr_msg *rsp_msg = nsfw_mgr_null_rspmsg_alloc (); - if (NULL == rsp_msg) + nsfw_mgr_msg *rsp_msg = nsfw_mgr_null_rspmsg_alloc(); + if (NULL == rsp_msg) { - nsfw_mgr_msg_free (msg); - NSFW_LOGERR ("alloc rsp msg failed]dst_typ=%d", dst_proc_type); - return FALSE; + nsfw_mgr_msg_free(msg); + NSFW_LOGERR("alloc rsp msg failed]dst_typ=%d", dst_proc_type); + return FALSE; } - (void) nsfw_mgr_send_req_wait_rsp (msg, rsp_msg); + (void) nsfw_mgr_send_req_wait_rsp(msg, rsp_msg); - ps_msg = GET_USER_MSG (nsfw_ps_chk_msg, rsp_msg); - ps_state = ps_msg->ps_state; + ps_msg = GET_USER_MSG(nsfw_ps_chk_msg, rsp_msg); + ps_state = ps_msg->ps_state; - nsfw_mgr_msg_free (msg); - nsfw_mgr_msg_free (rsp_msg); - NSFW_LOGINF ("get peer state]dst_type=%d,state=%d", dst_proc_type, - ps_state); - return ps_state; + nsfw_mgr_msg_free(msg); + nsfw_mgr_msg_free(rsp_msg); + NSFW_LOGINF("get peer state]dst_type=%d,state=%d", dst_proc_type, + ps_state); + return ps_state; } /***************************************************************************** * Prototype : nsfw_ps_send_hbt -* Description : send heart beat message to peer +* Description : seng heart beat message to peer * Input : nsfw_ps_info* pps_info * Output : None * Return Value : u8 * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_send_hbt (nsfw_ps_info * pps_info) +u8 nsfw_ps_send_hbt(nsfw_ps_info * pps_info) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("null ps_info!"); - return FALSE; + NSFW_LOGERR("null ps_info!"); + return FALSE; } - nsfw_mgr_msg *req_msg = - nsfw_mgr_msg_alloc (MGR_MSG_CHK_HBT_REQ, pps_info->proc_type); - if (NULL == req_msg) + nsfw_mgr_msg *req_msg = + nsfw_mgr_msg_alloc(MGR_MSG_CHK_HBT_REQ, pps_info->proc_type); + if (NULL == req_msg) { - NSFW_LOGERR ("alloc req msg failed]pps_info=%p", pps_info); - return FALSE; + NSFW_LOGERR("alloc req msg failed]pps_info=%p", pps_info); + return FALSE; } - req_msg->dst_pid = pps_info->host_pid; - nsfw_ps_chk_msg *ps_msg = GET_USER_MSG (nsfw_ps_chk_msg, req_msg); - ps_msg->ps_state = TRUE; - u8 ret = nsfw_mgr_send_msg (req_msg); - nsfw_mgr_msg_free (req_msg); - NSFW_LOGDBG ("send hbt msg]ret=%d,pps_info=%p,pid=%d,type=%d", ret, - pps_info, pps_info->host_pid, pps_info->proc_type); - return ret; + req_msg->dst_pid = pps_info->host_pid; + nsfw_ps_chk_msg *ps_msg = GET_USER_MSG(nsfw_ps_chk_msg, req_msg); + ps_msg->ps_state = TRUE; + u8 ret = nsfw_mgr_send_msg(req_msg); + nsfw_mgr_msg_free(req_msg); + NSFW_LOGDBG("send hbt msg]ret=%d,pps_info=%p,pid=%u,type=%d", ret, + pps_info, pps_info->host_pid, pps_info->proc_type); + return ret; } /***************************************************************************** @@ -1011,29 +1462,51 @@ nsfw_ps_send_hbt (nsfw_ps_info * pps_info) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_recv_hbt (nsfw_mgr_msg * msg) +int nsfw_ps_recv_hbt(nsfw_mgr_msg * msg) { - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("error msg nul!"); - return FALSE; + NSFW_LOGERR("error msg nul!"); + return FALSE; } - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL == rsp_msg) + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) { - NSFW_LOGERR ("alloc rsp failed,drop msg!" MSGINFO, PRTMSG (msg)); - return FALSE; + NSFW_LOGERR("alloc rsp failed,drop msg!" MSGINFO, PRTMSG(msg)); + return FALSE; } - nsfw_ps_chk_msg *ps_msg = GET_USER_MSG (nsfw_ps_chk_msg, rsp_msg); - ps_msg->ps_state = TRUE; - ps_msg->thread_chk_count = nsfw_all_thread_chk (); - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); + nsfw_ps_chk_msg *ps_msg = GET_USER_MSG(nsfw_ps_chk_msg, rsp_msg); + ps_msg->ps_state = TRUE; + ps_msg->thread_chk_count = nsfw_all_thread_chk(); + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); - return TRUE; + return TRUE; +} + +void log_sys_process_info(void) +{ + /* get thread info which is running in 0 core cpu */ +#define GET_SYS_PROCESS_STATUS_INFO "ps c -w -T -e -O user,s,spid,%cpu,%mem,psr,start --sort -pcpu |grep -E 'PSR| R ' |grep -E 'PSR| 0 | 1 '" + /* check cpu usage of all thread for daemon-stack process, this cmd running need spend 180ms */ +#define GET_NSTACK_MAIN_PROCESS_STATUS_INFO "top -d 1 -H -p `pidof nStackMain` -n 1 -b" + char result[SPL_MAX_BUF_LEN] = { 0 }; + int retVal = + nsfw_mgr_run_script(GET_NSTACK_MAIN_PROCESS_STATUS_INFO, result, + SPL_MAX_BUF_LEN); + if (-1 != retVal) + { + NSFW_LOGWAR("NSTACK_MAIN=%d\n%s", retVal, result); + } + retVal = + nsfw_mgr_run_script(GET_SYS_PROCESS_STATUS_INFO, result, + SPL_MAX_BUF_LEN); + if (-1 != retVal) + { + NSFW_LOGWAR("SYS=%d\n%s", retVal, result); + } } /***************************************************************************** @@ -1045,66 +1518,75 @@ nsfw_ps_recv_hbt (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_recv_hbt_rsp (nsfw_mgr_msg * msg) +int nsfw_ps_recv_hbt_rsp(nsfw_mgr_msg * msg) { - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("error msg nul!"); - return FALSE; + NSFW_LOGERR("error msg nul!"); + return FALSE; } - nsfw_ps_chk_msg *ps_msg = GET_USER_MSG (nsfw_ps_chk_msg, msg); - if (TRUE != ps_msg->ps_state) + nsfw_ps_chk_msg *ps_msg = GET_USER_MSG(nsfw_ps_chk_msg, msg); + if (TRUE != ps_msg->ps_state) { - NSFW_LOGERR ("Heartbeat failed]pid=%u,type=%u", msg->src_pid, - msg->src_proc_type); - return FALSE; + NSFW_LOGERR("Heartbeat failed]pid=%u,type=%u", msg->src_pid, + msg->src_proc_type); + return FALSE; } - nsfw_ps_info *pps_info = nsfw_ps_info_get (msg->src_pid); - if (NULL == pps_info) + nsfw_ps_info *pps_info = nsfw_ps_info_get(msg->src_pid); + if (NULL == pps_info) { - NSFW_LOGERR ("get ps_info failed]pid=%u,type=%u,count=%d", - msg->src_pid, msg->src_proc_type, - ps_msg->thread_chk_count); - return FALSE; + NSFW_LOGERR("get ps_info failed]pid=%u,type=%u,count=%d", + msg->src_pid, msg->src_proc_type, + ps_msg->thread_chk_count); + return FALSE; } - if (0 == ps_msg->thread_chk_count) + if (0 == ps_msg->thread_chk_count) { - pps_info->hbt_failed_count = 0; - return TRUE; + pps_info->hbt_failed_count = 0; + + /* send daemon-stack normal alarm, when hb normal one time */ + omc_send_nsmain_alarm(ALARM_EVENT_NSTACK_MAIN_ABNORMAL_RESTART_FAIL, + ALARM_CLEAN); + return TRUE; } - if (pps_info->hbt_failed_count > (u32) ps_msg->thread_chk_count) + u32 tmp_hbt_failed_count = pps_info->hbt_failed_count; + + if (pps_info->hbt_failed_count > (u32) ps_msg->thread_chk_count) { - pps_info->hbt_failed_count = (u32) ps_msg->thread_chk_count; + pps_info->hbt_failed_count = (u32) ps_msg->thread_chk_count; } - NSFW_LOGERR ("Heartbeat failed]pid=%u,type=%u,count=%d,ps_count=%u", - msg->src_pid, msg->src_proc_type, ps_msg->thread_chk_count, - pps_info->hbt_failed_count); - return FALSE; + NSFW_LOGERR("Heartbeat failed]pid=%u,type=%u,count=%d,ps_count=%u", + msg->src_pid, msg->src_proc_type, ps_msg->thread_chk_count, + pps_info->hbt_failed_count); + /* for fast get sys process status info */ + if (1 == tmp_hbt_failed_count) + { + log_sys_process_info(); + } + return FALSE; } -int -nsfw_ps_reset_hbt (void *pps_info, void *argv) +int nsfw_ps_reset_hbt(void *pps_info, void *argv) { - nsfw_ps_info *ps_info = pps_info; - if (NULL == ps_info) + nsfw_ps_info *ps_info = pps_info; + if (NULL == ps_info) { - NSFW_LOGERR ("ps_info nul!"); - return FALSE; + NSFW_LOGERR("ps_info nul!"); + return FALSE; } - if (NSFW_PROC_MAIN != ps_info->proc_type) + if (NSFW_PROC_MAIN != ps_info->proc_type) { - return FALSE; + return FALSE; } - ps_info->hbt_failed_count = *(u32 *) argv; - return TRUE; + ps_info->hbt_failed_count = *(u32 *) argv; + return TRUE; } /***************************************************************************** @@ -1117,69 +1599,70 @@ nsfw_ps_reset_hbt (void *pps_info, void *argv) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_hbt_timeout (u32 timer_type, void *data) +int nsfw_ps_hbt_timeout(u32 timer_type, void *data) { - nsfw_ps_info *pps_info = (nsfw_ps_info *) data; + nsfw_ps_info *pps_info = (nsfw_ps_info *) data; - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("null ps_info!"); - return FALSE; + NSFW_LOGERR("null ps_info!"); + return FALSE; } - if (NULL == pps_info->hbt_timer_ptr) + if (NULL == pps_info->hbt_timer_ptr) { - NSFW_LOGERR ("hbt has stop]pps_info=%p", pps_info); - pps_info->hbt_failed_count = 0; - return TRUE; + NSFW_LOGERR("hbt has stop]pps_info=%p", pps_info); + pps_info->hbt_failed_count = 0; + return TRUE; } - if (TRUE == g_hbt_switch) + if (TRUE == g_hbt_switch) { - struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; - pps_info->hbt_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_CHK_HBT_TIMER, data, - nsfw_ps_hbt_timeout, time_left); - return TRUE; + struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; + pps_info->hbt_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_CHK_HBT_TIMER, data, + nsfw_ps_hbt_timeout, time_left); + return TRUE; } - /* nic init may cost a few seconds, master will restart main if heartbeat timeout */ - if (NSFW_SOFT_HBT_CHK_COUNT != NSFW_MAX_HBT_CHK_COUNT) + /* nic init may cost a few seconds, master will restart main if heartbeat timeout- Begin */ + if (NSFW_SOFT_HBT_CHK_COUNT != NSFW_MAX_HBT_CHK_COUNT) { - if (NSFW_SOFT_HBT_CHK_COUNT < NSFW_MAX_HBT_CHK_COUNT) + if (NSFW_SOFT_HBT_CHK_COUNT < NSFW_MAX_HBT_CHK_COUNT) { - u32 new_hbt_count = 0; - (void) nsfw_ps_iterator (nsfw_ps_reset_hbt, &new_hbt_count); + u32 new_hbt_count = 0; + (void) nsfw_ps_iterator(nsfw_ps_reset_hbt, &new_hbt_count); } - NSFW_MAX_HBT_CHK_COUNT = NSFW_SOFT_HBT_CHK_COUNT; + NSFW_MAX_HBT_CHK_COUNT = NSFW_SOFT_HBT_CHK_COUNT; } - if (NSFW_MAX_HBT_CHK_COUNT <= pps_info->hbt_failed_count) + if (NSFW_MAX_HBT_CHK_COUNT <= pps_info->hbt_failed_count) { - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_HBT_FAILED); - /*reset counter */ - pps_info->hbt_failed_count = 0; + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_HBT_FAILED); + /*reset counter */ + pps_info->hbt_failed_count = 0; } - if (TRUE != nsfw_ps_send_hbt (pps_info)) + if (TRUE != nsfw_ps_send_hbt(pps_info)) { } - if (pps_info->hbt_failed_count > 0) + struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; + pps_info->hbt_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_CHK_HBT_TIMER, data, + nsfw_ps_hbt_timeout, time_left); + + if (pps_info->hbt_failed_count > 0) { - NSFW_LOGWAR ("Heartbeat failed]pid=%u,ps_count=%u, max_count=%d", - pps_info->host_pid, pps_info->hbt_failed_count, - NSFW_MAX_HBT_CHK_COUNT); + NSFW_LOGWAR("Heartbeat failed]pid=%u,ps_count=%u, max_count=%d", + pps_info->host_pid, pps_info->hbt_failed_count, + NSFW_MAX_HBT_CHK_COUNT); + log_sys_process_info(); } - pps_info->hbt_failed_count++; - struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; - pps_info->hbt_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_CHK_HBT_TIMER, data, - nsfw_ps_hbt_timeout, time_left); - return TRUE; + pps_info->hbt_failed_count++; + return TRUE; } /***************************************************************************** @@ -1191,29 +1674,28 @@ nsfw_ps_hbt_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_hbt_start (nsfw_ps_info * pps_info) +u8 nsfw_ps_hbt_start(nsfw_ps_info * pps_info) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("null ps_info!"); - return FALSE; + NSFW_LOGERR("null ps_info"); + return FALSE; } - if (NULL != pps_info->hbt_timer_ptr) + if (NULL != pps_info->hbt_timer_ptr) { - NSFW_LOGERR ("hbt start before!]ps_info=%p,pid=%u,type=%u", pps_info, - pps_info->host_pid, pps_info->proc_type); - return FALSE; + NSFW_LOGERR("hbt start before]ps_info=%p,pid=%u,type=%u", pps_info, + pps_info->host_pid, pps_info->proc_type); + return FALSE; } - struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; - pps_info->hbt_timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_CHK_HBT_TIMER, (void *) pps_info, - nsfw_ps_hbt_timeout, time_left); - NSFW_LOGINF ("hbt start!]ps_info=%p,pid=%u,type=%u", pps_info, - pps_info->host_pid, pps_info->proc_type); - return TRUE; + struct timespec time_left = { NSFW_CHK_HBT_TVLAUE, 0 }; + pps_info->hbt_timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_CHK_HBT_TIMER, (void *) pps_info, + nsfw_ps_hbt_timeout, time_left); + NSFW_LOGINF("hbt start]ps_info=%p,pid=%u,type=%u", pps_info, + pps_info->host_pid, pps_info->proc_type); + return TRUE; } /***************************************************************************** @@ -1225,24 +1707,23 @@ nsfw_ps_hbt_start (nsfw_ps_info * pps_info) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_ps_hbt_stop (nsfw_ps_info * pps_info) +u8 nsfw_ps_hbt_stop(nsfw_ps_info * pps_info) { - if (NULL == pps_info) + if (NULL == pps_info) { - NSFW_LOGERR ("null ps_info!"); - return FALSE; + NSFW_LOGERR("null ps_info!"); + return FALSE; } - if (NULL != pps_info->hbt_timer_ptr) + if (NULL != pps_info->hbt_timer_ptr) { - nsfw_timer_rmv_timer ((nsfw_timer_info *) pps_info->hbt_timer_ptr); - pps_info->hbt_timer_ptr = NULL; + nsfw_timer_rmv_timer((nsfw_timer_info *) pps_info->hbt_timer_ptr); + pps_info->hbt_timer_ptr = NULL; } - NSFW_LOGINF ("hbt stop!]ps_info=%p,pid=%d,type=%d", pps_info, - pps_info->host_pid, pps_info->proc_type); - return TRUE; + NSFW_LOGINF("hbt stop!]ps_info=%p,pid=%u,type=%d", pps_info, + pps_info->host_pid, pps_info->proc_type); + return TRUE; } /***************************************************************************** @@ -1255,33 +1736,31 @@ nsfw_ps_hbt_stop (nsfw_ps_info * pps_info) * Calls : * Called By : *****************************************************************************/ -u32 -nsfw_ps_iterator (nsfw_ps_proc_fun fun, void *argv) +u32 nsfw_ps_iterator(nsfw_ps_proc_fun fun, void *argv) { - u32 count = 0; - nsfw_ps_info *pps_info = NULL; - struct list_head *tNode; + u32 count = 0; + nsfw_ps_info *pps_info = NULL; + struct list_head *tNode; - if (NULL == fun) + if (NULL == fun) { - NSFW_LOGERR ("fun null!"); - return count; + NSFW_LOGERR("fun null!"); + return count; } - LINT_LIST ()list_for_each_entry (pps_info, tNode, (&g_ps_runing_list), node) - { - (void) fun (pps_info, argv); - count++; - } + list_for_each_entry(pps_info, tNode, (&g_ps_runing_list), node) + { + (void) fun(pps_info, argv); + count++; + } - NSFW_LOGINF ("proc pid]count=%u", count); - return count; + NSFW_LOGINF("proc pid]count=%u", count); + return count; } -int -filter (const struct dirent *dir) +int filter(const struct dirent *dir) { - return !fnmatch ("[1-9]*", dir->d_name, 0); + return !fnmatch("[1-9]*", dir->d_name, 0); } /***************************************************************************** @@ -1293,37 +1772,36 @@ filter (const struct dirent *dir) * Calls : * Called By : *****************************************************************************/ -inline nsfw_ps_info * -nsfw_ps_realloc_pid (u32 pid, u8 realloc_flg) +inline nsfw_ps_info *nsfw_ps_realloc_pid(u32 pid, u8 realloc_flg) { - nsfw_ps_info *pps_info = NULL; - if (pid >= NSFW_MAX_PID) + nsfw_ps_info *pps_info = NULL; + if (pid >= NSFW_MAX_PID) { - return NULL; + return NULL; } - if (g_ps_info[pid].ps_info == NULL) + if (g_ps_info[pid].ps_info == NULL) { - return NULL; + return NULL; } - if (TRUE == realloc_flg) + if (TRUE == realloc_flg) { - pps_info = nsfw_ps_info_alloc (pid, g_ps_info[pid].proc_type); - if (NULL == pps_info) + pps_info = nsfw_ps_info_alloc(pid, g_ps_info[pid].proc_type, 1); + if (NULL == pps_info) { - NSFW_LOGERR ("alloc ps_info failed!]pid=%u,type=%u", pid, - g_ps_info[pid].proc_type); - return NULL; + NSFW_LOGERR("alloc ps_info failed!]pid=%u,type=%u", pid, + g_ps_info[pid].proc_type); + return NULL; } } - else + else { - pps_info = g_ps_info[pid].ps_info; + pps_info = g_ps_info[pid].ps_info; } - pps_info->rechk_flg = TRUE; - return pps_info; + pps_info->rechk_flg = TRUE; + return pps_info; } /***************************************************************************** @@ -1335,34 +1813,37 @@ nsfw_ps_realloc_pid (u32 pid, u8 realloc_flg) * Calls : * Called By : *****************************************************************************/ -void -nsfw_ps_reload_pid () +void nsfw_ps_reload_pid() { - struct dirent **namelist; - i32 n; - u32 host_pid; - nsfw_ps_info *pps_info = NULL; + struct dirent **namelist; + i32 n; + u32 host_pid; + nsfw_ps_info *pps_info = NULL; - n = scandir ("/proc", &namelist, filter, 0); - if (n < 0) + n = scandir("/proc", &namelist, filter, 0); + if (n < 0) { - NSFW_LOGERR ("buf null"); + NSFW_LOGERR("buf null"); } - else + else { - while (n--) + + while (n--) { - host_pid = strtol (namelist[n]->d_name, NULL, 10); - pps_info = nsfw_ps_info_get (host_pid); - if (NULL != pps_info) + host_pid = strtol(namelist[n]->d_name, NULL, 10); + pps_info = nsfw_ps_info_get(host_pid); + if ((NULL != pps_info) && /* There is a nStack app with this pid, and */ + (nsfw_ps_get_starttime_from_file(host_pid) == nsfw_ps_get_starttime_from_info(host_pid) /* starttime is the same */ + || 0 == nsfw_ps_get_starttime_from_info(host_pid)) /* or NA in earlier version of Master */ + ) { - pps_info->rechk_flg = FALSE; + pps_info->rechk_flg = FALSE; } - free (namelist[n]); + free(namelist[n]); } - free (namelist); + free(namelist); } - return; + return; } /***************************************************************************** @@ -1374,19 +1855,18 @@ nsfw_ps_reload_pid () * Calls : * Called By : *****************************************************************************/ -void -nsfw_ps_realloc_all_pid (u32 * main_pid, u8 realloc_flg) +void nsfw_ps_realloc_all_pid(u32 * main_pid, u8 realloc_flg) { - u32 i; - nsfw_ps_info *pps_info = NULL; - for (i = 0; i < NSFW_MAX_PID; i++) + u32 i; + nsfw_ps_info *pps_info = NULL; + for (i = 0; i < NSFW_MAX_PID; i++) { - pps_info = nsfw_ps_realloc_pid (i, realloc_flg); - if (NULL != main_pid) + pps_info = nsfw_ps_realloc_pid(i, realloc_flg); + if (NULL != main_pid) { - if (NULL != pps_info && NSFW_PROC_MAIN == pps_info->proc_type) + if (NULL != pps_info && NSFW_PROC_MAIN == pps_info->proc_type) { - (*main_pid) = i; + (*main_pid) = i; } } } @@ -1402,49 +1882,48 @@ nsfw_ps_realloc_all_pid (u32 * main_pid, u8 realloc_flg) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_chk_exit_timeout (u32 timer_type, void *data) +int nsfw_ps_chk_exit_timeout(u32 timer_type, void *data) { - u32 i; - nsfw_ps_info *pps_info = NULL; - u32 pid = (u64) data; + u32 i; + nsfw_ps_info *pps_info = NULL; + u32 pid = (u64) data; - /*main pid exit first */ - if (NULL != data) + /*main pid exit first */ + if (NULL != data) { - pps_info = nsfw_ps_info_get (pid); - if (NULL != pps_info && TRUE == pps_info->rechk_flg) + pps_info = nsfw_ps_info_get(pid); + if (NULL != pps_info && TRUE == pps_info->rechk_flg) { - if (NSFW_PS_EXITING != pps_info->state) + if (NSFW_PS_EXITING != pps_info->state) { - NSFW_LOGWAR ("rechk pid exit]ps_info=%p,pid=%u", pps_info, - pps_info->host_pid); - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_EXITING); - pps_info->rechk_flg = FALSE; + NSFW_LOGWAR("rechk pid exit]ps_info=%p,pid=%u", pps_info, + pps_info->host_pid); + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_EXITING); + pps_info->rechk_flg = FALSE; } } } - for (i = 0; i < NSFW_MAX_PID; i++) + for (i = 0; i < NSFW_MAX_PID; i++) { - pps_info = nsfw_ps_info_get (i); - if (NULL != pps_info && TRUE == pps_info->rechk_flg) + pps_info = nsfw_ps_info_get(i); + if (NULL != pps_info && TRUE == pps_info->rechk_flg) { - if (NSFW_PS_EXITING == pps_info->state) + if (NSFW_PS_EXITING == pps_info->state) { - NSFW_LOGWAR ("double pid info]ps_info=%p,pid=%u", pps_info, - pps_info->host_pid); - continue; + NSFW_LOGWAR("double pid info]ps_info=%p,pid=%u", pps_info, + pps_info->host_pid); + continue; } - NSFW_LOGWAR ("rechk pid exit]ps_info=%p,pid=%u", pps_info, - pps_info->host_pid); - (void) nsfw_sw_ps_state (pps_info, NSFW_PS_EXITING); - pps_info->rechk_flg = FALSE; + NSFW_LOGWAR("rechk pid exit]ps_info=%p,pid=%u", pps_info, + pps_info->host_pid); + (void) nsfw_sw_ps_state(pps_info, NSFW_PS_EXITING); + pps_info->rechk_flg = FALSE; } } - return TRUE; + return TRUE; } /***************************************************************************** @@ -1456,27 +1935,44 @@ nsfw_ps_chk_exit_timeout (u32 timer_type, void *data) * Return Value : int * Calls : * Called By : -****************************************************************************/ -int -nsfw_ps_chk_timeout (u32 timer_type, void *data) +*****************************************************************************/ +int nsfw_ps_chk_timeout(u32 timer_type, void *data) { - u32 main_pid = 0; - u8 realloc_flg = (u8) (u64) data; - - nsfw_ps_realloc_all_pid (&main_pid, realloc_flg); - nsfw_ps_reload_pid (); - - struct timespec time_left = { NSFW_PS_CHK_EXIT_TVLAUE, 0 }; - g_ps_chk_timer = - (void *) nsfw_timer_reg_timer (NSFW_PS_CHK_EXIT_TVLAUE, - (void *) (u64) main_pid, - nsfw_ps_chk_exit_timeout, time_left); - return TRUE; + u32 main_pid = 0; + u8 realloc_flg = (u8) (u64) data; + + nsfw_ps_realloc_all_pid(&main_pid, realloc_flg); + nsfw_ps_reload_pid(); + + struct timespec time_left = { NSFW_PS_CHK_EXIT_TVLAUE, 0 }; + g_ps_chk_timer = + (void *) nsfw_timer_reg_timer(NSFW_PS_CHK_EXIT_TVLAUE, + (void *) (u64) main_pid, + nsfw_ps_chk_exit_timeout, time_left); + return TRUE; +} + +int nsfw_ps_check_pid_nstack_status(int pid) +{ + + if (pid < 0 || pid >= NSFW_MAX_PID) + { + NSFW_LOGWAR("get wrong pid :%d", pid); + return -1; + } + + if (NULL == g_master_ps_info[pid].ps_info) + { + return -1; + } + + /* pid is using nstack */ + return 0; } /***************************************************************************** * Prototype : nsfw_ps_rechk_pid_exit -* Description : recheck pid exit +* Description : rechck pid exit * Input : nsfw_ps_proc_fun fun * void* argv * Output : None @@ -1484,203 +1980,329 @@ nsfw_ps_chk_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -int -nsfw_ps_rechk_pid_exit (nsfw_ps_pid_fun fun, void *argv) +int nsfw_ps_rechk_pid_exit(nsfw_ps_pid_fun fun, void *argv) { - u32 ulI = 0; - if (NULL == fun) + + u32 ulI = 0; + if (NULL == fun) { - NSFW_LOGERR ("input err! fun null"); - return -1; + NSFW_LOGERR("input err! fun null"); + return -1; } - u8 *ps_pid = malloc (NSFW_MAX_PID); - if (NULL == ps_pid) + u8 *ps_pid = malloc(NSFW_MAX_PID); + if (NULL == ps_pid) { - NSFW_LOGERR ("malloc failed"); - return -1; + NSFW_LOGERR("malloc failed"); + return -1; } - int retval = MEMSET_S (ps_pid, NSFW_MAX_PID, 0, NSFW_MAX_PID); - if (EOK != retval) + int retval = memset_s(ps_pid, NSFW_MAX_PID, 0, NSFW_MAX_PID); + if (EOK != retval) { - NSFW_LOGERR ("MEMSET_S failed]retval=%d", retval); - free (ps_pid); - return -1; + NSFW_LOGERR("memset_s failed]retval=%d", retval); + free(ps_pid); + return -1; } - struct dirent **namelist; - i32 n; - u32 host_pid; - n = scandir ("/proc", &namelist, filter, 0); - if (n < 0) + struct dirent **namelist; + i32 n; + u32 host_pid; + n = scandir("/proc", &namelist, filter, 0); + if (n < 0) { - NSFW_LOGERR ("buf null"); - free (ps_pid); - return -1; + NSFW_LOGERR("buf null"); + free(ps_pid); + return -1; } - while (n--) + while (n--) { - host_pid = strtol (namelist[n]->d_name, NULL, 10); - if (host_pid < NSFW_MAX_PID) + host_pid = strtol(namelist[n]->d_name, NULL, 10); + /* here should use host_pid as ps_pid's index */ + if (host_pid < NSFW_MAX_PID) { - ps_pid[ulI] = TRUE; + ps_pid[host_pid] = TRUE; } - free (namelist[n]); + free(namelist[n]); + namelist[n] = NULL; } - free (namelist); + free(namelist); - int count = 0; - for (ulI = 0; ulI < NSFW_MAX_PID; ulI++) + int count = 0; + for (ulI = 0; ulI < NSFW_MAX_PID; ulI++) { - if ((NULL != g_master_ps_info[ulI].ps_info) && (FALSE == ps_pid[ulI])) + if ((NULL != g_master_ps_info[ulI].ps_info) && (FALSE == ps_pid[ulI])) { - (void) fun (ulI, g_master_ps_info[ulI].proc_type, argv); - NSFW_LOGWAR ("rechk pid exit]pid=%d,type=%d", ulI, - g_master_ps_info[ulI].proc_type); - count++; - continue; + (void) fun(ulI, g_master_ps_info[ulI].proc_type, argv); + NSFW_LOGWAR("rechk pid exit]ulI=%u,type=%d", ulI, + g_master_ps_info[ulI].proc_type); + count++; + continue; } } - free (ps_pid); - return count; + free(ps_pid); + return count; } -void -nsfw_ps_cfg_set_chk_count (u16 count) +void nsfw_ps_cfg_set_chk_count(u16 count) { - g_ps_cfg.ps_chk_hbt_count = count; + g_ps_cfg.ps_chk_hbt_count = count; } -/***************************************************************************** -* Prototype : nsfw_ps_module_init -* Description : ps_module init -* Input : void* param -* Output : None -* Return Value : static int -* Calls : -* Called By : -*****************************************************************************/ -int -nsfw_ps_module_init (void *param) +u64 nsfw_ps_get_starttime_from_file(u32 pid) { - u32 proc_type = (u32) ((long long) param); - nsfw_ps_init_cfg *ps_cfg = &g_ps_cfg; - int retval; - nsfw_pid_item *pid_info = NULL; - NSFW_LOGINF ("ps module init]type=%u", proc_type); - - ps_cfg->ps_chk_hbt_count = NSFW_MAX_HBT_CHK_COUNT_DEF; - ps_cfg->ps_chk_hbt_tvalue = NSFW_CHK_HBT_TVLAUE_DEF; - ps_cfg->ps_chk_hbt_soft_count = ps_cfg->ps_chk_hbt_count; - - nsfw_mem_zone pzoneinfo; - pzoneinfo.isocket_id = NSFW_SOCKET_ANY; - pzoneinfo.stname.entype = NSFW_SHMEM; - pzoneinfo.length = sizeof (nsfw_pid_item) * NSFW_MAX_PID; - if (-1 == - SPRINTF_S (pzoneinfo.stname.aname, NSFW_MEM_NAME_LENGTH, "%s", - "MAS_PS_INFO")) - { - NSFW_LOGERR ("SPRINTF_S failed]"); - return -1; - } - - switch (proc_type) - { - case NSFW_PROC_MAIN: - { - pid_info = malloc (sizeof (nsfw_pid_item) * NSFW_MAX_PID); - if (NULL == pid_info) - { - NSFW_LOGERR ("malloc mem failed!"); - return -1; - } - - retval = - MEMSET_S (pid_info, (sizeof (nsfw_pid_item) * NSFW_MAX_PID), 0, - (sizeof (nsfw_pid_item) * NSFW_MAX_PID)); - if (EOK != retval) - { - NSFW_LOGERR ("MEMSET_S failed]retval=%d.\n", retval); - free (pid_info); - return -1; - } + if (pid > NSFW_MAX_PID) + { + NSFW_LOGERR("Invalid pid=%u", pid); + return 0; + } + + char str[20]; + if (sprintf_s(str, sizeof(str), "/proc/%u/stat", pid) < 0) + { + NSFW_LOGERR("sprintf_s failed, pid=%u", pid); + return 0; + } + + FILE *psfile = fopen(str, "r"); + if (NULL == psfile) + { + NSFW_LOGERR("fopen /proc/%u/stat failed", pid); + return 0; + } + + u64 starttime = 0; + const char PROC_PID_STAT_FORMAT_GET_STARTTIME_ONLY[] = "%*d " /* 1. pid */ + "%*s " /* 2. filename of exe */ + "%*c " /* 3. state */ + "%*d " /* 4. ppid */ + "%*d " /* 5. process group */ + "%*d " /* 6. session ID */ + "%*d " /* 7. tty_nr */ + "%*d " /* 8. tpgid */ + "%*u " /* 9. flags */ + "%*u " /* 10. minflt */ + "%*u " /* 11. cminflt */ + "%*u " /* 12. majflt */ + "%*u " /* 13. cmajflt */ + "%*u " /* 14. utime */ + "%*u " /* 15. stime */ + "%*d " /* 16. cuttime */ + "%*d " /* 17. cstime */ + "%*d " /* 18. priority */ + "%*d " /* 19. nice */ + "%*d " /* 20. num_threads */ + "%*d " /* 21. NA since Linux 2.6 */ + "%llu"; /* 22. starttime, we need this field */ + + int ret; + if ((ret = + fscanf_s(psfile, PROC_PID_STAT_FORMAT_GET_STARTTIME_ONLY, + &starttime)) != 1) + { + NSFW_LOGERR("fscanf_s /proc/%u/stat failed, ret=%d, errno=%d", pid, + ret, errno); + fclose(psfile); /*no need to check return */ + return 0; + } + + NSFW_LOGDBG("pid:%u, starttime:%llu", pid, starttime); + fclose(psfile); /*no need to check return */ + return starttime; +} - g_ps_info = pid_info; +u64 nsfw_ps_get_starttime_from_info(u32 pid) +{ + return (u64) (g_ps_info[pid].starttime); +} - pzoneinfo.stname.enowner = NSFW_PROC_MAIN; - pid_info = nsfw_mem_zone_create (&pzoneinfo); - if (NULL == pid_info) - { - NSFW_LOGERR ("create pid_info failed!"); - return -1; - } +int nsfw_ps_module_init(void *param) +{ + u32 proc_type = (u32) ((long long) param); + nsfw_ps_init_cfg *ps_cfg = &g_ps_cfg; + int retval; + nsfw_pid_item *pid_info = NULL; + enum_alarm_id loop_alarm_id = ALARM_EVENT_BASE; - g_master_ps_info = pid_info; - break; - } - default: - return 0; - } + NSFW_LOGINF("ps module init]type=%u", proc_type); - ps_cfg->ps_info_size = NSFW_PS_INFO_MAX_COUNT; - ps_cfg->ps_waite_exit_tvalue = NSFW_PS_WEXIT_TVLAUE_DEF; - ps_cfg->net_link_buf = MAX_NET_LINK_BUF_DEF; + ps_cfg->ps_chk_hbt_count = NSFW_MAX_HBT_CHK_COUNT_DEF; + ps_cfg->ps_chk_hbt_tvalue = NSFW_CHK_HBT_TVLAUE_DEF; + ps_cfg->ps_chk_hbt_soft_count = ps_cfg->ps_chk_hbt_count; - INIT_LIST_HEAD (&(g_ps_runing_list)); + nsfw_mem_zone pzoneinfo; + pzoneinfo.isocket_id = NSFW_SOCKET_ANY; + pzoneinfo.stname.entype = NSFW_SHMEM; + pzoneinfo.lenth = sizeof(nsfw_pid_item) * NSFW_MAX_PID; + if (-1 == + sprintf_s(pzoneinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + "MAS_PS_INFO")) + { + NSFW_LOGERR("sprintf_s failed]"); + return -1; + } - nsfw_mem_sppool pmpinfo; - pmpinfo.enmptype = NSFW_MRING_MPMC; - pmpinfo.usnum = ps_cfg->ps_info_size; - pmpinfo.useltsize = sizeof (nsfw_ps_info); - pmpinfo.isocket_id = NSFW_SOCKET_ANY; - pmpinfo.stname.entype = NSFW_NSHMEM; - if (-1 == - SPRINTF_S (pmpinfo.stname.aname, NSFW_MEM_NAME_LENGTH, "%s", - "MAS_PS_INFOPOOL")) + switch (proc_type) { - NSFW_LOGERR ("SPRINTF_S failed]"); - return -1; + case NSFW_PROC_MASTER: + { + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_CHK_HBT_RSP, + nsfw_ps_recv_hbt_rsp); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_CHK_INIT_REQ, + nsfw_ps_recv_hbt); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_CHK_HBT_REQ, + nsfw_ps_recv_hbt); + (void) NSFW_REG_SOFT_INT(NSFW_HBT_TIMER, NSFW_CHK_HBT_TVLAUE, + 1, 0xFFFF); + (void) NSFW_REG_SOFT_INT(NSFW_HBT_COUNT_PARAM, + NSFW_SOFT_HBT_CHK_COUNT, 1, 0xFFFF); + (void) NSFW_REG_SOFT_INT(NSFW_APP_EXIT_TIMER, + NSFW_PS_WEXIT_TVLAUE, 1, 0xFFFF); + + pid_info = nsfw_mem_zone_lookup(&pzoneinfo.stname); + if (NULL == pid_info) + { + pid_info = nsfw_mem_zone_create(&pzoneinfo); + if (NULL == pid_info) + { + NSFW_LOGERR("alloc rec nul!"); + return -1; + } + + retval = + memset_s(pid_info, + (sizeof(nsfw_pid_item) * NSFW_MAX_PID), 0, + (sizeof(nsfw_pid_item) * NSFW_MAX_PID)); + if (EOK != retval) + { + NSFW_LOGERR("memset_s failed]retval=%d.\n", retval); + return -1; + } + } + g_master_ps_info = pid_info; + + MEM_STAT(NSFW_PS_MODULE, pzoneinfo.stname.aname, NSFW_SHMEM, + pzoneinfo.lenth); + g_ps_info = pid_info; + + for (loop_alarm_id = ALARM_EVENT_BASE; + loop_alarm_id < ALARM_EVENT_MAX; loop_alarm_id++) + { + g_omc_alm_state[loop_alarm_id].send_succ_flag = 1; + g_omc_alm_state[loop_alarm_id].current_alarm_state = + ALARM_CLEAN; + g_omc_alm_state[loop_alarm_id].resend_timer = NULL; + } + + break; + } + case NSFW_PROC_MAIN: + { + + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_CHK_INIT_REQ, + nsfw_ps_recv_hbt); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_CHK_HBT_REQ, + nsfw_ps_recv_hbt); + pid_info = malloc(sizeof(nsfw_pid_item) * NSFW_MAX_PID); + if (NULL == pid_info) + { + NSFW_LOGERR("malloc mem failed!"); + return -1; + } + + retval = + memset_s(pid_info, + (sizeof(nsfw_pid_item) * NSFW_MAX_PID), 0, + (sizeof(nsfw_pid_item) * NSFW_MAX_PID)); + if (EOK != retval) + { + NSFW_LOGERR("memset_s failed]retval=%d.\n", retval); + free(pid_info); + return -1; + } + + g_ps_info = pid_info; + + pzoneinfo.stname.enowner = NSFW_PROC_MASTER; + pid_info = nsfw_mem_zone_lookup(&pzoneinfo.stname); + if (NULL == pid_info) + { + NSFW_LOGERR("lookup pid_info failed!"); + return -1; + } + + g_master_ps_info = pid_info; + break; + } + default: + return 0; } - ps_cfg->ps_info_pool = nsfw_mem_sp_create (&pmpinfo); + ps_cfg->ps_info_size = NSFW_PS_INFO_MAX_COUNT; + ps_cfg->ps_waite_exit_tvalue = NSFW_PS_WEXIT_TVLAUE_DEF; + ps_cfg->net_link_buf = MAX_NET_LINK_BUF_DEF; - if (!ps_cfg->ps_info_pool) + INIT_LIST_HEAD(&(g_ps_runing_list)); + + nsfw_mem_sppool pmpinfo; + pmpinfo.enmptype = NSFW_MRING_MPMC; + pmpinfo.usnum = ps_cfg->ps_info_size; + pmpinfo.useltsize = sizeof(nsfw_ps_info); + pmpinfo.isocket_id = NSFW_SOCKET_ANY; + pmpinfo.stname.entype = NSFW_NSHMEM; + if (-1 == + sprintf_s(pmpinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + "MAS_PS_INFOPOOL")) { - NSFW_LOGERR ("alloc ps info pool_err"); - return -1; + NSFW_LOGERR("sprintf_s failed]"); + return -1; } + ps_cfg->ps_info_pool = nsfw_mem_sp_create(&pmpinfo); - MEM_STAT (NSFW_PS_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, - nsfw_mem_get_len (ps_cfg->ps_info_pool, NSFW_MEM_SPOOL)); + if (!ps_cfg->ps_info_pool) + { + NSFW_LOGERR("alloc ps info pool_err"); + return -1; + } + + MEM_STAT(NSFW_PS_MODULE, pmpinfo.stname.aname, NSFW_NSHMEM, + nsfw_mem_get_len(ps_cfg->ps_info_pool, NSFW_MEM_SPOOL)); - if (NSFW_PROC_MAIN != proc_type) + if (NSFW_PROC_MASTER != proc_type) { - return 0; + return 0; } - struct timespec time_left = { NSFW_PS_FIRST_CHK_TVLAUE, 0 }; - g_ps_chk_timer = - (void *) nsfw_timer_reg_timer (NSFW_PS_CHK_TIMER, (void *) TRUE, - nsfw_ps_chk_timeout, time_left); + struct timespec time_left = { NSFW_PS_FIRST_CHK_TVLAUE, 0 }; + g_ps_chk_timer = (void *) nsfw_timer_reg_timer(NSFW_PS_CHK_TIMER, (void *) TRUE, /* the first call will re-alloc all pid */ + nsfw_ps_chk_timeout, + time_left); + /* There may be latency from process exiting to /proc being updated, Master needs to check multiple times */ + int itv; + for (itv = 1; itv < 5; itv++) + { + time_left.tv_sec += itv; /* increasing interval */ + g_ps_chk_timer = (void *) nsfw_timer_reg_timer(NSFW_PS_CHK_TIMER, (void *) FALSE, /* the latter calls should not re-alloc */ + nsfw_ps_chk_timeout, + time_left); + } - if (TRUE != nsfw_ps_start_netlink ()) + if (TRUE != nsfw_ps_start_netlink()) { - return -1; + return -1; } - return 0; + return 0; } /* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_PS_MODULE) -NSFW_MODULE_PRIORITY (10) -NSFW_MODULE_DEPENDS (NSFW_MGR_COM_MODULE) -NSFW_MODULE_DEPENDS (NSFW_TIMER_MODULE) -NSFW_MODULE_INIT (nsfw_ps_module_init) +NSFW_MODULE_NAME(NSFW_PS_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_DEPENDS(NSFW_MGR_COM_MODULE) +NSFW_MODULE_DEPENDS(NSFW_TIMER_MODULE) +NSFW_MODULE_INIT(nsfw_ps_module_init) /* *INDENT-ON* */ #ifdef __cplusplus diff --git a/src/framework/ipc/ps/nsfw_ps_module.h b/src/framework/ipc/ps/nsfw_ps_module.h index b754cea..ce2db13 100644 --- a/src/framework/ipc/ps/nsfw_ps_module.h +++ b/src/framework/ipc/ps/nsfw_ps_module.h @@ -29,10 +29,6 @@ extern "C"{ /*==============================================* * constants or macros define * *----------------------------------------------*/ - -#define NSFW_MAX_PID 65535 -COMPAT_PROTECT (NSFW_MAX_PID, 65535); - #define NSFW_PS_INFO_MAX_COUNT 4095 #define MAX_NET_LINK_BUF_DEF 0x34000*32 @@ -44,15 +40,15 @@ COMPAT_PROTECT (NSFW_MAX_PID, 65535); typedef struct _nsfw_ps_init_cfg { - u32 ps_info_size; - u32 net_link_buf; + u32 ps_info_size; + u32 net_link_buf; - u16 ps_waite_exit_tvalue; - u16 ps_chk_hbt_count; - u16 ps_chk_hbt_soft_count; - u16 ps_chk_hbt_tvalue; + u16 ps_waite_exit_tvalue; + u16 ps_chk_hbt_count; + u16 ps_chk_hbt_soft_count; + u16 ps_chk_hbt_tvalue; - mring_handle ps_info_pool; + mring_handle ps_info_pool; } nsfw_ps_init_cfg; #define NSFW_PS_CHK_TIMER 1 @@ -61,22 +57,24 @@ typedef struct _nsfw_ps_init_cfg typedef struct _nsfw_pid_item { - u8 proc_type; - u8 u8_reserve; - u16 u16_reserve; - u32 u32_reserve; - nsfw_ps_info *ps_info; + u8 proc_type; + u8 u8_reserve; + u16 u16_reserve; + u32 starttime; + nsfw_ps_info *ps_info; } nsfw_pid_item; -int nsfw_ps_change_fun (i32 epfd, i32 socket, u32 events); -u8 nsfw_sw_ps_state (nsfw_ps_info * pps_info, u8 new_state); +u32 get_ps_exiting_cnt(); + +int nsfw_ps_change_fun(i32 epfd, i32 socket, u32 events); +u8 nsfw_sw_ps_state(nsfw_ps_info * pps_info, u8 new_state); /* for heartbeat checking*/ #define NSFW_MAX_THREAD_DOGS_COUNT 8 #define NSFW_CHK_HBT_TIMER 1 #define NSFW_MAX_HBT_PROC_FUN 4 -#define NSFW_CHK_HBT_TVLAUE_DEF 1 +#define NSFW_CHK_HBT_TVLAUE_DEF 3 #define NSFW_MAX_HBT_CHK_COUNT (g_ps_cfg.ps_chk_hbt_count) #define NSFW_SOFT_HBT_CHK_COUNT (g_ps_cfg.ps_chk_hbt_soft_count) @@ -84,11 +82,11 @@ u8 nsfw_sw_ps_state (nsfw_ps_info * pps_info, u8 new_state); typedef struct _nsfw_ps_chk_msg { - u32 ps_state; - i32 thread_chk_count; + u32 ps_state; + i32 thread_chk_count; } nsfw_ps_chk_msg; -int nsfw_ps_chk_timeout (u32 timer_type, void *data); +int nsfw_ps_chk_timeout(u32 timer_type, void *data); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/ipc/ps/nsfw_recycle_module.c b/src/framework/ipc/ps/nsfw_recycle_module.c index 01e16fb..06d7dd5 100644 --- a/src/framework/ipc/ps/nsfw_recycle_module.c +++ b/src/framework/ipc/ps/nsfw_recycle_module.c @@ -17,7 +17,7 @@ #include <stdlib.h> #include "types.h" #include "nstack_securec.h" -#include "nsfw_init.h" +#include "nsfw_init_api.h" #include "nsfw_mgr_com_api.h" #include "nsfw_mem_api.h" @@ -27,7 +27,6 @@ #include "nsfw_recycle_module.h" #include "nsfw_maintain_api.h" #include "nstack_log.h" -#include "common_mem_api.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -35,7 +34,7 @@ extern "C"{ /* *INDENT-ON* */ #endif /* __cplusplus */ -/* only work on nStackMain*/ +/* only work on daemon-stack*/ nsfw_recycle_cfg g_rec_cfg; nsfw_recycle_fun g_rec_fun[NSFW_REC_TYPE_MAX] = { 0 }; @@ -44,7 +43,7 @@ nsfw_rec_fun_info g_rec_lock_fun[NSFW_REC_LOCK_REL_MAX_FUN]; /***************************************************************************** * Prototype : nsfw_recycle_reg_fun -* Description : reg one recycle type recycle function +* Description : reg one recycle type recycle funciton * Input : u16 rec_type * nsfw_recycle_fun fun * Output : None @@ -52,18 +51,17 @@ nsfw_rec_fun_info g_rec_lock_fun[NSFW_REC_LOCK_REL_MAX_FUN]; * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_recycle_reg_fun (u16 rec_type, nsfw_recycle_fun fun) +u8 nsfw_recycle_reg_fun(u16 rec_type, nsfw_recycle_fun fun) { - if (NULL == fun || rec_type >= NSFW_REC_TYPE_MAX) + if (NULL == fun || rec_type >= NSFW_REC_TYPE_MAX) { - NSFW_LOGERR ("argv err]fun=%p,type=%u", fun, rec_type); - return FALSE; + NSFW_LOGERR("argv err]fun=%p,type=%u", fun, rec_type); + return FALSE; } - g_rec_fun[rec_type] = fun; - NSFW_LOGINF ("reg]fun=%d,type=%u", fun, rec_type); - return TRUE; + g_rec_fun[rec_type] = fun; + NSFW_LOGINF("reg]fun=%p,type=%u", fun, rec_type); + return TRUE; } /***************************************************************************** @@ -77,31 +75,30 @@ nsfw_recycle_reg_fun (u16 rec_type, nsfw_recycle_fun fun) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_recycle_lock_rel_fun (nsfw_recycle_fun fun, void *data, u8 proc_type) +u8 nsfw_recycle_lock_rel_fun(nsfw_recycle_fun fun, void *data, u8 proc_type) { - if (NULL == fun) + if (NULL == fun) { - NSFW_LOGERR ("argv err]fun=%p,data=%p", fun, data); - return FALSE; + NSFW_LOGERR("argv err]fun=%p,data=%p", fun, data); + return FALSE; } - u32 i; + u32 i; - for (i = 0; i < NSFW_REC_LOCK_REL_MAX_FUN; i++) + for (i = 0; i < NSFW_REC_LOCK_REL_MAX_FUN; i++) { - if (NULL == g_rec_lock_fun[i].rec_fun) + if (NULL == g_rec_lock_fun[i].rec_fun) { - g_rec_lock_fun[i].rec_fun = fun; - g_rec_lock_fun[i].data = data; - g_rec_lock_fun[i].proc_type = proc_type; - NSFW_LOGINF ("reg mgr_msg fun suc]fun=%p,data=%p", fun, data); - return TRUE; + g_rec_lock_fun[i].rec_fun = fun; + g_rec_lock_fun[i].data = data; + g_rec_lock_fun[i].proc_type = proc_type; + NSFW_LOGINF("reg mgr_msg fun suc]fun=%p,data=%p", fun, data); + return TRUE; } } - NSFW_LOGINF ("reg]fun=%p,data=%p", fun, data); - return TRUE; + NSFW_LOGINF("reg]fun=%p,data=%p", fun, data); + return TRUE; } /***************************************************************************** @@ -113,26 +110,25 @@ nsfw_recycle_lock_rel_fun (nsfw_recycle_fun fun, void *data, u8 proc_type) * Calls : * Called By : *****************************************************************************/ -int -nsfw_recycle_exit_pid_lock (u32 pid, u8 proc_type, void *argv) +int nsfw_recycle_exit_pid_lock(u32 pid, u8 proc_type, void *argv) { - u32 i; - NSFW_LOGINF ("release lock]pid=%d,type=%d", pid, proc_type); - for (i = 0; i < NSFW_REC_LOCK_REL_MAX_FUN; i++) + u32 i; + NSFW_LOGINF("release lock]pid=%u,type=%d", pid, proc_type); + for (i = 0; i < NSFW_REC_LOCK_REL_MAX_FUN; i++) { - if (NULL == g_rec_lock_fun[i].rec_fun) + if (NULL == g_rec_lock_fun[i].rec_fun) { - break; + break; } - if ((NSFW_PROC_NULL == g_rec_lock_fun[i].proc_type) - || (proc_type == g_rec_lock_fun[i].proc_type)) + if ((NSFW_PROC_NULL == g_rec_lock_fun[i].proc_type) + || (proc_type == g_rec_lock_fun[i].proc_type)) { - (void) g_rec_lock_fun[i].rec_fun (pid, g_rec_lock_fun[i].data, 0); + (void) g_rec_lock_fun[i].rec_fun(pid, g_rec_lock_fun[i].data, 0); } } - return 0; + return 0; } /***************************************************************************** @@ -144,23 +140,22 @@ nsfw_recycle_exit_pid_lock (u32 pid, u8 proc_type, void *argv) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_recycle_obj_end (u32 pid) +u8 nsfw_recycle_obj_end(u32 pid) { - nsfw_mgr_msg *rsp_msg = - nsfw_mgr_msg_alloc (MGR_MSG_RCC_END_REQ, NSFW_PROC_MAIN); - if (NULL == rsp_msg) + nsfw_mgr_msg *rsp_msg = + nsfw_mgr_msg_alloc(MGR_MSG_RCC_END_REQ, NSFW_PROC_MAIN); + if (NULL == rsp_msg) { - NSFW_LOGERR ("alloc rsp msg failed]pid=%u", pid); - return FALSE; + NSFW_LOGERR("alloc rsp msg failed]pid=%u", pid); + return FALSE; } - nsfw_ps_info_msg *ps_msg = GET_USER_MSG (nsfw_ps_info_msg, rsp_msg); - ps_msg->host_pid = pid; - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); - NSFW_LOGINF ("send obj end msg]pid=%d", pid); - return TRUE; + nsfw_ps_info_msg *ps_msg = GET_USER_MSG(nsfw_ps_info_msg, rsp_msg); + ps_msg->host_pid = pid; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + NSFW_LOGINF("send obj end msg]pid=%u", pid); + return TRUE; } /***************************************************************************** @@ -173,74 +168,74 @@ nsfw_recycle_obj_end (u32 pid) * Calls : * Called By : *****************************************************************************/ -nsfw_rcc_stat -nsfw_recycle_callback_all_obj (u32 pid, nsfw_recycle_pool * rec_pool) +nsfw_rcc_stat nsfw_recycle_callback_all_obj(u32 pid, + nsfw_recycle_pool * rec_pool) { - u32 match = 0; - nsfw_recycle_obj *obj = NULL; - if (NULL == rec_pool) + u32 match = 0; + nsfw_recycle_obj *obj = NULL; + if (NULL == rec_pool) { - return NSFW_RCC_CONTINUE; + return NSFW_RCC_CONTINUE; } - nsfw_recycle_obj *p_start = rec_pool->obj; - u32 i; - u32 size = rec_pool->pool_size; + nsfw_recycle_obj *p_start = rec_pool->obj; + u32 i; + u32 size = rec_pool->pool_size; - nsfw_ps_info *pps_info; - pps_info = nsfw_ps_info_get (pid); - if (NULL == pps_info) + nsfw_ps_info *pps_info; + pps_info = nsfw_ps_info_get(pid); + if (NULL == pps_info) { - NSFW_LOGERR ("get ps_info failed!]pid=%d", pid); - return NSFW_RCC_CONTINUE; + NSFW_LOGERR("get ps_info falied!]pid=%d", pid); + return NSFW_RCC_CONTINUE; } - i32 cur_idx = (i32) (u64) nsfw_ps_get_uv (pps_info, NSFW_REC_IDX); + i32 cur_idx = (i32) (u64) nsfw_ps_get_uv(pps_info, NSFW_REC_IDX); - if (-1 == cur_idx) + if (-1 == cur_idx) { - cur_idx = 0; - nsfw_ps_set_uv (pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); - (void) nsfw_recycle_exit_pid_lock (pid, NSFW_PROC_APP, NULL); + cur_idx = 0; + nsfw_ps_set_uv(pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); + (void) nsfw_recycle_exit_pid_lock(pid, NSFW_PROC_APP, NULL); } - else + else { - cur_idx++; - nsfw_ps_set_uv (pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); + cur_idx++; + nsfw_ps_set_uv(pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); } - for (i = cur_idx; i < size; i++) + for (i = cur_idx; i < size; i++) { - obj = &p_start[i]; - cur_idx = i; - nsfw_ps_set_uv (pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); - if (FALSE == obj->alloc_flag) + obj = &p_start[i]; + cur_idx = i; + nsfw_ps_set_uv(pps_info, NSFW_REC_IDX, (void *) (u64) cur_idx); + if (FALSE == obj->alloc_flag) { - continue; + continue; } - if ((obj->rec_type < NSFW_REC_TYPE_MAX) - && (NULL != g_rec_fun[obj->rec_type])) + if ((obj->rec_type < NSFW_REC_TYPE_MAX) + && (NULL != g_rec_fun[obj->rec_type])) { - match++; - if (NSFW_RCC_SUSPEND == - g_rec_fun[obj->rec_type] (pid, obj->data, obj->rec_type)) + match++; + if (NSFW_RCC_SUSPEND == + g_rec_fun[obj->rec_type] (pid, obj->data, obj->rec_type)) { - NSFW_LOGINF - ("call suspend]type=%d,obj_pid=%d,pid=%d,count=%d", - obj->rec_type, obj->host_pid, pid, match); - return NSFW_RCC_SUSPEND; + NSFW_LOGINF + ("call suspend]type=%d,obj_pid=%d,pid=%d,count=%d", + obj->rec_type, obj->host_pid, pid, match); + return NSFW_RCC_SUSPEND; } } - else + else { - NSFW_LOGERR ("obj_error!drop]type=%d,obj_pid=%d,pid=%d", - obj->rec_type, obj->host_pid, pid); + NSFW_LOGERR("obj_error!drop]type=%d,obj_pid=%u,pid=%u", + obj->rec_type, obj->host_pid, pid); } } - NSFW_LOGWAR ("rec obj]pid=%d,count=%d,cur_idx=%d", pid, match, cur_idx); - return NSFW_RCC_CONTINUE; + NSFW_LOGWAR("rec obj]pid=%u,match=%u,cur_idx=%d", pid, match, cur_idx); + return NSFW_RCC_CONTINUE; } /***************************************************************************** @@ -252,75 +247,67 @@ nsfw_recycle_callback_all_obj (u32 pid, nsfw_recycle_pool * rec_pool) * Calls : * Called By : *****************************************************************************/ -u8 -nsfw_recycle_pid_obj (u32 pid) +u8 nsfw_recycle_pid_obj(u32 pid) { - nsfw_ps_info *pps_info; - pps_info = nsfw_ps_info_get (pid); - if (NULL == pps_info) + nsfw_ps_info *pps_info; + pps_info = nsfw_ps_info_get(pid); + if (NULL == pps_info) { - NSFW_LOGERR ("get ps_info failed!]pid=%d", pid); - return FALSE; + NSFW_LOGERR("get ps_info falied]pid=%u", pid); + return FALSE; } - nsfw_recycle_pool *rec_pool = g_rec_cfg.mem_rec_obj_pool; - void *timer_ptr = nsfw_ps_get_uv (pps_info, NSFW_REC_TIMER); - if (NSFW_RCC_SUSPEND == nsfw_recycle_callback_all_obj (pid, rec_pool)) + nsfw_recycle_pool *rec_pool = g_rec_cfg.mem_rec_obj_pool; + void *timer_ptr = nsfw_ps_get_uv(pps_info, NSFW_REC_TIMER); + if (NSFW_RCC_SUSPEND == nsfw_recycle_callback_all_obj(pid, rec_pool)) { - if (NULL != timer_ptr) + if (NULL != timer_ptr) { - nsfw_timer_rmv_timer (timer_ptr); - timer_ptr = NULL; + nsfw_timer_rmv_timer(timer_ptr); + timer_ptr = NULL; } - struct timespec time_left = { NSFW_REC_WEND_TVLAUE, 0 }; - timer_ptr = - (void *) nsfw_timer_reg_timer (NSFW_REC_WEND_TIMER, - (void *) (u64) pid, - nsfw_recycle_obj_timeout, time_left); - nsfw_ps_set_uv (pps_info, NSFW_REC_TIMER, timer_ptr); - return TRUE; + struct timespec time_left = { NSFW_REC_WEND_TVLAUE, 0 }; + timer_ptr = + (void *) nsfw_timer_reg_timer(NSFW_REC_WEND_TIMER, + (void *) (u64) pid, + nsfw_recycle_obj_timeout, + time_left); + nsfw_ps_set_uv(pps_info, NSFW_REC_TIMER, timer_ptr); + return TRUE; } - if (NULL != timer_ptr) + if (NULL != timer_ptr) { - nsfw_timer_rmv_timer (timer_ptr); - nsfw_ps_set_uv (pps_info, NSFW_REC_TIMER, NULL); + nsfw_timer_rmv_timer(timer_ptr); + nsfw_ps_set_uv(pps_info, NSFW_REC_TIMER, NULL); } - (void) nsfw_ps_exit_end_notify (pid); - nsfw_ps_info_free (pps_info); - return TRUE; + (void) nsfw_ps_exit_end_notify(pid); + if (pps_info->proc_type == NSFW_PROC_MASTER) + { + nsfw_ps_info_free(pps_info); + } + return TRUE; } -/***************************************************************************** -* Prototype : nsfw_recycle_all_obj -* Description : -* Input : u32 pid -* nsfw_mem_addr_msg *addr_msg -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -nsfw_recycle_all_obj (u32 pid) +u8 nsfw_recycle_all_obj(u32 pid) { - nsfw_ps_info *pps_info; - pps_info = nsfw_ps_info_get (pid); - if (NULL == pps_info) + nsfw_ps_info *pps_info; + pps_info = nsfw_ps_info_get(pid); + if (NULL == pps_info) { - pps_info = nsfw_ps_info_alloc (pid, NSFW_PROC_APP); - if (NULL == pps_info) + pps_info = nsfw_ps_info_alloc(pid, NSFW_PROC_APP, 0); + if (NULL == pps_info) { - NSFW_LOGERR ("alloc ps_info failed!]pid=%u", pid); - return FALSE; + NSFW_LOGERR("alloc ps_info falied!]pid=%u", pid); + return FALSE; } } - nsfw_ps_set_uv (pps_info, NSFW_REC_IDX, (void *) (-1)); - nsfw_ps_set_uv (pps_info, NSFW_REC_TIMER, NULL); - return nsfw_recycle_pid_obj (pid); + nsfw_ps_set_uv(pps_info, NSFW_REC_IDX, (void *) (-1)); + nsfw_ps_set_uv(pps_info, NSFW_REC_TIMER, NULL); + return nsfw_recycle_pid_obj(pid); } /***************************************************************************** @@ -332,27 +319,26 @@ nsfw_recycle_all_obj (u32 pid) * Calls : * Called By : *****************************************************************************/ -int -mem_app_exit_proc (nsfw_mgr_msg * msg) +int mem_app_exit_proc(nsfw_mgr_msg * msg) { - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("msg nul"); - return FALSE; + NSFW_LOGERR("msg nul"); + return FALSE; } - nsfw_ps_info_msg *ps_info_msg = GET_USER_MSG (nsfw_ps_info_msg, msg); + nsfw_ps_info_msg *ps_info_msg = GET_USER_MSG(nsfw_ps_info_msg, msg); - /* look up the app rec memzone and release all resource */ - /* no need to send rsp for it will be send after stack process over */ - if (TRUE == nsfw_recycle_all_obj (ps_info_msg->host_pid)) + /* look up the app rec memzone and release all resource */ + /* no need to send rsp for it will be send after stack process over */ + if (TRUE == nsfw_recycle_all_obj(ps_info_msg->host_pid)) { - NSFW_LOGINF ("obj found!]pid=%d", ps_info_msg->host_pid); - return TRUE; + NSFW_LOGINF("obj found!]pid=%u", ps_info_msg->host_pid); + return TRUE; } - (void) nsfw_ps_exit_end_notify (ps_info_msg->host_pid); - return FALSE; + (void) nsfw_ps_exit_end_notify(ps_info_msg->host_pid); + return FALSE; } /***************************************************************************** @@ -364,18 +350,17 @@ mem_app_exit_proc (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -int -nsfw_recycle_obj_end_proc (nsfw_mgr_msg * msg) +int nsfw_recycle_obj_end_proc(nsfw_mgr_msg * msg) { - if (NULL == msg) + if (NULL == msg) { - NSFW_LOGERR ("msg nul"); - return FALSE; + NSFW_LOGERR("msg nul"); + return FALSE; } - nsfw_ps_info_msg *ps_info_msg = GET_USER_MSG (nsfw_ps_info_msg, msg); + nsfw_ps_info_msg *ps_info_msg = GET_USER_MSG(nsfw_ps_info_msg, msg); - return nsfw_recycle_pid_obj (ps_info_msg->host_pid); + return nsfw_recycle_pid_obj(ps_info_msg->host_pid); } /***************************************************************************** @@ -388,36 +373,35 @@ nsfw_recycle_obj_end_proc (nsfw_mgr_msg * msg) * Calls : * Called By : *****************************************************************************/ -int -nsfw_recycle_obj_timeout (u32 timer_type, void *data) +int nsfw_recycle_obj_timeout(u32 timer_type, void *data) { - u32 pid = (u64) data; - void *timer_ptr = NULL; - NSFW_LOGINF ("ps_info timerout]pid=%u", pid); + u32 pid = (u64) data; + void *timer_ptr = NULL; + NSFW_LOGINF("ps_info timerout]pid=%u", pid); - nsfw_ps_info *pps_info; - pps_info = nsfw_ps_info_get (pid); - if (NULL != pps_info) + nsfw_ps_info *pps_info; + pps_info = nsfw_ps_info_get(pid); + if (NULL != pps_info) { - nsfw_recycle_pool *rec_pool = g_rec_cfg.mem_rec_obj_pool; - if (NULL != rec_pool) + nsfw_recycle_pool *rec_pool = g_rec_cfg.mem_rec_obj_pool; + if (NULL != rec_pool) { - if (TRUE == g_hbt_switch) + if (TRUE == g_hbt_switch) { - struct timespec time_left = { NSFW_REC_WEND_TVLAUE, 0 }; - timer_ptr = - (void *) nsfw_timer_reg_timer (timer_type, data, - nsfw_recycle_obj_timeout, - time_left); - nsfw_ps_set_uv (pps_info, NSFW_REC_TIMER, timer_ptr); - return TRUE; + struct timespec time_left = { NSFW_REC_WEND_TVLAUE, 0 }; + timer_ptr = + (void *) nsfw_timer_reg_timer(timer_type, data, + nsfw_recycle_obj_timeout, + time_left); + nsfw_ps_set_uv(pps_info, NSFW_REC_TIMER, timer_ptr); + return TRUE; } } - nsfw_ps_set_uv (pps_info, NSFW_REC_TIMER, timer_ptr); + nsfw_ps_set_uv(pps_info, NSFW_REC_TIMER, timer_ptr); } - (void) nsfw_recycle_pid_obj (pid); - return TRUE; + (void) nsfw_recycle_pid_obj(pid); + return TRUE; } /***************************************************************************** @@ -429,96 +413,95 @@ nsfw_recycle_obj_timeout (u32 timer_type, void *data) * Calls : * Called By : *****************************************************************************/ -u8 -mem_rec_zone_init () +u8 mem_rec_zone_init() { - nsfw_mem_mring pringinfo; - pringinfo.enmptype = NSFW_MRING_MPMC; - pringinfo.isocket_id = NSFW_SOCKET_ANY; - pringinfo.stname.entype = NSFW_NSHMEM; - pringinfo.usnum = MEM_RECYCLE_PER_PRO_QUE; - u32 i; - for (i = 0; i < NSFW_REC_PRO_MAX; i++) + nsfw_mem_mring pringinfo; + pringinfo.enmptype = NSFW_MRING_MPMC; + pringinfo.isocket_id = NSFW_SOCKET_ANY; + pringinfo.stname.entype = NSFW_NSHMEM; + pringinfo.usnum = MEM_RECYCLE_PER_PRO_QUE; + u32 i; + for (i = 0; i < NSFW_REC_PRO_MAX; i++) { - if (-1 == - SPRINTF_S (pringinfo.stname.aname, NSFW_MEM_NAME_LENGTH, "%s%d", - MEM_REC_QUEUE_NAME, i)) + if (-1 == + sprintf_s(pringinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s%u", + MEM_REC_QUEUE_NAME, i)) { - NSFW_LOGERR ("SPRINTF_S failed]"); - return FALSE; + NSFW_LOGERR("sprintf_s fail"); + return FALSE; } - g_rec_cfg.mem_rec_pro[i] = nsfw_mem_ring_create (&pringinfo); - if (NULL == g_rec_cfg.mem_rec_pro[i]) + g_rec_cfg.mem_rec_pro[i] = nsfw_mem_ring_create(&pringinfo); + if (NULL == g_rec_cfg.mem_rec_pro[i]) { - NSFW_LOGERR ("alloc rec ring nul!"); - return FALSE; + NSFW_LOGERR("alloc rec ring nul"); + return FALSE; } } - MEM_STAT (NSFW_RECYCLE_MODULE, MEM_REC_QUEUE_NAME, NSFW_NSHMEM, - NSFW_REC_PRO_MAX * nsfw_mem_get_len (g_rec_cfg.mem_rec_pro[0], + MEM_STAT(NSFW_RECYCLE_MODULE, MEM_REC_QUEUE_NAME, NSFW_NSHMEM, + NSFW_REC_PRO_MAX * nsfw_mem_get_len(g_rec_cfg.mem_rec_pro[0], NSFW_MEM_RING)); - nsfw_mem_zone pzoneinfo; - pzoneinfo.isocket_id = NSFW_SOCKET_ANY; - pzoneinfo.stname.entype = NSFW_NSHMEM; - pzoneinfo.length = - MEM_RECYCLE_OBJ_MAX_NUM * sizeof (nsfw_recycle_obj) + - sizeof (nsfw_recycle_pool); - if (-1 == - SPRINTF_S (pzoneinfo.stname.aname, NSFW_MEM_NAME_LENGTH, "%s", - MEM_REC_POOL_NAME)) + nsfw_mem_zone pzoneinfo; + pzoneinfo.isocket_id = NSFW_SOCKET_ANY; + pzoneinfo.stname.entype = NSFW_NSHMEM; + pzoneinfo.lenth = + MEM_RECYCLE_OBJ_MAX_NUM * sizeof(nsfw_recycle_obj) + + sizeof(nsfw_recycle_pool); + if (-1 == + sprintf_s(pzoneinfo.stname.aname, NSFW_MEM_NAME_LENTH, "%s", + MEM_REC_POOL_NAME)) { - NSFW_LOGERR ("SPRINTF_S failed]"); - return FALSE; + NSFW_LOGERR("sprintf_s fail"); + return FALSE; } - g_rec_cfg.mem_rec_obj_pool = nsfw_mem_zone_create (&pzoneinfo); - if (NULL == g_rec_cfg.mem_rec_obj_pool) + g_rec_cfg.mem_rec_obj_pool = nsfw_mem_zone_create(&pzoneinfo); + if (NULL == g_rec_cfg.mem_rec_obj_pool) { - NSFW_LOGERR ("alloc rec pool nul!"); - return FALSE; + NSFW_LOGERR("alloc rec pool nul"); + return FALSE; } - MEM_STAT (NSFW_RECYCLE_MODULE, MEM_REC_POOL_NAME, NSFW_NSHMEM, - pzoneinfo.length); + MEM_STAT(NSFW_RECYCLE_MODULE, MEM_REC_POOL_NAME, NSFW_NSHMEM, + pzoneinfo.lenth); - int retval; - retval = - MEMSET_S (g_rec_cfg.mem_rec_obj_pool, pzoneinfo.length, 0, - pzoneinfo.length); - if (EOK != retval) + int retval; + retval = + memset_s(g_rec_cfg.mem_rec_obj_pool, pzoneinfo.lenth, 0, + pzoneinfo.lenth); + if (EOK != retval) { - NSFW_LOGERR ("mem set init failed!"); - return FALSE; + NSFW_LOGERR("mem set init fail"); + return FALSE; } - i32 j; - nsfw_recycle_pool *rec_pool = - (nsfw_recycle_pool *) g_rec_cfg.mem_rec_obj_pool; - rec_pool->pool_size = MEM_RECYCLE_OBJ_MAX_NUM; + i32 j; + nsfw_recycle_pool *rec_pool = + (nsfw_recycle_pool *) g_rec_cfg.mem_rec_obj_pool; + rec_pool->pool_size = MEM_RECYCLE_OBJ_MAX_NUM; - nsfw_recycle_obj *p_start = rec_pool->obj; - for (i = 0; i < NSFW_REC_PRO_MAX; i++) + nsfw_recycle_obj *p_start = rec_pool->obj; + for (i = 0; i < NSFW_REC_PRO_MAX; i++) { - for (j = 0; j < MEM_RECYCLE_PER_PRO_QUE; j++) + for (j = 0; j < MEM_RECYCLE_PER_PRO_QUE; j++) { - if (FALSE == p_start[j].alloc_flag) + if (FALSE == p_start[j].alloc_flag) { - if (0 == - nsfw_mem_ring_enqueue (g_rec_cfg.mem_rec_pro[i], - &p_start[j])) + if (0 == + nsfw_mem_ring_enqueue(g_rec_cfg.mem_rec_pro[i], + &p_start[j])) { - NSFW_LOGERR ("enqueue failed"); - break; + NSFW_LOGERR("enqueue fail"); + break; } } } - p_start = p_start + MEM_RECYCLE_PER_PRO_QUE; + p_start = p_start + MEM_RECYCLE_PER_PRO_QUE; } - NSFW_LOGINF ("init rec pool and ring suc!"); - return TRUE; + NSFW_LOGINF("init rec pool and ring suc"); + return TRUE; } /***************************************************************************** @@ -532,46 +515,45 @@ mem_rec_zone_init () * Calls : * Called By : *****************************************************************************/ -void * -nsfw_recycle_reg_obj (u8 priority, u16 rec_type, void *data) +void *nsfw_recycle_reg_obj(u8 priority, u16 rec_type, void *data) { - if (NSFW_REC_PRO_MAX <= priority) + if (NSFW_REC_PRO_MAX <= priority) { - NSFW_LOGERR ("pro error]priority=%d,rec_type=%d,data=%p", priority, - rec_type, data); - return NULL; + NSFW_LOGERR("pro error]priority=%d,rec_type=%d,data=%p", priority, + rec_type, data); + return NULL; } - nsfw_recycle_obj *obj = NULL; - if (0 == - nsfw_mem_ring_dequeue (g_rec_cfg.mem_rec_pro[priority], (void *) &obj)) + nsfw_recycle_obj *obj = NULL; + if (0 == + nsfw_mem_ring_dequeue(g_rec_cfg.mem_rec_pro[priority], (void *) &obj)) { - NSFW_LOGERR ("dequeue error]priority=%d,rec_type=%d,data=%p", - priority, rec_type, data); - return NULL; + NSFW_LOGERR("dequeue error]priority=%d,rec_type=%d,data=%p", + priority, rec_type, data); + return NULL; } - if (EOK != MEMSET_S (obj, sizeof (*obj), 0, sizeof (*obj))) + if (EOK != memset_s(obj, sizeof(*obj), 0, sizeof(*obj))) { - if (0 == nsfw_mem_ring_enqueue (g_rec_cfg.mem_rec_pro[priority], obj)) + if (0 == nsfw_mem_ring_enqueue(g_rec_cfg.mem_rec_pro[priority], obj)) { - NSFW_LOGERR ("enqueue error]priority=%d,rec_type=%d,data=%p", - priority, rec_type, data); + NSFW_LOGERR("enqueue error]priority=%d,rec_type=%d,data=%p", + priority, rec_type, data); } - NSFW_LOGERR ("mem set error]priority=%d,rec_type=%d,data=%p", - priority, rec_type, data); - return NULL; + NSFW_LOGERR("mem set error]priority=%d,rec_type=%d,data=%p", + priority, rec_type, data); + return NULL; } - obj->alloc_flag = TRUE; - obj->rec_type = rec_type; - obj->data = data; - obj->host_pid = get_sys_pid (); - obj->alloc_flag = TRUE; - NSFW_LOGINF ("en queue obj]priority=%d,rec_type=%d,data=%p", priority, - rec_type, data); - return obj; + obj->alloc_flag = TRUE; + obj->rec_type = rec_type; + obj->data = data; + obj->host_pid = get_sys_pid(); + obj->alloc_flag = TRUE; + NSFW_LOGINF("en queue obj]priority=%d,rec_type=%d,data=%p", priority, + rec_type, data); + return obj; } /***************************************************************************** @@ -583,77 +565,60 @@ nsfw_recycle_reg_obj (u8 priority, u16 rec_type, void *data) * Calls : * Called By : *****************************************************************************/ -int -nsfw_recycle_rechk_lock () +int nsfw_recycle_rechk_lock() { - return nsfw_ps_rechk_pid_exit (nsfw_recycle_exit_pid_lock, NULL); + return nsfw_ps_rechk_pid_exit(nsfw_recycle_exit_pid_lock, NULL); } -/***************************************************************************** -* Prototype : nsfw_recycle_module_init -* Description : module init -* Input : void* param -* Output : None -* Return Value : static int -* Calls : -* Called By : -*****************************************************************************/ -NSTACK_STATIC int nsfw_recycle_module_init (void *param); -NSTACK_STATIC int -nsfw_recycle_module_init (void *param) +NSTACK_STATIC int nsfw_recycle_module_init(void *param); +NSTACK_STATIC int nsfw_recycle_module_init(void *param) { - u32 proc_type = (u32) ((long long) param); - NSFW_LOGINF ("recycle module init]type=%d", proc_type); - g_rec_cfg.rec_waite_end_tvalue = NSFW_REC_WEND_TVLAUE_DEF; - switch (proc_type) + u32 proc_type = (u32) ((long long) param); + NSFW_LOGINF("recycle module init]type=%u", proc_type); + g_rec_cfg.rec_waite_end_tvalue = NSFW_REC_WEND_TVLAUE_DEF; + switch (proc_type) { - case NSFW_PROC_MAIN: - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_APP_EXIT_REQ, mem_app_exit_proc); - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_RCC_END_REQ, - nsfw_recycle_obj_end_proc); - if (TRUE == mem_rec_zone_init ()) - { - return 0; - } + case NSFW_PROC_MASTER: + return 0; + case NSFW_PROC_MAIN: + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_APP_EXIT_REQ, + mem_app_exit_proc); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_RCC_END_REQ, + nsfw_recycle_obj_end_proc); + if (TRUE == mem_rec_zone_init()) + { + return 0; + } - return 0; - default: - if (proc_type < NSFW_PROC_MAX) - { - break; - } - return -1; + return 0; + default: + if (proc_type < NSFW_PROC_MAX) + { + break; + } + return -1; } - return 0; + return 0; } -/***************************************************************************** -* Prototype : nsfw_recycle_fork_init -* Description : fork init -* Input : None -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -nsfw_recycle_fork_init () +u8 nsfw_recycle_fork_init() { - /* reconnect to master after fork in child proc */ - nsfw_mgr_close_dst_proc (NSFW_PROC_MAIN, 0); - if (0 == nsfw_recycle_module_init ((void *) ((long long) NSFW_PROC_APP))) + /* reconnect to master after fork in child proc */ + nsfw_mgr_close_dst_proc(NSFW_PROC_MAIN, 0); + nsfw_mgr_close_dst_proc(NSFW_PROC_MASTER, 0); + if (0 == nsfw_recycle_module_init((void *) ((long long) NSFW_PROC_APP))) { - return TRUE; + return TRUE; } - return FALSE; + return FALSE; } /* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_RECYCLE_MODULE) -NSFW_MODULE_PRIORITY (10) -NSFW_MODULE_DEPENDS (NSFW_PS_MEM_MODULE) -NSFW_MODULE_INIT (nsfw_recycle_module_init) +NSFW_MODULE_NAME(NSFW_RECYCLE_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_DEPENDS(NSFW_PS_MEM_MODULE) +NSFW_MODULE_INIT(nsfw_recycle_module_init) /* *INDENT-ON* */ #ifdef __cplusplus diff --git a/src/framework/ipc/ps/nsfw_recycle_module.h b/src/framework/ipc/ps/nsfw_recycle_module.h index 694c1d2..ca9ce7e 100644 --- a/src/framework/ipc/ps/nsfw_recycle_module.h +++ b/src/framework/ipc/ps/nsfw_recycle_module.h @@ -18,6 +18,8 @@ #define _NSFW_RECYCLE_MODULE_H #include "nsfw_recycle_api.h" +#include "nsfw_mem_api.h" +#include "types.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -40,40 +42,41 @@ extern "C"{ typedef struct _nsfw_recycle_obj { - u8 alloc_flag; - u8 u8reserve; - u16 rec_type; - u32 host_pid; - void *data; - u64 u64reserve; + u8 alloc_flag; + u8 u8reserve; + u16 rec_type; + u32 host_pid; + void *data; + u64 u64reserve; } nsfw_recycle_obj; #define NSFW_REC_LOCK_REL_MAX_FUN 32 typedef struct _nsfw_rec_fun_info { - nsfw_recycle_fun rec_fun; - void *data; - u8 proc_type; + nsfw_recycle_fun rec_fun; + void *data; + u8 proc_type; } nsfw_rec_fun_info; typedef struct _nsfw_recycle_pool { - u32 pool_size; - nsfw_recycle_obj obj[0]; + u32 pool_size; + + nsfw_recycle_obj obj[0]; } nsfw_recycle_pool; typedef struct _nsfw_recycle_cfg { - u16 rec_waite_end_tvalue; - mring_handle mem_rec_obj_pool; - mzone_handle mem_rec_pro[NSFW_REC_PRO_MAX]; + u16 rec_waite_end_tvalue; + mring_handle mem_rec_obj_pool; + mzone_handle mem_rec_pro[NSFW_REC_PRO_MAX]; } nsfw_recycle_cfg; -extern nsfw_rcc_stat nsfw_recycle_callback_all_obj (u32 pid, - nsfw_recycle_pool * - rec_pool); -extern int nsfw_recycle_obj_timeout (u32 timer_type, void *data); +extern nsfw_rcc_stat nsfw_recycle_callback_all_obj(u32 pid, + nsfw_recycle_pool * + rec_pool); +extern int nsfw_recycle_obj_timeout(u32 timer_type, void *data); #ifdef __cplusplus /* *INDENT-OFF* */ diff --git a/src/framework/ipc/ps/nsfw_soft_param.c b/src/framework/ipc/ps/nsfw_soft_param.c deleted file mode 100644 index 743276f..0000000 --- a/src/framework/ipc/ps/nsfw_soft_param.c +++ /dev/null @@ -1,297 +0,0 @@ -/* -* -* 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 <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" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C"{ -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -typedef struct _nsfw_set_soft_item -{ - void *data; - u32 size; - u64 max; - u64 min; -} nsfw_set_soft_item; - -/* *INDENT-OFF* */ -nsfw_set_soft_fun g_soft_fun[NSFW_MAX_SOFT_PARAM] = { 0 }; -nsfw_set_soft_item g_soft_int_cfg[NSFW_MAX_SOFT_PARAM]; -/* *INDENT-ON* */ - -int -nsfw_isdigitstr (const char *str) -{ - if (NULL == str || '\0' == str[0]) - return 0; - - while (*str) - { - if (*str < '0' || *str > '9') - return 0; - str++; - } - return 1; -} - -u8 -nsfw_soft_param_reg_fun (u32 param_name, nsfw_set_soft_fun fun) -{ - if (NULL == fun || param_name >= NSFW_MAX_SOFT_PARAM) - { - NSFW_LOGERR ("argv err]fun=%p,type=%u", fun, param_name); - return FALSE; - } - - g_soft_fun[param_name] = fun; - NSFW_LOGINF ("reg]fun=%d,type=%u", fun, param_name); - return TRUE; -} - -int -nsfw_soft_set_int (u32 param, char *buf, u32 buf_len) -{ - u64 buf_value = 0; - if (NULL == buf || param >= NSFW_MAX_SOFT_PARAM) - { - NSFW_LOGERR ("argv err]buf=%p,param=%u", buf, param); - return FALSE; - } - - if (!nsfw_isdigitstr (buf)) - { - NSFW_LOGERR ("argv err]buf=%s,param=%u", buf, param); - return FALSE; - } - - char *parsing_end; - buf_value = (u64) strtol (buf, &parsing_end, 10); - nsfw_set_soft_item *int_item = &g_soft_int_cfg[param]; - if (NULL == int_item->data) - { - NSFW_LOGERR ("data err]buf=%s,param=%u,min=%llu,max=%llu", buf, param, - int_item->min, int_item->max); - return FALSE; - } - - if (buf_value < int_item->min || buf_value > int_item->max) - { - NSFW_LOGERR ("argv err]buf=%s,param=%u,min=%llu,max=%llu", buf, param, - int_item->min, int_item->max); - return FALSE; - } - - u32 size = int_item->size; - if (size >= sizeof (u64)) - { - size = sizeof (u64); - } - - if (EOK != MEMCPY_S (int_item->data, size, &buf_value, size)) - { - NSFW_LOGERR ("MEMCPY_S failed"); - return FALSE; - } - - NSFW_LOGINF ("set soft param ok]param=%u,value=%llu,size=%u", param, - buf_value, size); - return TRUE; -} - -/***************************************************************************** -* Prototype : nsfw_soft_param_reg_int -* Description : reg int param set -* Input : u32 param_name -* u32 size -* u32 min -* u32 max -* u64 *data -* Output : None -* Return Value : u8 -* Calls : -* Called By : -*****************************************************************************/ -u8 -nsfw_soft_param_reg_int (u32 param_name, u32 size, u32 min, u32 max, - u64 * data) -{ - if (NULL == data || param_name >= NSFW_MAX_SOFT_PARAM) - { - NSFW_LOGERR ("argv err]data=%p,type=%u", data, param_name); - return FALSE; - } - - g_soft_int_cfg[param_name].data = data; - g_soft_int_cfg[param_name].size = size; - g_soft_int_cfg[param_name].max = max; - g_soft_int_cfg[param_name].min = min; - return nsfw_soft_param_reg_fun (param_name, nsfw_soft_set_int); -} - -void -nsfw_set_soft_para (fw_poc_type proc_type, u32 para_name, void *value, - u32 size) -{ - nsfw_mgr_msg *msg = - (nsfw_mgr_msg *) nsfw_mgr_msg_alloc (MGR_MSG_SOF_PAR_REQ, proc_type); - if (NULL == msg) - { - NSFW_LOGERR - ("nsfw_mgr_msg_alloc failed] msg type=%d, proc type=%d, para_name=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name); - return; - } - - nsfw_soft_param_msg *soft_msg = GET_USER_MSG (nsfw_soft_param_msg, msg); - - soft_msg->param_name = para_name; - soft_msg->rsp_code = 0; - - if (EOK != - MEMCPY_S (soft_msg->param_value, sizeof (soft_msg->param_value), - value, size)) - { - NSFW_LOGERR - ("MEMCPY_S failed] msg type=%d, proc type=%d, para_name=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name); - nsfw_mgr_msg_free (msg); - return; - } - - nsfw_mgr_msg *rsp = nsfw_mgr_null_rspmsg_alloc (); - if (NULL == rsp) - { - NSFW_LOGERR - ("nsfw_mgr_null_rspmsg_alloc failed] msg type=%d, proc type=%d, para_name=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name); - nsfw_mgr_msg_free (msg); - return; - } - - if (!nsfw_mgr_send_req_wait_rsp (msg, rsp)) - { - NSFW_LOGERR - ("can not get response] msg type=%d, proc type=%d, para_name=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name); - nsfw_mgr_msg_free (msg); - nsfw_mgr_msg_free (rsp); - return; - } - - nsfw_soft_param_msg *soft_rsp_msg = GET_USER_MSG (nsfw_soft_param_msg, rsp); - if (soft_rsp_msg->rsp_code != NSFW_EXIT_SUCCESS) - { - NSFW_LOGERR - ("set soft param failed] msg type=%d, proc type=%d, para_name=%u, rsp code=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name, soft_rsp_msg->rsp_code); - nsfw_mgr_msg_free (msg); - nsfw_mgr_msg_free (rsp); - return; - } - - NSFW_LOGINF - ("set soft param success] msg type=%d, proc type=%d, para_name=%u", - MGR_MSG_SOF_PAR_REQ, proc_type, para_name); - - nsfw_mgr_msg_free (msg); - nsfw_mgr_msg_free (rsp); - return; -} - -int -nsfw_softparam_msg_proc (nsfw_mgr_msg * msg) -{ - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL == rsp_msg) - { - NSFW_LOGERR ("alloc rsp failed,drop msg!" MSGINFO, PRTMSG (msg)); - return FALSE; - } - - nsfw_soft_param_msg *soft_msg = GET_USER_MSG (nsfw_soft_param_msg, msg); - nsfw_soft_param_msg *soft_rsp_msg = - GET_USER_MSG (nsfw_soft_param_msg, rsp_msg); - if ((soft_msg->param_name < NSFW_MAX_SOFT_PARAM) - && (NULL != g_soft_fun[soft_msg->param_name])) - { - soft_msg->param_value[sizeof (soft_msg->param_value) - 1] = 0; - (void) g_soft_fun[soft_msg->param_name] (soft_msg->param_name, - (char *) - soft_msg->param_value, - sizeof - (soft_msg->param_value)); - soft_rsp_msg->rsp_code = NSFW_EXIT_SUCCESS; - } - else - { - NSFW_LOGERR ("set soft failed!]soft=%u", soft_msg->param_name); - soft_rsp_msg->rsp_code = NSFW_EXIT_FAILED; - } - - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); - return TRUE; -} - -int nsfw_softparam_module_init (void *param); -int -nsfw_softparam_module_init (void *param) -{ - u8 proc_type = (u8) ((long long) param); - NSFW_LOGINF ("softparam module init]type=%u", proc_type); - switch (proc_type) - { - case NSFW_PROC_MAIN: - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_SOF_PAR_REQ, - nsfw_softparam_msg_proc); - return 0; - default: - if (proc_type < NSFW_PROC_MAX) - { - break; - } - return -1; - } - - return 0; -} - -/* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_SOFT_PARAM_MODULE) -NSFW_MODULE_PRIORITY (99) -NSFW_MODULE_INIT (nsfw_softparam_module_init) -/* *INDENT-ON* */ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ diff --git a/src/framework/lib_common_mem/common_api.c b/src/framework/lib_common_mem/common_api.c deleted file mode 100644 index cfb869d..0000000 --- a/src/framework/lib_common_mem/common_api.c +++ /dev/null @@ -1,325 +0,0 @@ -/* -* -* 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 "common_mem_api.h" -#include "common_mem_pal.h" -#include "nstack_log.h" -#include "nstack_securec.h" -#include "common_func.h" - -void -sys_sem_init_v2 (sys_sem_t_v2 sem) -{ - sem->locked = 1; -} - -/** Returns the current time in milliseconds, - * may be the same as sys_jiffies or at least based on it. */ -u32_t -sys_now (void) -{ - struct timespec now; - - if (unlikely (0 != clock_gettime (CLOCK_MONOTONIC, &now))) - { - NSCOMM_LOGERR ("Failed to get time, errno = %d", errno); - } - - return 1000 * now.tv_sec + now.tv_nsec / 1000000; -} - -long -sys_jiffies (void) -{ - return sys_now (); -} - -err_t -sys_sem_new_v2 (sys_sem_t_v2 * sem, u8_t isUnLockd) -{ - int retVal; - if (!sem) - { - return -1; - } - *sem = malloc (sizeof (common_mem_spinlock_t)); - - if (NULL == *sem) - { - return -1; - } - else - { - retVal = - MEMSET_S (*sem, sizeof (common_mem_spinlock_t), 0, - sizeof (common_mem_spinlock_t)); - if (EOK != retVal) - { - NSCOMM_LOGERR ("MEMSET_S failed]ret=%d", retVal); - free (*sem); - *sem = NULL; - return -1; - } - common_mem_spinlock_init (*sem); - } - - if (!isUnLockd) - { - common_mem_spinlock_lock (*sem); - } - - return 0; -} - -void -sys_sem_free_v2 (sys_sem_t_v2 * sem) -{ - if ((sem != NULL) && (*sem != NULL)) - { - free (*sem); - *sem = NULL; - } - else - { - } -} - -void -sys_sem_signal_v2 (sys_sem_t_v2 * sem) -{ - common_mem_spinlock_unlock (*sem); -} - -void -sys_sem_signal_s_v2 (sys_sem_t_v2 sem) -{ - common_mem_spinlock_unlock (sem); -} - -u32_t -sys_arch_sem_trywait_v2 (sys_sem_t_v2 * sem) -{ - return (u32_t) common_mem_spinlock_trylock (*sem); -} - -u32_t -sys_arch_sem_wait_v2 (sys_sem_t_v2 * pstsem) -{ - common_mem_spinlock_lock (*pstsem); - return 0; -} - -u32_t -sys_arch_sem_wait_s_v2 (sys_sem_t_v2 sem) -{ - common_mem_spinlock_lock (sem); - return 0; -} - -volatile pid_t g_sys_host_pid = SYS_HOST_INITIAL_PID; - -/***************************************************************************** -* Prototype : get_exec_name_by_pid -* Description : get exec name by pid -* Input : pid_t pid -* char *task_name -* Output : None -* Return Value : void -* Calls : -* Called By : -*****************************************************************************/ -void -get_exec_name_by_pid (pid_t pid, char *task_name, int task_name_len) -{ - int retVal; - char path[READ_FILE_BUFLEN] = { 0 }; - char buf[READ_FILE_BUFLEN] = { 0 }; - - retVal = SPRINTF_S (path, sizeof (path), "/proc/%d/status", pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return; - } - - FILE *fp = fopen (path, "r"); - if (NULL != fp) - { - if (fgets (buf, READ_FILE_BUFLEN - 1, fp) == NULL) - { - fclose (fp); - return; - } - fclose (fp); - -#ifdef SECUREC_LIB - retVal = SSCANF_S (buf, "%*s %s", task_name, task_name_len); -#else - retVal = SSCANF_S (buf, "%*s %s", task_name); -#endif - - if (1 != retVal) - { - NSSOC_LOGERR ("SSCANF_S failed]ret=%d", retVal); - return; - } - } -} - -pid_t -get_hostpid_from_file_one_time (u32_t pid) -{ - int retVal; - char path[READ_FILE_BUFLEN] = { 0 }; - char buf[READ_FILE_BUFLEN] = { 0 }; - char fmt[READ_FILE_BUFLEN] = { 0 }; - char out[READ_FILE_BUFLEN] = { 0 }; - char task_name[BUF_SIZE_FILEPATH] = { 0 }; - pid_t hostpid = SYS_HOST_INITIAL_PID; - get_exec_name_by_pid (pid, task_name, BUF_SIZE_FILEPATH); - - retVal = SPRINTF_S (fmt, sizeof (fmt), "%s%s", task_name, " (%s"); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return hostpid; - } - retVal = SPRINTF_S (path, sizeof (path), "/proc/%d/sched", pid); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return hostpid; - } - FILE *fp = fopen (path, "r"); - if (NULL != fp) - { - if (fgets (buf, READ_FILE_BUFLEN - 1, fp) == NULL) - { - fclose (fp); - return hostpid; - } - fclose (fp); - /* Compiler needs "fmt" to be like "%s%s" to - understand. But we have "fmt" already prepared and used here. It can - be suppressed, not an issue - */ -#pragma GCC diagnostic ignored "-Wformat-nonliteral" - retVal = SSCANF_S (buf, fmt, out, READ_FILE_BUFLEN); - if (-1 == retVal) - { - NSPOL_LOGERR ("SSCANF_S failed]ret=%d", retVal); - return hostpid; - } - } - - hostpid = (pid_t) strtol (out, NULL, 0); - if (hostpid == 0) - { - hostpid = 1; - } - - return hostpid; -} - -#define MAX_GET_PID_TIME 10 -pid_t -get_hostpid_from_file (u32_t pid) -{ - pid_t ret_pid = SYS_HOST_INITIAL_PID; - int i = 0; - ret_pid = get_hostpid_from_file_one_time (pid); - while (0 == ret_pid || ret_pid == SYS_HOST_INITIAL_PID) - { - i++; - if (i > MAX_GET_PID_TIME) - { - NSFW_LOGERR ("get pid failed]pid=%u,hostpid=%d", pid, ret_pid); - break; - } - sys_sleep_ns (0, 5000000); - ret_pid = get_hostpid_from_file_one_time (pid); - } - - return ret_pid; -} - -/***************************************************************************** -* Prototype : get_hostpid_from_file -* Description : get host pid by sub namespace pid in docker -* Input : uint32_t pid -* Output : None -* Return Value : uint32_t -* Calls : -* Called By : -*****************************************************************************/ -pid_t -sys_get_hostpid_from_file (pid_t pid) -{ - g_sys_host_pid = get_hostpid_from_file (pid); - NSCOMM_LOGDBG ("ok]cur pid=%d, input pid=%d", g_sys_host_pid, pid); - return g_sys_host_pid; -} - -pid_t -update_sys_pid () -{ - g_sys_host_pid = SYS_HOST_INITIAL_PID; - return get_sys_pid (); -} - -/***************************************************************************** -* Prototype : get_pid_namespace -* Description : Get namespace of pid -* Input : uint32_t pid -* Output : None -* Return Value : uint64_t -* Calls : -* Called By : -*****************************************************************************/ -uint64_t -get_pid_namespace (pid_t pid) -{ - char buf[BUF_SIZE_FILEPATH] = { 0 }; - char path[BUF_SIZE_FILEPATH] = { 0 }; - const char *pstart; - int ret = 0; - if (!pid) - { - NSSOC_LOGERR ("Pid is zero!"); - return 0; - } - - ret = - SNPRINTF_S (path, sizeof (path), sizeof (path) - 1, "/proc/%d/ns/pid", - pid); - if (-1 == ret) - { - NSSOC_LOGERR ("SNPRINTF_S failed]ret=%d", ret); - return 0; - } - - ret = readlink (path, buf, sizeof (buf) - 1); - if (ret <= (int) sizeof (STR_PID)) - { - NSSOC_LOGERR ("readlink pid ns file error]ret=%d", ret); - return 0; - } - - buf[ret - 1] = 0; - pstart = &(buf[sizeof (STR_PID)]); - return strtoull (pstart, NULL, 10); -} diff --git a/src/framework/lib_common_mem/common_buf.c b/src/framework/lib_common_mem/common_buf.c deleted file mode 100644 index d31ca83..0000000 --- a/src/framework/lib_common_mem/common_buf.c +++ /dev/null @@ -1,299 +0,0 @@ -/* -* -* 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 <stdio.h> -#include <stdlib.h> -#include <stdint.h> -#include <stdarg.h> -#include <inttypes.h> -#include <errno.h> -#include <ctype.h> -#include <sys/queue.h> - -#include "common_mem_base_type.h" - -#include "common_mem_common.h" - -#include "common_mem_memzone.h" - -#include "common_mem_pal.h" - -#include "common_mem_mempool.h" -#include "common_mem_buf.h" - -#include "nstack_log.h" -#include "nstack_securec.h" - -#include "common_func.h" -#include "common_pal_bitwide_adjust.h" - -#define LOG_ERR 0 -#define LOG_WARN 1 -#define LOG_INFO 2 -#define LOG_DEBUG 3 -#define LOG_MAX 4 - -#define COMMON_LOG_PRINT(level, fmt, args...) \ - if (level <= log_level) NSCOMM_LOGERR("===>[COMMON]"fmt, ##args); \ - -#define COMMON_PANIC(fmt) \ - NSCOMM_LOGERR("==>[COMMON_PANIC]"fmt); \ - common_dump_stack(); \ - -#define PARA1_SET(argv, tempargv, Index, para1) do {\ - retVal = STRCPY_S(tempargv[Index], PATA_STRLENT, para1);\ - if (retVal != EOK)\ - {\ - NSCOMM_LOGERR("STRCPY_S failed]ret=%d", retVal);\ - return DMM_MBUF_RET_ERR;\ - }\ - argv[Index] = tempargv[Index]; \ - Index ++; } while (0) - -#define PARA2_SET(argv, tempargv, Index, para1, para2) do {\ - retVal = STRCPY_S(tempargv[Index], PATA_STRLENT, para1); \ - if (retVal != EOK)\ - {\ - NSCOMM_LOGERR("STRCPY_S failed]ret=%d", retVal);\ - return DMM_MBUF_RET_ERR;\ - }\ - argv[Index] = tempargv[Index]; \ - Index++; \ - retVal = STRCPY_S(tempargv[Index], PATA_STRLENT, para2); \ - if (retVal != EOK)\ - {\ - NSCOMM_LOGERR("STRCPY_S failed]ret=%d", retVal);\ - return DMM_MBUF_RET_ERR;\ - }\ - argv[Index] = tempargv[Index]; \ - Index ++; } while (0) - -#define PATA_STRLENT 64 -#define PATA_NUM_MAX 12 - -int log_level = LOG_INFO; - -int -nscomm_pal_module_init (nsfw_mem_para * para, - common_mem_pal_module_info * pinfo, u8 app_mode) -{ - char tempargv[PATA_NUM_MAX][PATA_STRLENT]; - char *argv[PATA_NUM_MAX]; - char tempbuf[PATA_STRLENT]; - unsigned int Index = 0; - int ioffset = 0; - int agindex = 0; - int intmask = 0; - int retVal; - char name[10] = { '\0' }; - - if (para == NULL) - { - NSCOMM_LOGERR ("para is null"); - return DMM_MBUF_RET_ERR; - } - - retVal = MEMSET_S (tempargv, sizeof (tempargv), '\0', sizeof (tempargv)); - if (EOK != retVal) - { - NSCOMM_LOGERR ("MEMSET_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - retVal = MEMSET_S (argv, sizeof (argv), 0, sizeof (argv)); - if (EOK != retVal) - { - NSCOMM_LOGERR ("MEMSET_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - if (NSFW_PROC_MAIN == para->enflag) - { - if (para->iargsnum != 0) - { - if (common_mem_pal_init (para->iargsnum, para->pargs) < 0) - { - COMMON_LOG_PRINT (LOG_ERR, "Cannot init pal\r\n"); - return DMM_MBUF_RET_ERR; - } - else - { - return DMM_MBUF_RET_OK; - } - } - - PARA1_SET (argv, tempargv, agindex, "nStackMain"); - PARA2_SET (argv, tempargv, agindex, "-c", "0x1"); - PARA2_SET (argv, tempargv, agindex, "-n", "4"); - PARA1_SET (argv, tempargv, agindex, "--huge-dir=/mnt/nstackhuge"); - PARA1_SET (argv, tempargv, agindex, "--proc-type=primary"); - - if (app_mode == 1) - { - sprintf (name, "dmm_app_%ld", (long) getpid ()); - PARA2_SET (argv, tempargv, agindex, "--file-prefix", name); - PARA1_SET (argv, tempargv, agindex, "--no-pci"); - - // TODO: the size of the memory should not be fixed - PARA2_SET (argv, tempargv, agindex, "-m", "32"); - } - else - { - // TODO: replay the name 'nStackMain' - /* snprintf(name, 10, "dmm_main_%ld", (long) getpid()); */ - PARA2_SET (argv, tempargv, agindex, "--file-prefix", "nStackMain"); - PARA2_SET (argv, tempargv, agindex, "-m", "2048"); - } - - } - else - { - PARA1_SET (argv, tempargv, agindex, "nStackMain"); - PARA2_SET (argv, tempargv, agindex, "--file-prefix", "nStackMain"); - - retVal = SPRINTF_S (tempbuf, PATA_STRLENT, "0x"); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", ioffset); - return DMM_MBUF_RET_ERR; - } - ioffset = retVal; - for (Index = 0; Index < LCORE_MASK_MAX; Index++) - { - if (ioffset >= PATA_STRLENT) - { - NSCOMM_LOGERR ("SPRINTF_S tempbuf overflow]ioffset=%d", - ioffset); - return DMM_MBUF_RET_ERR; - } - retVal = - SPRINTF_S (&(tempbuf[ioffset]), PATA_STRLENT - ioffset, "%8u", - pinfo->ilcoremask[Index]); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", ioffset); - return DMM_MBUF_RET_ERR; - } - ioffset = ioffset + retVal; - intmask |= pinfo->ilcoremask[Index]; - } - if (0 == intmask) - { - PARA2_SET (argv, tempargv, agindex, "-c", "0x1"); - } - else - { - PARA2_SET (argv, tempargv, agindex, "-c", tempbuf); - } - if (pinfo->ishare_mem_size > 0) - { - retVal = MEMSET_S (tempbuf, PATA_STRLENT, 0, PATA_NUM_MAX); - if (EOK != retVal) - { - NSCOMM_LOGERR ("MEMSET_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - retVal = - SPRINTF_S (tempbuf, PATA_STRLENT, "%d", pinfo->ishare_mem_size); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - PARA2_SET (argv, tempargv, agindex, "-m", tempbuf); - } - - retVal = MEMSET_S (tempbuf, PATA_STRLENT, 0, PATA_NUM_MAX); - if (EOK != retVal) - { - NSCOMM_LOGERR ("MEMSET_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - - switch (pinfo->ucproctype) - { - case DMM_PROC_T_PRIMARY: - retVal = SPRINTF_S (tempbuf, PATA_STRLENT, "--proc-type=primary"); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - break; - case DMM_PROC_T_SECONDARY: - retVal = SPRINTF_S (tempbuf, PATA_STRLENT, "--proc-type=secondary"); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - break; - case DMM_PROC_T_AUTO: - default: - retVal = SPRINTF_S (tempbuf, PATA_STRLENT, "--proc-type=auto"); - if (-1 == retVal) - { - NSCOMM_LOGERR ("SPRINTF_S failed]ret=%d", retVal); - return DMM_MBUF_RET_ERR; - } - break; - } - PARA1_SET (argv, tempargv, agindex, tempbuf); - - if (DMM_HUGTBL_DISABLE == pinfo->uchugeflag) - { - PARA1_SET (argv, tempargv, agindex, "--no-huge"); - } - } - if (common_mem_pal_init (agindex, argv) < 0) - { - COMMON_LOG_PRINT (LOG_ERR, "Cannot init pal\r\n"); - return DMM_MBUF_RET_ERR; - } - return DMM_MBUF_RET_OK; -} - -void * -nscomm_memzone_data_reserve_name (const char *name, size_t len, int socket_id) -{ - const struct common_mem_memzone *mz = NULL; - /* - rte_memzone_reserve must Call first, cause rte_memzone_reserve has a globe lock. - while proc race happen, who(calls A) got lock first will create memzone success. - others create same memzone proc will got lock after A, and rte_memzone_reserve return NULL; - so while rte_memzone_reserve return NULL we need do rte_memzone_lookup; - */ - mz = common_mem_memzone_reserve (name, len, socket_id, 0); - if (mz == NULL) - { - mz = common_mem_memzone_lookup (name); - } - - return mz ? (void *) ADDR_SHTOL (mz->addr_64) : NULL; -} - -void * -nscomm_memzone_data_lookup_name (const char *name) -{ - void *addr = NULL; - const struct common_mem_memzone *mz = NULL; - mz = common_mem_memzone_lookup (name); - if (mz == NULL) - { - return NULL; - } - addr = (void *) ADDR_SHTOL (mz->addr_64); - return addr; -} diff --git a/src/framework/lib_common_mem/common_func.c b/src/framework/lib_common_mem/common_func.c deleted file mode 100644 index 5220374..0000000 --- a/src/framework/lib_common_mem/common_func.c +++ /dev/null @@ -1,205 +0,0 @@ -/* -* -* 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 "common_mem_pal_memconfig.h" -#include "common_mem_mbuf.h" -#include "common_mem_common.h" -#include "nstack_log.h" -#include "common_pal_bitwide_adjust.h" - -#include "common_func.h" - -#include "nstack_securec.h" - -#define COMMON_PROCESS_MAPS "/proc/self/maps" - -int g_PrimSameFlg = 1; - -NSTACK_STATIC void **g_PrimAddr2LocalMap = NULL; -NSTACK_STATIC void *g_LocalBaseAddr = NULL; -NSTACK_STATIC void *g_LocalMaxAddr = NULL; -NSTACK_STATIC void *g_LocalCfgAddrBase = NULL; - -NSTACK_STATIC uint64_t *g_LocalAddr2PrimMap = NULL; -NSTACK_STATIC uint64_t g_PrimBaseAddr = 0; -NSTACK_STATIC uint64_t g_PrimMaxAddr = 0; -NSTACK_STATIC uint64_t g_PrimCfgAddrBase = 0; - -NSTACK_STATIC uint64_t g_LBitMask = 0; -NSTACK_STATIC int g_LBitMaskLen = 0; - -uint64_t -pal_laddr_to_shddr (void *LAddr) -{ - size_t l2pIdx; - - if (g_PrimSameFlg || LAddr == NULL) - { - return (uint64_t) LAddr; - } - - /*calculate the IDX */ - l2pIdx = (ALIGN_PTR (LAddr) - ALIGN_PTR (g_LocalBaseAddr)) >> g_LBitMaskLen; - - /*check the Hugepage Addr Rang */ - if (LAddr <= g_LocalMaxAddr && LAddr >= g_LocalBaseAddr - && g_LocalAddr2PrimMap[l2pIdx]) - { - return g_LocalAddr2PrimMap[l2pIdx] + (ALIGN_PTR (LAddr) & g_LBitMask); - } - - /*check the Cfg Mapping Addr Rang */ - if (LAddr >= g_LocalCfgAddrBase - && LAddr <= - (void *) ((char *) g_LocalCfgAddrBase + - sizeof (struct common_mem_mem_config))) - { - return g_PrimCfgAddrBase + ((char *) LAddr - - (char *) g_LocalCfgAddrBase); - } - - NSCOMM_LOGWAR - ("WARNING!!! Input invalid LAddr]LAddr=%p, g_LocalBaseAddr=%p, g_LocalMaxAddr=%p, g_LocalCfgAddrBase=%p, g_LocalCfgAddrMax=%p.", - LAddr, g_LocalBaseAddr, g_LocalMaxAddr, g_LocalCfgAddrBase, - (char *) g_LocalCfgAddrBase + sizeof (struct common_mem_mem_config)); - - return (uint64_t) LAddr; -} - -void * -pal_shddr_to_laddr (uint64_t PAddr) -{ - size_t p2lIdx; - - if (g_PrimSameFlg || PAddr == ALIGN_PTR (NULL)) - { - return (void *) PAddr; - } - - p2lIdx = (PAddr - g_PrimBaseAddr) >> g_LBitMaskLen; - /*check the Hugepage Addr Rang */ - if (PAddr <= g_PrimMaxAddr && PAddr >= g_PrimBaseAddr - && g_PrimAddr2LocalMap[p2lIdx]) - { - return (void *) ((uint64_t) g_PrimAddr2LocalMap[p2lIdx] + - (PAddr & g_LBitMask)); - } - - /*check the Cfg Mapping Addr Rang */ - if (PAddr >= g_PrimCfgAddrBase - && PAddr <= g_PrimCfgAddrBase + sizeof (struct common_mem_mem_config)) - { - return (void *) ((uint64_t) g_LocalCfgAddrBase + PAddr - - g_PrimCfgAddrBase); - } - - NSCOMM_LOGWAR - ("WARNING!!! Input invalid PAddr]PAddr=%lx, g_PrimBaseAddr=%lx, g_PrimMaxAddr=%lx, g_PrimCfgAddrBase=%lx, g_PrimCfgAddrMax=%lx.", - PAddr, g_PrimBaseAddr, g_PrimMaxAddr, g_PrimCfgAddrBase, - g_PrimCfgAddrBase + sizeof (struct common_mem_mem_config)); - - return (void *) PAddr; -} - -/*lint +e539 */ - -int -dmm_pal_addr_align () -{ - return g_PrimSameFlg; -} - -int32_t -dmm_pktmbuf_pool_iterator (struct common_mem_mempool * mp, uint32_t start, - uint32_t end, dmm_mbuf_item_fun fun, void *argv) -{ - if (NULL == mp || fun == NULL) - { - return 0; - } - - if (start >= mp->size || end <= start) - { - return 0; - } - - int32_t elm_size = mp->elt_size + mp->header_size + mp->trailer_size; - struct common_mem_mbuf *elm_mbuf = (struct common_mem_mbuf *) (STAILQ_FIRST (&mp->mem_list)->addr + start * elm_size + mp->header_size); /*lint !e647 */ - - uint32_t i; - uint32_t mbuf_end = COMMON_MEM_MIN (end, mp->size) - start; - for (i = 0; i < mbuf_end; i++) - { - (void) fun (elm_mbuf, argv); - elm_mbuf = (struct common_mem_mbuf *) ((char *) elm_mbuf + elm_size); - } - - return mbuf_end; -} - -void -dmm_addr_print (void) -{ - const struct common_mem_mem_config *mcfg = - common_mem_pal_get_configuration ()->mem_config; - int s; - FILE *fd; - char *ptembuf = NULL; - if (!mcfg) - { - NSCOMM_LOGERR ("mcfg is null"); - return; - } - /*printf base address */ - NSCOMM_LOGINF ("********master baseaddr begin***************"); - for (s = 0; s < COMMON_MEM_MAX_MEMSEG; ++s) - { - if ((mcfg->memseg[s].len > 0) && (mcfg->memseg[s].addr != 0)) - { - NSCOMM_LOGINF ("addr:%p, len:%u", mcfg->memseg[s].addr, - mcfg->memseg[s].len); - } - } - NSCOMM_LOGINF ("********master baseaddr end***************"); - - fd = fopen (COMMON_PROCESS_MAPS, "r"); - if (!fd) - { - NSCOMM_LOGERR ("/proc/self/maps open fail, erro:%d", errno); - return; - } - - ptembuf = (char *) malloc (BUFSIZ); - if (!ptembuf) - { - NSCOMM_LOGERR ("malloc buff failed]buff_len=%d", BUFSIZ); - fclose (fd); - return; - } - if (EOK != MEMSET_S (ptembuf, BUFSIZ, 0, BUFSIZ)) - { - NSCOMM_LOGERR ("MEMSET_S failed] buff=%p", ptembuf); - } - NSCOMM_LOGINF ("********self process addr space begin***************"); - while (fgets (ptembuf, BUFSIZ, fd) != NULL) - { - NSCOMM_LOGERR ("%s", ptembuf); - } - NSCOMM_LOGINF ("********self process addr space end*****************"); - fclose (fd); - free (ptembuf); - return; -} diff --git a/src/framework/log/nsfw_set_log.c b/src/framework/log/nsfw_set_log.c deleted file mode 100644 index 31241b5..0000000 --- a/src/framework/log/nsfw_set_log.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -* -* 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" - -#ifdef __cplusplus -/* *INDENT-OFF* */ -extern "C"{ -/* *INDENT-ON* */ -#endif /* __cplusplus */ - -typedef struct _nsfw_log_cfg -{ - u8 proc_type; - char master_log_path[NSFW_LOG_VALUE_LEN]; - char runing_log_path[NSFW_LOG_VALUE_LEN]; - char opr_log_path[NSFW_LOG_VALUE_LEN]; -} nsfw_log_cfg; - -nsfw_log_cfg g_log_cfg; - -const char nsfw_mas_log[NSFW_LOG_VALUE_LEN] = "maspath"; -const char nsfw_flush_name[NSFW_LOG_VALUE_LEN] = "flush"; - -enum _set_log_type -{ - SET_LOG_LEVEL = 0, - SET_LOG_FLUSH, - SET_LOG_MASTER, - SET_LOG_MAIN, - - SET_LOG_INVALID -}; - -/***************************************************************************** -* Prototype : nsfw_set_log_path -* Description : set log path -* Input : const char *param -* const char *value -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -int -nsfw_set_log_path (const char *param, const char *value) -{ - if (NULL == param || NULL == value) - { - NSFW_LOGERR ("log param error!]param=%p,value=%p", param, value); - return FALSE; - } - - if (cmp_log_path (value)) - { - if (check_log_dir_valid (value) < 0) - { - NSFW_LOGERR ("path is invalid]value=%s", value); - return FALSE; - } - if (EOK != - STRCPY_S (g_log_cfg.master_log_path, NSFW_LOG_VALUE_LEN, value)) - { - NSFW_LOGERR ("strcpy error!"); - return FALSE; - } - - NSFW_LOGINF ("renew log path]%s", g_log_cfg.master_log_path); - nstack_modify_log_dir (g_log_cfg.master_log_path); - NSFW_LOGINF ("set log success]newpath=%s!", g_log_cfg.master_log_path); - return TRUE; - } - return FALSE; -} - -/***************************************************************************** -* Prototype : nsfw_flush_log_info -* Description : flush the log info -* Input : const char *param -* u8 proc_type -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -int -nsfw_flush_log_info (const char *param, u8 proc_type) -{ - if (NULL == param) - { - NSFW_LOGERR ("log param error!]param=%p", param); - return FALSE; - } - glogFlushLogFiles (GLOG_LEVEL_DEBUG); - NSFW_LOGINF ("flush log success]proc_type=%u", proc_type); - return TRUE; -} - -/***************************************************************************** -* Prototype : nsfw_set_log_msg_proc -* Description : set log message process -* Input : nsfw_mgr_msg* msg -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -int -nsfw_set_log_msg_proc (nsfw_mgr_msg * msg) -{ - int ret = -1; - int status = -1; - if (NULL == msg) - { - NSFW_LOGERR ("msg nul"); - return FALSE; - } - - nsfw_set_log_msg *set_log_msg = GET_USER_MSG (nsfw_set_log_msg, msg); - - if (0 == strcmp (set_log_msg->module, nsfw_mas_log)) - { - status = SET_LOG_MASTER; - } - else if (0 == strcmp (set_log_msg->module, nsfw_flush_name)) - { - status = SET_LOG_FLUSH; - } - else if (nsfw_isdigitstr (set_log_msg->module)) - { - status = SET_LOG_LEVEL; - } - - switch (status) - { - case SET_LOG_LEVEL: - ret = setlog_level_value (set_log_msg->module, set_log_msg->log_level); - break; - case SET_LOG_FLUSH: - ret = nsfw_flush_log_info (set_log_msg->module, msg->dst_proc_type); - break; - case SET_LOG_MASTER: - ret = nsfw_set_log_path (set_log_msg->module, set_log_msg->log_level); - break; - default: - NSFW_LOGERR ("default error]status=%d,set_log_msg->module=%s", status, - set_log_msg->module); - return FALSE; - } - - nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc (msg); - if (NULL == rsp_msg) - { - NSFW_LOGERR ("alloc rsp failed,drop msg!" MSGINFO, PRTMSG (msg)); - return FALSE; - } - nsfw_set_log_msg *log_rsp_msg = GET_USER_MSG (nsfw_set_log_msg, rsp_msg); - log_rsp_msg->rsp_code = ret; - (void) nsfw_mgr_send_msg (rsp_msg); - nsfw_mgr_msg_free (rsp_msg); - return TRUE; -} - -/***************************************************************************** -* Prototype : nsfw_cfg_module_init -* Description : module init -* Input : void* param -* Output : None -* Return Value : static int -* Calls : -* Called By : -*****************************************************************************/ -static int nsfw_cfg_module_init (void *param); -static int -nsfw_cfg_module_init (void *param) -{ - u8 proc_type = (u8) ((long long) param); - NSFW_LOGINF ("log cfg module init]type=%u", proc_type); - switch (proc_type) - { - case NSFW_PROC_MAIN: - (void) nsfw_mgr_reg_msg_fun (MGR_MSG_SET_LOG_REQ, - nsfw_set_log_msg_proc); - g_log_cfg.proc_type = proc_type; - return 0; - default: - if (proc_type < NSFW_PROC_MAX) - { - break; - } - return -1; - } - - return 0; -} - -/* *INDENT-OFF* */ -NSFW_MODULE_NAME (NSFW_LOG_CFG_MODULE) -NSFW_MODULE_PRIORITY (99) -NSFW_MODULE_INIT (nsfw_cfg_module_init) -/* *INDENT-ON* */ - -#ifdef __cplusplus -/* *INDENT-OFF* */ -} -/* *INDENT-ON* */ -#endif /* __cplusplus */ diff --git a/src/framework/log/nstack_log.c b/src/framework/log/nstack_log.c index 483a10a..d760648 100644 --- a/src/framework/log/nstack_log.c +++ b/src/framework/log/nstack_log.c @@ -17,8 +17,8 @@ /*==============================================* * include header files * *----------------------------------------------*/ - -#include "nstack_log.h" +#include "nstack_log_base.h" +#include "nstack_log_async.h" #include <sys/stat.h> #include <dirent.h> #include <time.h> @@ -26,6 +26,7 @@ #include <execinfo.h> #include <fcntl.h> #include "nstack_securec.h" +#include "nsfw_maintain_api.h" #include <pthread.h> /*==============================================* @@ -33,177 +34,258 @@ *----------------------------------------------*/ #define FILE_NAME_LEN 256 -#define MAX_PRE_INIT_LOG_COUNT 256 -#define MAX_LOCK_RETRY_COUNT 50000 /* changed MAX_LOCK_RETRY_COUNT to 50000 to avoid function being blocked for too long */ -/* *INDENT-OFF* */ + int g_l4_dump_enable = 0; -static int pre_init_log_count = 0; -static struct pre_init_info pre_init_log[MAX_PRE_INIT_LOG_COUNT] = {{0, ""}}; -/* *INDENT-ON* */ + __thread unsigned int nstack_log_nonreentry = 0; -int ctrl_log_switch = 0; +//ctrl log switch just for ctrl now +bool ctrl_log_switch = FALSE; /*==============================================* * project-wide global variables * *----------------------------------------------*/ struct nstack_logs g_nstack_logs[MAX_LOG_MODULE] = { {0, 0, 0, 0}, {0xFFFF, 0, 0, 0} }; /* Clear compile warning */ + struct log_init_para g_log_init_para = - { 50, 10, NSTACK_LOG_NAME, 10, 10, NSTACK_LOG_NAME }; + { 50, 10, NSTACK_LOG_NAME, 10, 10, NSTACK_LOG_NAME }; + static int g_my_pro_type = LOG_PRO_INVALID; #define DEFAULT_LOG_CTR_TIME 5 static struct log_ctrl_info g_log_ctrl_info[LOG_CTRL_ID_MAX]; +//better put in the struct for file_type +bool log_asyn_inited = FALSE; + /*==============================================* * routines' or functions' implementations * *----------------------------------------------*/ -/* change the print level, not only has err, Begin.*/ -void -save_pre_init_log (uint32_t level, char *fmt, ...) +void write_pre_init_log(bool type) { - va_list ap; - int ret = 0; - /* add pre_init_log_count rang check */ - if (level > NSLOG_DBG || pre_init_log_count >= MAX_PRE_INIT_LOG_COUNT - || pre_init_log_count < 0) + int i = 0; + int ret = -1; + int count = get_pre_init_log_count(); + size_t size = MAX_PRE_INIT_LOG_COUNT * sizeof(struct pre_init_info); + unsigned int level = 0; + struct pre_init_info *pre_buf = (struct pre_init_info *) malloc(size); /*malloc() can be used */ + if (!pre_buf) { - return; + NSPOL_LOGERR("malloc fail]count=%d", count); + return; } - pre_init_log[pre_init_log_count].log_buffer[PRE_INIT_LOG_LENGTH - 1] = '\0'; - (void) va_start (ap, fmt); - ret = - VSNPRINTF_S (pre_init_log[pre_init_log_count].log_buffer, - PRE_INIT_LOG_LENGTH, PRE_INIT_LOG_LENGTH - 1, fmt, ap); - if (-1 == ret) + + ret = memset_s(pre_buf, size, 0, size); + if (EOK != ret) { - va_end (ap); - return; + NSPOL_LOGERR("memset_s fail]ret=%d,count=%d", ret, count); + free(pre_buf); /*free() can be used */ + return; } - va_end (ap); - pre_init_log[pre_init_log_count].level = level; - pre_init_log_count++; -} -void -write_pre_init_log () -{ - int i = 0; - for (; i < pre_init_log_count; i++) + ret = get_pre_init_log_buffer(pre_buf, MAX_PRE_INIT_LOG_COUNT); + if (ret < 0) { - if (NSLOG_ERR == pre_init_log[i].level) - { - NSPOL_LOGERR ("pre init log: %s", pre_init_log[i].log_buffer); - } - else if (NSLOG_WAR == pre_init_log[i].level) + NSPOL_LOGERR("get the init log fail]ret=%d,count=%d", ret, count); + free(pre_buf); /*free() can be used */ + return; + } + + for (; i < count; i++) + { + level = pre_buf[i].level; + if (type && (level >= NSLOG_INF)) { - NSPOL_LOGWAR (NS_LOG_STACKX_ON, "pre init log: %s", - pre_init_log[i].log_buffer); + continue; } - else if (NSLOG_INF == pre_init_log[i].level) + + switch (level) { - NSPOL_LOGINF (NS_LOG_STACKX_ON, "pre init log: %s", - pre_init_log[i].log_buffer); + case NSLOG_ERR: + NSPOL_LOGERR("pre init log: %s", pre_buf[i].log_buffer); + break; + case NSLOG_WAR: + NSPOL_LOGWAR(NS_LOG_STACKPOOL_ON, "pre init log: %s", + pre_buf[i].log_buffer); + break; + case NSLOG_INF: + NSPOL_LOGINF(NS_LOG_STACKPOOL_ON, "pre init log: %s", + pre_buf[i].log_buffer); + break; + case NSLOG_DBG: + NSPOL_LOGDBG(NS_LOG_STACKPOOL_ON, "pre init log: %s", + pre_buf[i].log_buffer); + break; + default: + break; } } + + free(pre_buf); /*free() can be used */ + return; } -int -cmp_log_path (const char *path) +void get_current_time(char *buf, const int len) { - if (NULL == path) + if (NULL == buf || len <= 0) { - return 1; + return; } - /* remove struct log_info g_nstack_log_info */ - if (NULL != g_log_init_para.mon_log_path) + int retVal; + time_t cur_tick; + struct tm cur_time; + + (void) time(&cur_tick); /*time() can be used */ + if (NULL == localtime_r(&cur_tick, &cur_time)) { - if (strcmp (g_log_init_para.mon_log_path, path) == 0) - { - return 0; - } + return; + } + + // from man page of localtime_r: + // tm_year The number of years since 1900. + // tm_mon The number of months since January, in the range 0 to 11. + /* There are some unsafe function ,need to be replace with safe function */ + retVal = snprintf_s(buf, len, len - 1, "%04d%02d%02d%02d%02d%02d", + cur_time.tm_year + 1900, cur_time.tm_mon + 1, + cur_time.tm_mday, cur_time.tm_hour, cur_time.tm_min, + cur_time.tm_sec); + if (-1 == retVal) + { + return; } - return 1; + buf[len - 1] = 0; } -void -get_current_time (char *buf, const int len) +void nstack_setlog_level(int module, uint32_t level) { - int retVal; - time_t cur_tick; - struct tm cur_time; - (void) time (&cur_tick); - /* add return value check, */ - if (NULL == localtime_r (&cur_tick, &cur_time)) + if (MAX_LOG_MODULE <= module || module < 0) { - return; + return; + } + g_nstack_logs[module].level = level; + /* log suppression switched off when level set to DBG */ + g_nstack_logs[module].suppress_off = (NSLOG_DBG == level) ? 1 : 0; +} + +bool nstack_log_info_check(uint32_t module, uint32_t level) +{ + if ((MAX_LOG_MODULE <= module) || !nstack_log_level_valid(level)) + { + return FALSE; } - // from man page of localtime_r: - // tm_year The number of years since 1900. - // tm_mon The number of months since January, in the range 0 to 11. - retVal = - SNPRINTF_S (buf, len, len - 1, "%04d%02d%02d%02d%02d%02d", - cur_time.tm_year + 1900, cur_time.tm_mon + 1, - cur_time.tm_mday, cur_time.tm_hour, cur_time.tm_min, - cur_time.tm_sec); - if (-1 == retVal) + /* no need compare module ,which is done ahead */ + if ((LOG_PRO_INVALID == g_my_pro_type) || (FALSE != ctrl_log_switch)) { - return; + return FALSE; } - buf[len - 1] = 0; + + return TRUE; + } /***************************************************************************** -* Prototype : nstack_setlog_level -* Description : Set global log level -* Input : int module -* uint32_t level +* Prototype : nstack_log_method_check +* Description : log print method choice, process main, master, nStackCtrl use +* domain socket to log, app and segment error use orginal method. +* Input : uint32_t level +* ... * Output : None -* Return Value : void +* Return Value : bool * Calls : * Called By : *****************************************************************************/ -void -nstack_setlog_level (int module, uint32_t level) +bool nstack_log_method_check(uint32_t level) { - if (MAX_LOG_MODULE <= module || module < 0) + if (LOG_PRO_APP <= g_my_pro_type) + { + return FALSE; + } + + //for segment error log + if (level == NSLOG_EMG) { - return; + return FALSE; } - g_nstack_logs[module].level = level; + + if (!log_asyn_inited) + { + return FALSE; + } + + return TRUE; +} + +NSTACK_STATIC int get_file_type(uint32_t module) +{ + return g_nstack_logs[module].file_type; } /***************************************************************************** -* Prototype : nstack_log_info_check -* Description : log info check +* Prototype : nstack_log +* Description : log print * Input : uint32_t module -* uint32_t level +* const char *format * ... * Output : None -* Return Value : bool +* Return Value : None * Calls : * Called By : *****************************************************************************/ -bool -nstack_log_info_check (uint32_t module, uint32_t level) +NSTACK_FMT_CHECK(3) + void nstack_log(uint32_t module, uint32_t level, const char *format, ...) { - if (MAX_LOG_MODULE <= module) + va_list ap; + int ret; + char pre_buf[PRE_INIT_LOG_LENGTH] = { 0 }; + char buf[MAX_BUFFER_LEN] = { 0 }; + char format_buf[MAX_BUFFER_LEN]; + format_buf[sizeof(format_buf) - 1] = 0; + int file_type = 0; + + if (NULL == format) + { + return; + } + + ret = nstack_log_get_prefix(level, pre_buf, sizeof(pre_buf)); + if (ret < 0) { - return false; + return; } - /* no need compare module ,which is done ahead */ - if (LOG_PRO_INVALID == g_my_pro_type) + ret = sprintf_s(format_buf, sizeof(format_buf), "%s %s", pre_buf, format); + if (-1 == ret) { - return false; + return; } - return true; + + va_start(ap, format); /*no need to check return */ + ret = vsprintf_s(buf, sizeof(buf), format_buf, ap); + if (-1 == ret) + { + va_end(ap); + return; + } + va_end(ap); + + buf[sizeof(buf) - 1] = '\0'; + + //get the file type + if (MAX_LOG_MODULE <= module) + { + return; //something wrong, but can't print log here + } + file_type = get_file_type(module); + + // send the buf and write to client fd + (void) nstack_log_client_send(file_type, buf, ret); + + return; } -/* *INDENT-OFF* */ NSTACK_STATIC inline void init_operation_log_para() { g_nstack_logs[OPERATION].file_type = LOG_TYPE_OPERATION; @@ -213,24 +295,28 @@ NSTACK_STATIC inline void init_nstack_log_para() { int i = 0; - (void)glogLevelSet(GLOG_LEVEL_DEBUG); + /* change to glog functions,no need file type control */ + (void) glogLevelSet(GLOG_LEVEL_DEBUG); glogBufLevelSet(GLOG_LEVEL_WARNING); - for(; i<GLOG_LEVEL_BUTT; i++) - glogSetLogSymlink(i,""); + for (; i < GLOG_LEVEL_BUTT; i++) + glogSetLogSymlink(i, ""); glogDir(g_log_init_para.run_log_path); nstack_log_count_set(g_log_init_para.run_log_count); glogMaxLogSizeSet(g_log_init_para.run_log_size); - glogSetLogFilenameExtension(STACKX_LOG_NAME); + glogSetLogFilenameExtension(STACKPOOL_LOG_NAME); glogFlushLogSecsSet(FLUSH_TIME); - for (i = 0; i < MAX_LOG_MODULE ; i++ ) + /* Fix nstack_log_init file type */ + for (i = 0; i < MAX_LOG_MODULE; i++) { if (i == OPERATION) { continue; } + g_nstack_logs[i].file_type = LOG_TYPE_NSTACK; } + init_operation_log_para(); } @@ -238,36 +324,44 @@ NSTACK_STATIC inline void init_ctrl_log_para() { int i = 0; - (void)glogLevelSet(GLOG_LEVEL_DEBUG); + /* change to glog functions,no need file type control */ + /* omc_ctrl single log file should be 10M [Start] */ + (void) glogLevelSet(GLOG_LEVEL_DEBUG); glogBufLevelSet(GLOG_LEVEL_WARNING); - for(; i<GLOG_LEVEL_BUTT; i++) - glogSetLogSymlink(i,""); + for (; i < GLOG_LEVEL_BUTT; i++) + glogSetLogSymlink(i, ""); glogDir(g_log_init_para.mon_log_path); nstack_log_count_set(g_log_init_para.mon_log_count); glogMaxLogSizeSet(g_log_init_para.mon_log_size); glogSetLogFilenameExtension(OMC_CTRL_LOG_NAME); glogFlushLogSecsSet(FLUSH_TIME); + + for (i = 0; i < MAX_LOG_MODULE; i++) + { + g_nstack_logs[i].file_type = LOG_TYPE_CTRL; + } } NSTACK_STATIC inline void init_master_log_para() { int i = 0; - (void)glogLevelSet(GLOG_LEVEL_DEBUG); + /* change to glog functions,no need file type control */ + (void) glogLevelSet(GLOG_LEVEL_DEBUG); glogBufLevelSet(GLOG_LEVEL_WARNING); - for(; i<GLOG_LEVEL_BUTT; i++) - glogSetLogSymlink(i,""); + for (; i < GLOG_LEVEL_BUTT; i++) + glogSetLogSymlink(i, ""); glogDir(g_log_init_para.mon_log_path); nstack_log_count_set(g_log_init_para.mon_log_count); glogMaxLogSizeSet(g_log_init_para.mon_log_size); glogSetLogFilenameExtension(MASTER_LOG_NAME); glogFlushLogSecsSet(FLUSH_TIME); - for (i = 0; i < MAX_LOG_MODULE ; i++ ) + + for (i = 0; i < MAX_LOG_MODULE; i++) { g_nstack_logs[i].file_type = LOG_TYPE_MASTER; } } -/* *INDENT-OFF* */ /***************************************************************************** * Prototype : nstack_log_init @@ -280,83 +374,116 @@ NSTACK_STATIC inline void init_master_log_para() *****************************************************************************/ int nstack_log_init() { - char *pst_temp = NULL; - int log_level = NSLOG_INF; - pst_temp = getenv("NSTACK_LOG_ON"); - if (pst_temp) - { - if (strcmp (pst_temp, "INF") == 0) - { - log_level = NSLOG_INF; - } - else if (strcmp (pst_temp, "DBG") == 0) - { - log_level = NSLOG_DBG; - } - else if (strcmp (pst_temp, "WAR") == 0) - { - log_level = NSLOG_WAR; - } - else if (strcmp (pst_temp, "ERR") == 0) + char *pst_temp = NULL; + uint32_t log_level = NSLOG_INF; + int proc_type = g_my_pro_type; + int ret_client = 0; + int ret_server = 0; + bool type = FALSE; + + pst_temp = getenv("NSTACK_LOG_ON"); /*getenv() can be used */ + + if (pst_temp) { - log_level = NSLOG_ERR; + if (strcmp(pst_temp, "INF") == 0) + { + log_level = NSLOG_INF; + } + else if (strcmp(pst_temp, "DBG") == 0) + { + log_level = NSLOG_DBG; + } + else if (strcmp(pst_temp, "WAR") == 0) + { + log_level = NSLOG_WAR; + } + else if (strcmp(pst_temp, "ERR") == 0) + { + log_level = NSLOG_ERR; + } + else if (strcmp(pst_temp, "EMG") == 0) + { + log_level = NSLOG_EMG; + } + else + { + log_level = NSLOG_ERR; + } + } - else if (strcmp (pst_temp, "EMG") == 0) + else { - log_level = NSLOG_EMG; + log_level = NSLOG_INF; } - else if (strcmp (pst_temp, "PERF") == 0) + + int i = 0; + for (i = 0; i < MAX_LOG_MODULE; i++) { - ctrl_log_switch = 1; + nstack_setlog_level(i, log_level); } - else + + if (log_level <= NSLOG_WAR) { - log_level = NSLOG_ERR; + /*MONITR log level must set to larger than warning */ + nstack_setlog_level(MASTER, NSLOG_WAR); } - } - else + + /* monitr and nstack write the same file, it will cause synchronize problem */ + switch (proc_type) { - log_level = NSLOG_INF; + case LOG_PRO_NSTACK: + glogInit("NSTACK"); + init_nstack_log_para(); + break; + case LOG_PRO_OMC_CTRL: + glogInit("CTRL"); + init_ctrl_log_para(); + type = TRUE; + break; + case LOG_PRO_MASTER: + glogInit("MASTER"); + init_master_log_para(); + break; + default: + return 0; } - int i = 0; - for (i = 0; i < MAX_LOG_MODULE; i++) + + init_log_ctrl_info(); + + // this is for monitr to check whether log has beed inited + g_nstack_logs[NSOCKET].inited = 1; + + /* init the asyn log method for */ + ret_server = nstack_log_server_init(proc_type); + + ret_client = nstack_log_client_init(proc_type); + + /* if async log init fail, + * use synchron log method and record it.*/ + + if ((ret_client == 0) && (ret_server == 0)) { - nstack_setlog_level (i, log_level); + log_asyn_inited = TRUE; } - if (log_level <= NSLOG_WAR) + else { - /*MONITOR log level must set to larger than warning */ - nstack_setlog_level (MASTER, NSLOG_WAR); + NSPOL_LOGWAR(NS_LOG_STACKPOOL_ON, + "async log module init fail, use synchron log"); } - /* monitor and nstack write the same file, it will cause synchronize problem */ - switch (g_my_pro_type) - { - case LOG_PRO_NSTACK: - glogInit ("NSTACK"); - init_nstack_log_para (); - break; - case LOG_PRO_OMC_CTRL: - glogInit ("CTRL"); - init_ctrl_log_para (); - break; - case LOG_PRO_MASTER: - glogInit ("MASTER"); - init_master_log_para (); - break; - default: - return 0; - } + NSPOL_LOGINF(NS_LOG_STACKPOOL_ON, "daemon-stack_version=%s", + NSTACK_VERSION); + NSPOL_LOGINF(NS_LOG_STACKPOOL_ON, + "ret_client=%d,ret_server=%d,log_asyn_inited=%d", + ret_client, ret_server, log_asyn_inited); - init_log_ctrl_info(); + /* omc log restrain */ + write_pre_init_log(type); - // this is for monitr to check whether log has beed inited - g_nstack_logs[NSOCKET].inited = 1; - NSPOL_LOGERR ("nStackMain_version=%s", NSTACK_VERSION); - write_pre_init_log(); - return 0; + return 0; } +/* nStack Log print */ /***************************************************************************** * Prototype : get_str_value * Description : get int value @@ -366,27 +493,26 @@ int nstack_log_init() * Calls : * Called By : *****************************************************************************/ -int -get_str_value (const char *arg) +int get_str_value(const char *arg) { - char *parsing_end; - int iValue = 0; - int oldErrno = errno; - if (arg == NULL) + char *parsing_end; + int iValue = 0; + int oldErrno = errno; + + if (arg == NULL) { - return -1; + return -1; } - errno = 0; - iValue = (int) strtol (arg, &parsing_end, 0); - if (errno || (!parsing_end) || parsing_end[0] != 0) + errno = 0; + iValue = (int) strtol(arg, &parsing_end, 0); + if (errno || (!parsing_end) || parsing_end[0] != 0) { - iValue = -1; + iValue = -1; } errno = oldErrno; - return iValue; + return iValue; } - /***************************************************************************** * Prototype : setlog_level_value * Description : proc log level config @@ -397,61 +523,62 @@ get_str_value (const char *arg) * Calls : * Called By : *****************************************************************************/ -int -setlog_level_value (const char *param, const char *value) +int setlog_level_value(const char *param, const char *value) { - int i = 0; - int module = 0; - int logLevel = 0; - module = get_str_value (param); - if ((module < 0) || (MAX_LOG_MODULE <= module)) + int i = 0; + int module = 0; + int logLevel = 0; + module = get_str_value(param); + if ((module < 0) || (MAX_LOG_MODULE <= module)) { - NSOPR_LOGERR ("input module error]param=%s,module=%d", param, module); - return 1; + NSOPR_LOGERR("input module error]param=%s,module=%d", param, module); + return 1; } - - if (strcmp (value, LOG_LEVEL_ERR) == 0) + if (strcmp(value, LOG_LEVEL_ERR) == 0) { - logLevel = NSLOG_ERR; + logLevel = NSLOG_ERR; } - else if (strcmp (value, LOG_LEVEL_WAR) == 0) + else if (strcmp(value, LOG_LEVEL_WAR) == 0) { - logLevel = NSLOG_WAR; + logLevel = NSLOG_WAR; } - else if (strcmp (value, LOG_LEVEL_DBG) == 0) + else if (strcmp(value, LOG_LEVEL_DBG) == 0) { - logLevel = NSLOG_DBG; + logLevel = NSLOG_DBG; } - else if (strcmp (value, LOG_LEVEL_INF) == 0) + else if (strcmp(value, LOG_LEVEL_INF) == 0) { - logLevel = NSLOG_INF; + logLevel = NSLOG_INF; } - else if (strcmp (value, LOG_LEVEL_EMG) == 0) + else if (strcmp(value, LOG_LEVEL_EMG) == 0) { - logLevel = NSLOG_EMG; + logLevel = NSLOG_EMG; } - else + else { - NSOPR_LOGERR ("input log level error!"); - return 1; + NSOPR_LOGERR("input log level error!"); + return 1; } - NSOPR_LOGINF ("set module log with level]module=%d,logLevel=0x%x", - module, logLevel); - if (module > 0) + + NSOPR_LOGINF("set module log with level]module=%d,logLevel=0x%x", module, + logLevel); + + if (module > 0) { - nstack_setlog_level (module, logLevel); - return 0; + nstack_setlog_level(module, logLevel); + return 0; } - if (0 == module) + + if (0 == module) { - for ( i = 0; i < MAX_LOG_MODULE ; i++ ) + for (i = 0; i < MAX_LOG_MODULE; i++) { - nstack_setlog_level(i,logLevel); + nstack_setlog_level(i, logLevel); } } - return 0; -} + return 0; +} /***************************************************************************** * Prototype : check_log_dir_valid @@ -462,39 +589,39 @@ setlog_level_value (const char *param, const char *value) * Calls : * Called By : *****************************************************************************/ -int -check_log_dir_valid (const char *path) +int check_log_dir_valid(const char *path) { - size_t length; - struct stat statbuf; - if (NULL == path) + size_t length; + struct stat statbuf; + if (NULL == path) { - return -1; + return -1; } - length = strlen (path) + 1; - if ((length <= 1) || (length > FILE_NAME_LEN)) + + length = strlen(path) + 1; + if ((length <= 1) || (length > FILE_NAME_LEN)) { - return -1; + return -1; } - /* only write permission is allowed */ - if ((0 != access (path, W_OK))) + /* only write permission is legal */ + if ((0 != access(path, W_OK))) { - /* if path can access, use env path */ - return -1; + /* if path can access, use env path */ + return -1; } - if ((0 == lstat (path, &statbuf)) && S_ISDIR (statbuf.st_mode)) + if ((0 == lstat(path, &statbuf)) && S_ISDIR(statbuf.st_mode)) { - return 0; - } - else + return 0; + + } + else { - return -1; + return -1; } } - /***************************************************************************** * Prototype : get_app_env_log_path * Description : called by environment-specific log init function @@ -505,49 +632,48 @@ check_log_dir_valid (const char *path) * Calls : * Called By : *****************************************************************************/ -int -get_app_env_log_path (char *app_file_path, unsigned int app_file_size) +int get_app_env_log_path(char *app_file_path, unsigned int app_file_size) { - char *pst_app_log_path_flag = NULL; - char *pst_app_log_path_string = NULL; - int log_to_file = 0; - int ret = -1; - char *app_dir = NULL; + char *pst_app_log_path_flag = NULL; + char *pst_app_log_path_string = NULL; + int log_to_file = 0; + int ret = -1; + char *app_dir = NULL; - if ((NULL == app_file_path) || (0 == app_file_size)) + if ((NULL == app_file_path) || (0 == app_file_size)) { - return 0; + return 0; } - pst_app_log_path_flag = getenv ("NSTACK_LOG_FILE_FLAG"); - if (pst_app_log_path_flag && strcmp (pst_app_log_path_flag, "1") == 0) + + pst_app_log_path_flag = getenv("NSTACK_LOG_FILE_FLAG"); /* getenv() can be used */ + + if (pst_app_log_path_flag && strcmp(pst_app_log_path_flag, "1") == 0) { - /* if set environment variable to 1,then output to file*/ + /* if set enviroment variable to 1,then output to file */ log_to_file = 1; } - else + else { - /* if environment variable is not equal 1 or - don't set this environment variable ,output to STDOUT */ + /* if enviroment variable is not equal 1 or don't set this enviroment variable ,output to STDOUT */ return 0; } /* add the realpath and dir check */ /* APP LOG can be set by user */ - pst_app_log_path_string = getenv("NSTACK_APP_LOG_PATH"); - + pst_app_log_path_string = getenv("NSTACK_APP_LOG_PATH"); /* getenv() can be used */ if ((NULL == pst_app_log_path_string) - ||(strlen (pst_app_log_path_string) > FILE_NAME_LEN - 1)) + || (strlen(pst_app_log_path_string) > FILE_NAME_LEN - 1)) { - goto app_default; + goto app_default; } - app_dir = realpath (pst_app_log_path_string, NULL); - if (check_log_dir_valid (pst_app_log_path_string) < 0) + app_dir = realpath(pst_app_log_path_string, NULL); + if (check_log_dir_valid(pst_app_log_path_string) < 0) { - goto app_default; + goto app_default; } - ret = STRCPY_S (app_file_path, app_file_size, app_dir); - if(EOK != ret) + ret = strcpy_s(app_file_path, app_file_size, app_dir); + if (EOK != ret) { log_to_file = 0; } @@ -555,53 +681,28 @@ get_app_env_log_path (char *app_file_path, unsigned int app_file_size) free(app_dir); return log_to_file; -app_default: + app_default: - if ((0 == access (APP_LOG_PATH, W_OK))) + if ((0 == access(APP_LOG_PATH, W_OK))) { - ret = STRCPY_S (app_file_path, app_file_size, APP_LOG_PATH); - if (EOK != ret) + ret = strcpy_s(app_file_path, app_file_size, APP_LOG_PATH); + if (EOK != ret) { - log_to_file = 0; + log_to_file = 0; } } - else + else { - log_to_file = 0; + log_to_file = 0; } - if (NULL != app_dir) + if (NULL != app_dir) { - free (app_dir); + free(app_dir); } - return log_to_file; - -} - -/***************************************************************************** -* Prototype : nstack_get_app_logname -* Description : get the name of app's log -* Input : None -* Output : None -* Return Value : int -* Calls : -* Called By : -*****************************************************************************/ -int -nstack_get_app_logname (char* log_name) -{ - int pid = getpid (); - char processname[FILE_NAME_LEN] = {0}; - - if (log_name == NULL) - return 1; - - strncpy (processname, program_invocation_short_name, 10); - - snprintf (log_name, FILE_NAME_LEN, "app_%s_%d.log", processname, pid); + return log_to_file; - return 0; } /***************************************************************************** @@ -613,252 +714,290 @@ nstack_get_app_logname (char* log_name) * Calls : * Called By : *****************************************************************************/ -void -nstack_log_init_app () +void nstack_log_init_app() { - char *pc_temp = NULL; - int log_level = NSLOG_ERR; - int i = 0; - int file_flag = 0; - char app_log_path[FILE_NAME_LEN] = { 0 }; - int ret = 0; - char app_log_name[FILE_NAME_LEN] = { 0 }; + char *pc_temp = NULL; + uint32_t log_level = NSLOG_ERR; + int i = 0; + int file_flag = 0; + char app_log_path[FILE_NAME_LEN] = { 0 }; - /* log already initialized, just return */ - if (LOG_PRO_INVALID != g_my_pro_type) + /* log alread initialized, just return */ + if (LOG_PRO_INVALID != g_my_pro_type) { - return; + return; } - /* Add app log hook module init */ - nstack_log_hook_init (); - if (0 != g_nstack_logs[NSOCKET].inited) + /* Add app log hook module init */ + nstack_log_hook_init(); + + if (0 != g_nstack_logs[NSOCKET].inited) { - return; + return; } - glogInit ("APP"); - pc_temp = getenv ("NSTACK_LOG_ON"); - if (pc_temp) + glogInit("APP"); + + pc_temp = getenv("NSTACK_LOG_ON"); /*getenv() can be used */ + + if (pc_temp) { - if (strcmp (pc_temp, "INF") == 0) - { - log_level = NSLOG_INF; - } - else if (strcmp (pc_temp, "DBG") == 0) + if (strcmp(pc_temp, "INF") == 0) { - log_level = NSLOG_DBG; + log_level = NSLOG_INF; } - else if (strcmp (pc_temp, "WAR") == 0) + else if (strcmp(pc_temp, "DBG") == 0) { - log_level = NSLOG_WAR; + log_level = NSLOG_DBG; } - else if (strcmp (pc_temp, "ERR") == 0) + else if (strcmp(pc_temp, "WAR") == 0) { - log_level = NSLOG_ERR; + log_level = NSLOG_WAR; } - else if (strcmp (pc_temp, "EMG") == 0) + else if (strcmp(pc_temp, "ERR") == 0) { - log_level = NSLOG_EMG; + log_level = NSLOG_ERR; } - else if (strcmp (pc_temp, "PERF") == 0) + else if (strcmp(pc_temp, "EMG") == 0) { - ctrl_log_switch = 1; + log_level = NSLOG_EMG; } - else + else { - log_level = NSLOG_ERR; + log_level = NSLOG_ERR; } } - else + else { - log_level = NSLOG_ERR; + log_level = NSLOG_ERR; } - /* socket interface APP called include both stack-x and nstack module! */ - nstack_setlog_level (STACKX, log_level); - nstack_setlog_level (NSOCKET, log_level); - nstack_setlog_level (LOGRTE, log_level); - nstack_setlog_level (LOGDFX, log_level); - nstack_setlog_level (LOGFW, log_level); - nstack_setlog_level (LOGHAL, log_level); - nstack_setlog_level (LOGSBR, log_level); + /* socket interface APP called include both stackpool and nstack module! */ + nstack_setlog_level(STACKPOOL, log_level); + nstack_setlog_level(NSOCKET, log_level); + nstack_setlog_level(LOGRTP, log_level); + nstack_setlog_level(LOGDFX, log_level); + nstack_setlog_level(LOGFW, log_level); + nstack_setlog_level(LOGHAL, log_level); + nstack_setlog_level(LOGSBR, log_level); - /* package the app env handle function, Begin */ - file_flag = get_app_env_log_path (app_log_path, FILE_NAME_LEN); - if ((1 == file_flag) && (strlen (app_log_path) > 0)) + file_flag = get_app_env_log_path(app_log_path, FILE_NAME_LEN); + if ((1 == file_flag) && (strlen(app_log_path) > 0)) { - glogDir (app_log_path); - glogBufLevelSet (GLOG_LEVEL_WARNING); - (void) glogLevelSet (GLOG_LEVEL_DEBUG); - for (i = 0; i < GLOG_LEVEL_BUTT; i++) - glogSetLogSymlink (i, ""); - nstack_log_count_set (APP_LOG_COUNT); - glogMaxLogSizeSet (APP_LOG_SIZE); - ret = nstack_get_app_logname (app_log_name); - if (ret == 0) - { - glogSetLogFilenameExtension (app_log_name); - } - else - { - glogSetLogFilenameExtension (APP_LOG_NAME); - } - glogFlushLogSecsSet (FLUSH_TIME); + /* change to glog functions,no need file type control */ + glogDir(app_log_path); + glogBufLevelSet(GLOG_LEVEL_WARNING); + (void) glogLevelSet(GLOG_LEVEL_DEBUG); + for (i = 0; i < GLOG_LEVEL_BUTT; i++) + glogSetLogSymlink(i, ""); + nstack_log_count_set(APP_LOG_COUNT); + glogMaxLogSizeSet(APP_LOG_SIZE); + glogSetLogFilenameExtension(APP_LOG_NAME); + glogFlushLogSecsSet(FLUSH_TIME); } - else + else { - glogToStderrSet (1); + glogToStderrSet(1); } - for (i = 0; i < MAX_LOG_MODULE; i++) + for (i = 0; i < MAX_LOG_MODULE; i++) { - g_nstack_logs[i].file_type = LOG_TYPE_APP; + g_nstack_logs[i].file_type = LOG_TYPE_APP; } - init_log_ctrl_info (); - g_my_pro_type = LOG_PRO_APP; - SetGlogCtrlOpt (TRUE); - NSPOL_LOGERR ("app_nStack_version=%s", NSTACK_VERSION); - return; + + init_log_ctrl_info(); + + g_my_pro_type = LOG_PRO_APP; + SetGlogCtrlOpt(TRUE); + + NSPOL_LOGCUSINF("app_nStack_version=%s", NSTACK_VERSION); + return; } -void -nstack_segment_error (int s) +void nstack_segment_error(int s) { - #define BACKTRACE_SIZ 20 - void *array[BACKTRACE_SIZ]; - int size; - int i; - char **strings = NULL; - /*if set, flush the log immediately */ - glogFlushLogFiles (GLOG_LEVEL_DEBUG); + void *array[BACKTRACE_SIZ]; + int size; + int i; + char **strings = NULL; - size = backtrace (array, BACKTRACE_SIZ); - NSPOL_LOGEMG - ("------------------DUMP_BACKTRACE[%d]--------------------------------\n", - size); + /*if set, flush the log immediately */ + glogFlushLogFiles(GLOG_LEVEL_DEBUG); - /* easy to view signal in separate log file */ - NSPOL_LOGEMG ("Received signal s=%d", s); + size = backtrace(array, BACKTRACE_SIZ); + NSPOL_LOGEMG + ("------------------DUMP_BACKTRACE[%d]--------------------------------\n", + size); - for (i = 0; i < size; i++) + /*easy to view signal in separate log file */ + NSPOL_LOGEMG("Received signal s=%d", s); + + for (i = 0; i < size; i++) { - NSPOL_LOGEMG ("[%d]:%p\n", i, array[i]); + NSPOL_LOGEMG("[%d]:%p\n", i, array[i]); } - strings = backtrace_symbols (array, size); - if (NULL == strings) + + strings = backtrace_symbols(array, size); + if (NULL == strings) { - return; + return; } - for (i = 0; i < size; i++) + for (i = 0; i < size; i++) { - NSPOL_LOGEMG ("[%d]:%s\n", i, strings[i]); + NSPOL_LOGEMG("[%d]:%s\n", i, strings[i]); } - NSPOL_LOGEMG - ("-------------------------------------------------------------------\n"); - free (strings); + + NSPOL_LOGEMG + ("-------------------------------------------------------------------\n"); + free(strings); /*free() can be used */ + } -void -set_log_init_para (struct log_init_para *para) +void set_log_init_para(struct log_init_para *para) { - if (NULL == para) - + if (NULL == para) { - return; + return; } - if (EOK != - MEMCPY_S (&g_log_init_para, sizeof (struct log_init_para), para, - sizeof (struct log_init_para))) + if (EOK != + memcpy_s(&g_log_init_para, sizeof(struct log_init_para), para, + sizeof(struct log_init_para))) { - return; + return; } } /* control log printed counts */ -static inline void -update_log_prt_time (struct timespec *cur_time, struct timespec *log_prt_time) +static inline void update_log_prt_time(struct timespec *cur_time, + struct timespec *log_prt_time) { - log_prt_time->tv_sec = cur_time->tv_sec; - log_prt_time->tv_nsec = cur_time->tv_nsec; + log_prt_time->tv_sec = cur_time->tv_sec; + log_prt_time->tv_nsec = cur_time->tv_nsec; } -int -check_log_prt_time (int id) +bool check_log_prt_time(int id) { - struct timespec cur_time; - struct timespec *log_prt_time = NULL; - if (id >= LOG_CTRL_ID_MAX || id < 0) + struct timespec cur_time; + struct timespec *log_prt_time = NULL; + + if (id >= LOG_CTRL_ID_MAX || id < 0) + { + return FALSE; + } + + (void) clock_gettime(CLOCK_MONOTONIC, &cur_time); + log_prt_time = &g_log_ctrl_info[id].last_log_time; + if (cur_time.tv_sec - log_prt_time->tv_sec >= + g_log_ctrl_info[id].expire_time) { - return 0; + /*first log need print, Begin */ + set_log_ctrl_time(id, DEFAULT_LOG_CTR_TIME); + update_log_prt_time(&cur_time, log_prt_time); + return TRUE; } - (void) clock_gettime (CLOCK_MONOTONIC, &cur_time); - log_prt_time = &g_log_ctrl_info[id].last_log_time; - if (cur_time.tv_sec - log_prt_time->tv_sec >= - g_log_ctrl_info[id].expire_time) + + g_log_ctrl_info[id].unprint_count++; + return FALSE; +} + +/***************************************************************************** +* Prototype : check_log_restrain_valid +* Description : check if the log if valid and ctrl restrain time expire. +* Input : int id +* : uint32_t module, +* : uint32_t level +* ... +* Output : None +* Return Value : bool +* Calls : +* Called By : +*****************************************************************************/ +bool check_log_restrain_valid(int id, uint32_t module, uint32_t level) +{ + if (nstack_log_info_check(module, level) && check_log_prt_time(id)) { - /* first log need print */ - set_log_ctrl_time (id, DEFAULT_LOG_CTR_TIME); - update_log_prt_time (&cur_time, log_prt_time); - return 1; + return TRUE; } - g_log_ctrl_info[id].unprint_count++; - return 0; + + return FALSE; } -int -get_unprt_log_count (int id) +int get_unprt_log_count(int id) { - return g_log_ctrl_info[id].unprint_count; + return g_log_ctrl_info[id].unprint_count; } -void -clr_unprt_log_count (int id) +void clr_unprt_log_count(int id) { - g_log_ctrl_info[id].unprint_count = 0; + g_log_ctrl_info[id].unprint_count = 0; } -void -set_log_ctrl_time (int id, int ctrl_time) +void set_log_ctrl_time(int id, int ctrl_time) { - if (id >= LOG_CTRL_ID_MAX || id < 0) + if (id >= LOG_CTRL_ID_MAX || id < 0) { - return; + return; } - if (ctrl_time <= 0) + if (ctrl_time <= 0) + { + return; + } + + g_log_ctrl_info[id].expire_time = ctrl_time; +} + +void init_log_ctrl_info() +{ + int i = 0; + for (; i < LOG_CTRL_ID_MAX; i++) { - return; + /*first log need print */ + g_log_ctrl_info[i].expire_time = 0; + g_log_ctrl_info[i].unprint_count = 0; + g_log_ctrl_info[i].last_log_time.tv_sec = 0; + g_log_ctrl_info[i].last_log_time.tv_nsec = 0; } - g_log_ctrl_info[id].expire_time = ctrl_time; + // for every socket api, need different log id + + // for nstack inner +} + +void set_log_proc_type(int log_proc_type) +{ + g_my_pro_type = log_proc_type; } -void -init_log_ctrl_info () +int nstack_log_flush(unsigned long long timeout) { - int i = 0; - for (; i < LOG_CTRL_ID_MAX; i++) + if (LOG_PRO_APP <= g_my_pro_type) { - /* first log need print */ - g_log_ctrl_info[i].expire_time = 0; - g_log_ctrl_info[i].unprint_count = 0; - g_log_ctrl_info[i].last_log_time.tv_sec = 0; - g_log_ctrl_info[i].last_log_time.tv_nsec = 0; + glogFlushLogFiles(GLOG_LEVEL_DEBUG); + return 0; } - // for every socket api, need different log id + if (log_asyn_inited) + { + return nstack_log_server_flush(g_my_pro_type, timeout); + } + else + { + return -1; + } +} - // for nstack inner +void set_nstack_log_nonreentry(uint32_t val) +{ + nstack_log_nonreentry = val; } -void -set_log_proc_type (int log_proc_type) +unsigned int get_nstack_log_nonreentry(void) { - g_my_pro_type = log_proc_type; + return nstack_log_nonreentry; } diff --git a/src/framework/log/nstack_log_async.c b/src/framework/log/nstack_log_async.c new file mode 100644 index 0000000..1b17d8d --- /dev/null +++ b/src/framework/log/nstack_log_async.c @@ -0,0 +1,1427 @@ +/* +* +* 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 <fcntl.h> +#include <sys/epoll.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <stddef.h> +#include <stdio.h> +#include <errno.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <pthread.h> +#include "types.h" +#include "nstack_securec.h" +#include "nsfw_base_linux_api.h" +#include "nstack_log_async.h" + +#include <signal.h> +#include <syscall.h> + +/*sockaddr_un.sun_path is an array of 108 bytes*/ +#define UNIX_SOCK_MAX_PATH_LEN 108 +#define MAX_CONN_NUM 5 +#define MAX_LOG_RECV_BUF 0x34000*2 +#define ASYNLOG_THREAD_NAME "nstk_log_asyn" + +NSTACK_STATIC char nstack_sock_running[UNIX_SOCK_MAX_PATH_LEN + 1]; +NSTACK_STATIC char nstack_sock_operation[UNIX_SOCK_MAX_PATH_LEN + 1]; +NSTACK_STATIC char nstack_sock_master[UNIX_SOCK_MAX_PATH_LEN + 1]; +NSTACK_STATIC char nstack_sock_ctrl[UNIX_SOCK_MAX_PATH_LEN + 1]; +NSTACK_STATIC char nstack_sock_dir[UNIX_SOCK_MAX_PATH_LEN + 1]; + +int g_nstack_log_client_fd[MAX_LOG_TYPE] = { -1, -1, -1, -1, -1 }; +int g_nstack_log_server_fd[MAX_LOG_TYPE] = { -1, -1, -1, -1, -1 }; + +#define NSTACK_LOG_SER_STATE_RUNNING 0 +#define NSTACK_LOG_SER_STATE_FLUSHING 1 + +#define NSTACK_LOG_SER_FLUSH_SIG '\5' + +NSTACK_STATIC int g_nstack_log_server_state[MAX_LOG_TYPE] = { NSTACK_LOG_SER_STATE_RUNNING }; /*can be used */ + +static int pre_init_log_count = 0; +static struct pre_init_info pre_init_log[MAX_PRE_INIT_LOG_COUNT] = + { {0, ""} }; +__thread unsigned int pre_log_nonreentry = 0; +extern bool log_asyn_inited; + +/***************************************************************************** +* Prototype : nstack_log_sock_set +* Description : set the sockfd state, for example O_NONBLOCK and so on, +* Input : int sock: fd. +* : int type: module type. +* ... +* Output : None +* Return Value : 0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC inline int nstack_log_sock_set(int sock, int type) +{ + int flags; + + if (type < 0) + { + return -1; + } + + flags = nsfw_base_fcntl(sock, F_GETFD, 0); + if (flags < 0) + { + return -1; + } + + flags |= type; + + if (nsfw_base_fcntl(sock, F_SETFD, flags) < 0) + { + return -1; + } + + return 0; +} + +/***************************************************************************** +* Prototype : unlink_log_servername +* Description : unlink the servername +* Input : int log_type: +* ... +* Output : None +* Return Value : void +* Calls : +* Called By : +*****************************************************************************/ + +void unlink_log_servername(int log_type) +{ + switch (log_type) + { + case LOG_TYPE_NSTACK: + unlink(nstack_sock_running); + break; + case LOG_TYPE_OPERATION: + unlink(nstack_sock_operation); + break; + case LOG_TYPE_MASTER: + unlink(nstack_sock_master); + break; + case LOG_TYPE_CTRL: + unlink(nstack_sock_ctrl); + break; + default: + break; + } + return; + +} + +/***************************************************************************** +* Prototype : nstack_log_sock_path +* Description : init the nstack log domain socket path which use to handle +* the log with a thread of long connect +* Input : int proc_type +* ... +* Output : static varible store +* Return Value : >=0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC int nstack_log_sock_path(int proc_type) +{ + char *directory = "/var/run"; + const char *home_dir = getenv("HOME"); /*can be used */ + bool env_path = FALSE; + int ret = -1; + int val = -1; + int val_opera = -1; + pid_t pid = getpid(); + + if (getuid() != 0 && home_dir != NULL) + { + directory = realpath(home_dir, NULL); + if (!directory) + { + save_pre_init_log(NSLOG_ERR, "directory is NULL]errno=%d", errno); + return -1; + } + env_path = TRUE; + } + + if (EOK != (ret = strcpy_s(nstack_sock_dir, UNIX_SOCK_MAX_PATH_LEN, directory))) /* check return value with EOK */ + { + save_pre_init_log(NSLOG_ERR, "strcpy_s fail]ret=%d", ret); + goto err_init; + } + + /*modify 'destMax' and return value check */ + if (EOK != + (ret = + strcat_s(nstack_sock_dir, sizeof(nstack_sock_dir), "/ip_module"))) + { + save_pre_init_log(NSLOG_ERR, "strcat_s fail]ret=%d", ret); + goto err_init; + } + + switch (proc_type) + { + case LOG_PRO_NSTACK: + val = + sprintf_s(nstack_sock_running, UNIX_SOCK_MAX_PATH_LEN, + "%s/%s_%d", nstack_sock_dir, "nStackMainRunLog", + pid); + val_opera = + sprintf_s(nstack_sock_operation, UNIX_SOCK_MAX_PATH_LEN, + "%s/%s_%d", nstack_sock_dir, "nStackMainOpeLog", + pid); + if (val_opera < 0) + { + save_pre_init_log(NSLOG_ERR, "sprintf_s fail]val_opera=%d", + val_opera); + ret = -1; + goto err_init; + } + break; + case LOG_PRO_MASTER: + val = + sprintf_s(nstack_sock_master, UNIX_SOCK_MAX_PATH_LEN, + "%s/%s_%d", nstack_sock_dir, "nStackMasterLog", + pid); + break; + case LOG_PRO_OMC_CTRL: + // nStackCtrl don't add pid, as it may exit before unlink which may leave a useless file in ip_module directory. + // this will cause losing some log sometime, but it's ok. + val = + sprintf_s(nstack_sock_ctrl, UNIX_SOCK_MAX_PATH_LEN, "%s/%s", + nstack_sock_dir, "nStackCtrlLog"); + break; + default: + save_pre_init_log(NSLOG_ERR, "process invalid]proc_type=%d", + proc_type); + ret = -1; + goto err_init; + } + + if ((val < 0)) + { + save_pre_init_log(NSLOG_ERR, "sprintf_s fail]proc_type=%d,val=%d", + proc_type, val); + ret = -1; + goto err_init; + } + + ret = 0; + + err_init: + + if (env_path == TRUE) + { + free(directory); + } + return ret; +} + +/***************************************************************************** +* Prototype : nstack_log_sock_listen +* Description : create the nstack log domain socket, bind the share domain file, +* listen the client connect, for server side. +* Input : const char *servername, file name for the domain +* ... +* Output : listen fd +* Return Value : >=0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC int nstack_log_sock_listen(const char *servername) +{ + int fd, ret; + unsigned int len; + struct stat st; + struct sockaddr_un un; + int opt = 1; + + if ((ret = stat(nstack_sock_dir, &st)) != 0) + { + save_pre_init_log(NSLOG_ERR, + "stat get file info fail]ret=%d,nstack_sock_dir=%s", + ret, nstack_sock_dir); + return -1; + } + + if ((fd = nsfw_base_socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + { + save_pre_init_log(NSLOG_ERR, "create socket fail]fd=%d,errno=%d", fd, + errno); + return -1; + } + + if ((ret = + nsfw_base_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, + sizeof(opt))) < 0) + { + save_pre_init_log(NSLOG_ERR, "set socket reuse fail]ret=%d,errno=%d", + ret, errno); + goto listen_err; + } + + unlink(servername); /* in case it already exists */ + + ret = memset_s(&un, sizeof(un), 0, sizeof(un)); + if (EOK != ret) + { + save_pre_init_log(NSLOG_ERR, "memset_s fail]ret=%d", ret); + goto listen_err; + } + + un.sun_family = AF_UNIX; + ret = strcpy_s(un.sun_path, sizeof(un.sun_path), servername); + if (EOK != ret) + { + save_pre_init_log(NSLOG_ERR, "strcpy_s fail]ret=%d", ret); + goto listen_err; + } + + len = + (unsigned int) (offsetof(struct sockaddr_un, sun_path) + + strlen(servername)); + + if ((ret = nsfw_base_bind(fd, (struct sockaddr *) &un, len)) < 0) + { + save_pre_init_log(NSLOG_ERR, + "bind domain socket fail]ret=%d,errno=%d", ret, + errno); + goto listen_err; + } + + if ((ret = nsfw_base_listen(fd, MAX_CONN_NUM)) < 0) + { + save_pre_init_log(NSLOG_ERR, "listen fail]ret=%d,errno=%d", ret, + errno); + goto listen_err; + } + + return fd; + + listen_err: + + (void) nsfw_base_close(fd); + + return -1; + +} + +/***************************************************************************** +* Prototype : nstack_log_fd_to_type +* Description : traverse the fd from fds to get the fd num, it returns +* the file type, which matches the fd. +* Input : int *fds +* : int fd +* ... +* Output : fd +* Return Value : >=0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC inline int nstack_log_fd_to_type(const int *fds, int fd) +{ + int i; + for (i = 0; i <= LOG_TYPE_CTRL; i++) + { + if (fd == fds[i]) + { + return i; + } + } + return -1; +} + +/***************************************************************************** +* Prototype : nstack_log_signal_handler +* Description : syn Leibniz issue, the signal interrupt 34, the log collect +* thread create early as process signal handle too late. +* Input : None +* ... +* Output : None +* Return Value : 0 success, -1 false +* Calls : +* Called By : +*****************************************************************************/ +int nstack_log_signal_handler() +{ + sigset_t waitset, oset; + int s = -1; + + if (0 != sigemptyset(&waitset)) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, "sigemptyset fail"); + return -1; + } + + if (0 != sigaddset(&waitset, SIGRTMIN)) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "sigaddset fail]SIGRTMIN"); + return -1; + } + + if (0 != sigaddset(&waitset, SIGRTMIN + 2)) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "sigaddset fail]SIGRTMIN+2"); + return -1; + } + + if ((s = pthread_sigmask(SIG_BLOCK, &waitset, &oset)) != 0) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "pthread_sigmask fail]s=%d", s); + return -1; + } + + return 0; + +} + +#define ASYNC_MAXEVENTS 20 +NSTACK_STATIC int nstack_log_server_prepare(int proc_type, + struct epoll_event *ev, + int *epfd, + struct epoll_event *events) +{ + int ret; + int listen_fd; + + /* thread signal mask handle */ + if (nstack_log_signal_handler() < 0) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "signal handle fail]proc_type=%d", proc_type); + return -1; + } + + /* init the array */ + ret = + memset_s(events, sizeof(struct epoll_event) * ASYNC_MAXEVENTS, 0, + sizeof(struct epoll_event) * ASYNC_MAXEVENTS); + if (EOK != ret) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "memset_s fail]ret=%d,proc_type=%d", ret, proc_type); + return -1; + } + + // create ep fd, the max scope of epoll is 256 + *epfd = nsfw_base_epoll_create(256); + if (*epfd < 0) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "create epoll fail]epfd=%d,proc_type=%d,errno=%d", + *epfd, proc_type, errno); + return -1; + } + + int i; + for (i = 0; i <= LOG_TYPE_CTRL; i++) + { + if ((listen_fd = g_nstack_log_server_fd[i]) <= 0) + { + continue; + } + ev->data.fd = listen_fd; + ev->events = EPOLLIN; + + // add server listen fd to epoll + if ((ret = + nsfw_base_epoll_ctl(*epfd, EPOLL_CTL_ADD, listen_fd, ev)) < 0) + { + NS_PTHREADLOG(LOG_TYPE_UNRECOGNIZED, NSLOG_ERR, + "epoll ctl add fail]ret=%d,epfd=%d,listen_fd=%d,errno=%d", + ret, *epfd, listen_fd, errno); + return -1; + } + } + return 0; + +} + +NSTACK_STATIC int nstack_log_server_recv_old(int *accepted_fd, + struct epoll_event *event) +{ + int sockfd; + int log_type; + //one log content 2048 enough. + char buffer[MAX_BUFFER_LEN]; + ssize_t num; + + log_type = nstack_log_fd_to_type(accepted_fd, event->data.fd); + /*log_type has been protected */ + if ((log_type >= 0) && (log_type < MAX_LOG_TYPE)) + { + if ((sockfd = event->data.fd) < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "accept fd invalid]sockfd=%d,log_type=%d", sockfd, + log_type); + return -1; + } + + /* change 3th param from 'sizeof(buffer)' to 'sizeof(buffer)-1', make room for '\0' terminated */ + if ((num = + nsfw_base_recv(sockfd, buffer, sizeof(buffer) - 1, 0)) <= 0) + { + if (num == 0 || (errno != EAGAIN && errno != EINTR)) + { + //if server close, client side will recv EPIPE + NS_PTHREADLOG(log_type, NSLOG_ERR, + "recv the msg fail]sockfd=%d,num=%ld,log_type=%d,errno=%d", + sockfd, num, log_type, errno); + (void) nsfw_base_close(accepted_fd[log_type]); + accepted_fd[log_type] = -1; + } + return -1; + } + + int offset = 0; + int j; + if (g_nstack_log_server_state[log_type] == + NSTACK_LOG_SER_STATE_FLUSHING) + { + for (j = 0; j < num; j++) + { + if (buffer[j] == NSTACK_LOG_SER_FLUSH_SIG) + { + buffer[j] = '\0'; + glog_print_buffer(log_type, buffer, j); + glogFlushLogFiles(GLOG_LEVEL_DEBUG); + + (void) (__sync_bool_compare_and_swap + (&g_nstack_log_server_state[log_type], + NSTACK_LOG_SER_STATE_FLUSHING, + NSTACK_LOG_SER_STATE_RUNNING)); + + offset = j + 1; + break; + } + } + } + + /* make buffer '\0' terminated. glog_print_buffer() need a '\0' terminated string, or it will coredump!!! */ + buffer[num] = '\0'; + + if (offset < num) + { + // write file + glog_print_buffer(log_type, buffer + offset, num - offset); + } + + return -1; + } + + return 0; +} + +NSTACK_STATIC int nstack_log_server_accept_new(int *accepted_fd, + struct epoll_event *ev, + int epfd, + struct epoll_event *event) +{ + int ret; + int log_type; + + log_type = nstack_log_fd_to_type(g_nstack_log_server_fd, event->data.fd); + /*log_type has been protected */ + if ((log_type >= 0) && (log_type < MAX_LOG_TYPE)) + { + struct sockaddr_un un_cli; + socklen_t clilen = sizeof(un_cli); + accepted_fd[log_type] = + nsfw_base_accept(event->data.fd, (struct sockaddr *) &un_cli, + &clilen); + if (accepted_fd[log_type] < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "accept the socket fail]accepted_fd[%d]=%d,errno=%d", + log_type, accepted_fd[log_type], errno); + return -1; + } + ev->data.fd = accepted_fd[log_type]; + + int size, size_len; + size = MAX_LOG_RECV_BUF; + size_len = sizeof(size); + if ((ret = + nsfw_base_setsockopt(accepted_fd[log_type], SOL_SOCKET, + SO_RCVBUF, (void *) &size, + (socklen_t) size_len)) < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "set the socket sendbuf fail]accepted_fd[%d]=%d,ret=%d,errno=%d", + log_type, accepted_fd[log_type], ret, errno); + (void) nsfw_base_close(accepted_fd[log_type]); + accepted_fd[log_type] = -1; + return -1; + } + + //set the non_blocking mode. + if ((ret = + nstack_log_sock_set(accepted_fd[log_type], O_NONBLOCK)) < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "set the socket non_blocking fail]accepted_fd[%d]=%d,ret=%d", + log_type, accepted_fd[log_type], ret); + (void) nsfw_base_close(accepted_fd[log_type]); + accepted_fd[log_type] = -1; + return -1; + } + + if ((ret = + nsfw_base_epoll_ctl(epfd, EPOLL_CTL_ADD, accepted_fd[log_type], + ev)) < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "add epoll fail]accepted_fd[%d]=%d,ret=%d,errno=%d", + log_type, accepted_fd[log_type], ret, errno); + (void) nsfw_base_close(accepted_fd[log_type]); + accepted_fd[log_type] = -1; + return -1; + } + + if ((ret = + nsfw_base_epoll_ctl(epfd, EPOLL_CTL_DEL, event->data.fd, + NULL)) < 0) + { + NS_PTHREADLOG(log_type, NSLOG_WAR, + "delete the epoll listen fail]event->data.fd=%d,ret=%d,errno=%d", + event->data.fd, ret, errno); + } + + // remove server listening fd and servername as no use then + (void) nsfw_base_close(event->data.fd); + + unlink_log_servername(log_type); + + } + + return 0; +} + +/***************************************************************************** +* Prototype : nstack_log_server_process +* Description : init the nstack log domain socket for server side, and create +* a thread to wait the client conect or data come. +* Input : int proc_type +* ... +* Output : None +* Return Value : void* +* Calls : +* Called By : +*****************************************************************************/ +void *nstack_log_server_process(void *args) +{ + int epfd; + struct epoll_event ev, events[ASYNC_MAXEVENTS]; + int accepted_fd[MAX_LOG_TYPE] = { -1, -1, -1, -1, -1 }; + int proc_type = (int) (u64) args; + + if (0 != nstack_log_server_prepare(proc_type, &ev, &epfd, events)) + { + /* err msg has been printed */ + return ((void *) 0); + } + + while (1) + { + int i; + int nfds = nsfw_base_epoll_wait(epfd, events, ASYNC_MAXEVENTS, -1); + + for (i = 0; i < nfds; i++) + { + /*Notes: it listen the epoll all of the process, cannot save the log by save_pre_init_log + * for the log recv module*/ + if (0 != nstack_log_server_recv_old(accepted_fd, &events[i])) + continue; + + /*Notes: accept the client fd */ + if (0 != + nstack_log_server_accept_new(accepted_fd, &ev, epfd, + &events[i])) + continue; + } + + } + + return ((void *) 0); /*can be used, should never get here */ +} + +/***************************************************************************** +* Prototype : nstack_log_sock_conn +* Description : create the nstack log domain socket, and connect the server, +* for client side. +* Input : const char *servername, file name for the domain +* ... +* Output : fd +* Return Value : >=0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +NSTACK_STATIC int nstack_log_sock_conn(const char *servername) +{ + int fd = -1; + unsigned int len; + struct sockaddr_un un; + int opt = 1; + int ret = -1; + int size = MAX_LOG_RECV_BUF; + size_t size_len; + size_len = sizeof(size); + + if (NULL == servername) + { + save_pre_init_log(NSLOG_ERR, + "invalid input parameter]servername=NULL"); + return -1; + } + + //create a UNIX domain stream socket and it is non blocking + if ((fd = nsfw_base_socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0) /*can be used */ + { + save_pre_init_log(NSLOG_ERR, + "client create the domain socket fail]fd=%d,errno=%d", + fd, errno); + return -1; + } + + if ((ret = + nsfw_base_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, + sizeof(opt))) < 0) + { + save_pre_init_log(NSLOG_ERR, + "client set domain socket reuse fail]fd=%d,ret=%d,errno=%d", + fd, ret, errno); + goto connect_err; + } + + if ((ret = + nsfw_base_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *) &size, + (socklen_t) size_len)) < 0) + { + save_pre_init_log(NSLOG_ERR, + "client set domain socket sendbuf fail]fd=%d,ret=%d,errno=%d", + fd, ret, errno); + goto connect_err; + } + + ret = memset_s(&un, sizeof(un), 0, sizeof(un)); + if (EOK != ret) + { + save_pre_init_log(NSLOG_ERR, "memset_s fail]ret=%d", ret); + goto connect_err; + } + un.sun_family = AF_UNIX; + if (strlen(servername) > UNIX_SOCK_MAX_PATH_LEN) + { + save_pre_init_log(NSLOG_ERR, + "servername string is %d bigger than %d", + strlen(servername), UNIX_SOCK_MAX_PATH_LEN); + goto connect_err; + } + ret = strcpy_s(un.sun_path, sizeof(un.sun_path), servername); + if (EOK != ret) + { + save_pre_init_log(NSLOG_ERR, "strcpy_s fail]ret=%d", ret); + goto connect_err; + } + + len = + (unsigned int) (offsetof(struct sockaddr_un, sun_path) + + strlen(servername)); + + //connect the server + if ((ret = nsfw_base_connect(fd, (struct sockaddr *) &un, len)) < 0) + { + save_pre_init_log(NSLOG_ERR, + "client connect the server fail]ret=%d,errno=%d", + ret, errno); + goto connect_err; + } + + return fd; + + connect_err: + + (void) nsfw_base_close(fd); + + return -1; + +} + +/***************************************************************************** +* Prototype : nstack_log_server_init +* Description : init the nstack log domain socket for server side, and create +* a thread to wait the client conect or data come. +* Input : int proc_type +* ... +* Output : None +* Return Value : 0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +int nstack_log_server_init(int proc_type) +{ + int ret = -1; + int listen_fd = -1; + int listen_fd_opera = -1; + + if ((ret = nstack_log_sock_path(proc_type)) < 0) + { + save_pre_init_log(NSLOG_ERR, "asyn server get path fail]ret=%d", ret); + return -1; + } + + switch (proc_type) + { + case LOG_PRO_NSTACK: + g_nstack_log_server_state[LOG_TYPE_NSTACK] = + NSTACK_LOG_SER_STATE_RUNNING; + g_nstack_log_server_state[LOG_TYPE_OPERATION] = + NSTACK_LOG_SER_STATE_RUNNING; + listen_fd = nstack_log_sock_listen(nstack_sock_running); + g_nstack_log_server_fd[LOG_TYPE_NSTACK] = listen_fd; + listen_fd_opera = nstack_log_sock_listen(nstack_sock_operation); + g_nstack_log_server_fd[LOG_TYPE_OPERATION] = listen_fd_opera; + if (listen_fd_opera < 0) + { + save_pre_init_log(NSLOG_ERR, + "asyn server operation fd listen fail]listen_fd_opera=%d", + listen_fd_opera); + return -1; + } + break; + case LOG_PRO_MASTER: + g_nstack_log_server_state[LOG_TYPE_MASTER] = + NSTACK_LOG_SER_STATE_RUNNING; + listen_fd = nstack_log_sock_listen(nstack_sock_master); + g_nstack_log_server_fd[LOG_TYPE_MASTER] = listen_fd; + break; + case LOG_PRO_OMC_CTRL: + g_nstack_log_server_state[LOG_TYPE_CTRL] = + NSTACK_LOG_SER_STATE_RUNNING; + listen_fd = nstack_log_sock_listen(nstack_sock_ctrl); + g_nstack_log_server_fd[LOG_TYPE_CTRL] = listen_fd; + break; + default: + save_pre_init_log(NSLOG_ERR, "process invalid]proc_type=%d", + proc_type); + return -1; + } + + if (listen_fd < 0) + { + save_pre_init_log(NSLOG_ERR, "asyn server listen fail]listen_fd=%d", + listen_fd); + return -1; + } + + pthread_t t; + if ((ret = + pthread_create(&t, NULL, nstack_log_server_process, + (void *) (u64) proc_type)) != 0) + { + save_pre_init_log(NSLOG_ERR, "asyn server create thread fail]ret=%d", + ret); + return -1; + } + + /* thread name string should smaller than 16 bytes */ + + ret = pthread_setname_np(t, ASYNLOG_THREAD_NAME); + if (ret != 0) + { + save_pre_init_log(NSLOG_WAR, + "asyn server set thread name fail, use process name]ret=%d", + ret); + } + else + { + save_pre_init_log(NSLOG_INF, + "asyn server set thread name success]thread name=%s", + ASYNLOG_THREAD_NAME); + } + + if (proc_type == LOG_PRO_NSTACK) + { + save_pre_init_log(NSLOG_INF, + "asyn server init success]listen_fd=%d,listen_fd_opera=%d", + listen_fd, listen_fd_opera); + } + else + { + save_pre_init_log(NSLOG_INF, "asyn server init success]listen_fd=%d", + listen_fd); + } + + return 0; +} + +#define NSTACK_LOG_SEND_FLUSH_SIG(fd, ret) \ +do \ +{\ + if (fd > 0) \ + { \ + ret = nsfw_base_send(fd, "\5" /* NSTACK_LOG_SER_FLUSH_SIG */, 1, MSG_NOSIGNAL); \ + } else { \ + ret = -1; \ + }\ +} while(0) + +#ifndef MAX_U64_NUM +#define MAX_U64_NUM ((unsigned long long)0xffffffffffffffff) +#endif + +NSTACK_STATIC int nstack_log_current_time2msec(unsigned long long *msec) +{ + struct timespec tout; + if (0 != clock_gettime(CLOCK_MONOTONIC, &tout)) + { + return -1; + } + + if (MAX_U64_NUM / 1000 < (unsigned long long) tout.tv_sec) + { + return -1; + } + unsigned long long sec2msec = 1000 * tout.tv_sec; + unsigned long long nsec2msec = + (unsigned long long) tout.tv_nsec / 1000000; + + if (MAX_U64_NUM - sec2msec < nsec2msec) + { + return -1; + } + + *msec = sec2msec + nsec2msec; + return 0; +} + +int nstack_log_server_flush(int proc_type, unsigned long long timeout) +{ + int i = 0; + unsigned long long start = 0; + unsigned long long end = 0; + int flushed = 0; + int ret = 0; + + switch (proc_type) + { + case LOG_PRO_NSTACK: + g_nstack_log_server_state[LOG_TYPE_NSTACK] = + NSTACK_LOG_SER_STATE_FLUSHING; + g_nstack_log_server_state[LOG_TYPE_OPERATION] = + NSTACK_LOG_SER_STATE_FLUSHING; + + // send ENQ + NSTACK_LOG_SEND_FLUSH_SIG(g_nstack_log_client_fd + [LOG_TYPE_NSTACK], ret); + if (ret < 0) + { + g_nstack_log_server_state[LOG_TYPE_NSTACK] = + NSTACK_LOG_SER_STATE_RUNNING; + g_nstack_log_server_state[LOG_TYPE_OPERATION] = + NSTACK_LOG_SER_STATE_RUNNING; + return -1; + } + NSTACK_LOG_SEND_FLUSH_SIG(g_nstack_log_client_fd + [LOG_TYPE_OPERATION], ret); + if (ret < 0) + { + g_nstack_log_server_state[LOG_TYPE_OPERATION] = + NSTACK_LOG_SER_STATE_RUNNING; + return -1; + } + break; + case LOG_PRO_MASTER: + g_nstack_log_server_state[LOG_TYPE_MASTER] = + NSTACK_LOG_SER_STATE_FLUSHING; + // send ENQ + NSTACK_LOG_SEND_FLUSH_SIG(g_nstack_log_client_fd + [LOG_TYPE_MASTER], ret); + if (ret < 0) + { + g_nstack_log_server_state[LOG_TYPE_MASTER] = + NSTACK_LOG_SER_STATE_RUNNING; + return -1; + } + break; + case LOG_PRO_OMC_CTRL: + g_nstack_log_server_state[LOG_TYPE_CTRL] = + NSTACK_LOG_SER_STATE_FLUSHING; + // send ENQ + NSTACK_LOG_SEND_FLUSH_SIG(g_nstack_log_client_fd[LOG_TYPE_CTRL], + ret); + if (ret < 0) + { + g_nstack_log_server_state[LOG_TYPE_CTRL] = + NSTACK_LOG_SER_STATE_RUNNING; + return -1; + } + break; + default: + return 0; + } + + if (nstack_log_current_time2msec(&start)) + { + return -1; + } + + while (1) + { + if (timeout > 0) + { + if (nstack_log_current_time2msec(&end)) + { + break; + } + if (end < start || (end - start) > timeout) + { + break; + } + } + + flushed = 1; + for (i = 0; i < MAX_LOG_TYPE; i++) + { + if (g_nstack_log_server_state[i] != NSTACK_LOG_SER_STATE_RUNNING) + { + flushed = 0; + break; + } + } + if (flushed) + { + return 0; + } + sys_sleep_ns(0, 500000); + } + + return -1; +} + +/***************************************************************************** +* Prototype : nstack_log_client_init +* Description : init the nstack log domain socket, which use to handle +* the log with a thread of the domain connect, store the +* client fd, for client side. +* Input : int proc_type +* ... +* Output : None +* Return Value : 0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +int nstack_log_client_init(int proc_type) +{ + int connfd = -1; + int connfd_opt = -1; + + switch (proc_type) + { + case LOG_PRO_NSTACK: + //get the con fd and store the fd to g_nstack_log_client_fd + connfd = nstack_log_sock_conn(nstack_sock_running); + g_nstack_log_client_fd[LOG_TYPE_NSTACK] = connfd; + connfd_opt = nstack_log_sock_conn(nstack_sock_operation); + if (connfd_opt < 0) + { + save_pre_init_log(NSLOG_ERR, + "asyn client init fail]connfd_opt=%d", + connfd_opt); + return -1; + } + g_nstack_log_client_fd[LOG_TYPE_OPERATION] = connfd_opt; + break; + case LOG_PRO_MASTER: + connfd = nstack_log_sock_conn(nstack_sock_master); + g_nstack_log_client_fd[LOG_TYPE_MASTER] = connfd; + break; + case LOG_PRO_OMC_CTRL: + connfd = nstack_log_sock_conn(nstack_sock_ctrl); + g_nstack_log_client_fd[LOG_TYPE_CTRL] = connfd; + break; + default: + save_pre_init_log(NSLOG_ERR, "process invalid]proc_type=%d", + proc_type); + return -1; + } + + if (connfd < 0) + { + save_pre_init_log(NSLOG_ERR, "asyn client init fail]connfd=%d", + connfd); + return -1; + } + + if (proc_type == LOG_PRO_NSTACK) + { + save_pre_init_log(NSLOG_INF, + "asyn client init success]connfd=%d,connfd_opt=%d", + connfd, connfd_opt); + } + else + { + save_pre_init_log(NSLOG_INF, "asyn client init success]connfd=%d", + connfd); + } + + return 0; +} + +/***************************************************************************** +* Prototype : nstack_log_client_send +* Description : send the log data to the file, file_type will get the fd +* for the specified conn. +* Input : int file_type +* : char *buffer +* : size_t buflen +* ... +* Output : None +* Return Value : 0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +int nstack_log_client_send(int file_type, char *buffer, size_t buflen) +{ + int connfd = -1; + int num = -1; + int count = 2; //if errno is EAGAIN or EINTR, try twice + if ((NULL == buffer) || (buflen == 0) || (file_type < 0) + || (file_type > LOG_TYPE_CTRL)) + { + return -1; + } + + //get the fd as the file_type specified. + connfd = g_nstack_log_client_fd[file_type]; + if (connfd < 0) + { + NS_PTHREADLOG(file_type, NSLOG_ERR, + "connfd invalid]connfd=%d,file_type=%d", connfd, + file_type); + goto async_err; + } + + while (count-- > 0) + { + // write to client fd + if ((num = + nsfw_base_send(connfd, buffer, buflen, MSG_NOSIGNAL)) == buflen) + { + break; + } + else if (num <= 0) + { + if (num == 0 || ((errno != EAGAIN) && (errno != EINTR))) + { + NS_PTHREADLOG(file_type, NSLOG_ERR, + "async log module fail, domain socket close]g_nstack_log_client_fd[%d]=%d,num=%d,errno=%d", + file_type, connfd, num, errno); + (void) nsfw_base_close(connfd); + g_nstack_log_client_fd[file_type] = -1; + goto async_err; + } + } + else + { + break; + } + } + + return 0; + + async_err: + NS_PTHREADLOG(file_type, NSLOG_ERR, + "current process will turn DIO synchron log module]buflen=%zu,buffer=%s", + buflen, buffer); + log_asyn_inited = FALSE; + + return -1; +} + +/***************************************************************************** +* Prototype : nstack_log_level_valid +* Description : check if the level is valid. +* Input : uint32_t level +* ... +* Output : None +* Return Value : TRUE means success, FALSE means fail +* Calls : +* Called By : +*****************************************************************************/ +bool nstack_log_level_valid(uint32_t level) +{ + switch (level) + { + case NSLOG_CUS: + case NSLOG_DBG: + case NSLOG_INF: + case NSLOG_WAR: + case NSLOG_ERR: + case NSLOG_EMG: + break; + default: + return FALSE; + } + return TRUE; +} + +/***************************************************************************** +* Prototype : save_pre_init_log +* Description : save the pre init log for nstack as the log module still +* be unavailable. +* Input : uint32_t level +* : char *fmt +* ... +* Output : None +* Return Value : void +* Calls : +* Called By : +*****************************************************************************/ + +/* change the print level, not only has err */ +void save_pre_init_log(uint32_t level, char *fmt, ...) +{ + va_list ap; + int ret = 0; + /*add pre_init_log_count rang check */ + if (!nstack_log_level_valid(level) + || pre_init_log_count >= MAX_PRE_INIT_LOG_COUNT + || pre_init_log_count < 0) + { + return; + } + + pre_init_log[pre_init_log_count].log_buffer[PRE_INIT_LOG_LENGTH - 1] = + '\0'; + + (void) va_start(ap, fmt); /*keep behavior same with C00,and it won't any effect here */ + ret = + vsnprintf_s(pre_init_log[pre_init_log_count].log_buffer, + PRE_INIT_LOG_LENGTH, PRE_INIT_LOG_LENGTH - 1, fmt, ap); + if (-1 == ret) + { + va_end(ap); + return; + } + va_end(ap); + pre_init_log[pre_init_log_count].level = level; + pre_init_log_count++; + return; +} + +/***************************************************************************** +* Prototype : get_pre_init_log_count +* Description : get the count value of the pre log record. +* Input : None +* ... +* Output : log count num +* Return Value : nonnegative number +* Calls : +* Called By : +*****************************************************************************/ +int get_pre_init_log_count() +{ + int count = pre_init_log_count; + if ((count < 0) || (count >= MAX_PRE_INIT_LOG_COUNT)) + { + return 0; + } + return count; +} + +/***************************************************************************** +* Prototype : get_pre_init_log_buffer +* Description : get the stored log content of the pre log, the content will +* copy to the input parameter array for print. +* Input : struct pre_init_info pre_buf[] +* : uint32_t size +* ... +* Output : None +* Return Value : 0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +int get_pre_init_log_buffer(struct pre_init_info *pre_buf, uint32_t size) +{ + int ret = -1; + size_t array_size = sizeof(struct pre_init_info) * size; + if (NULL == pre_buf || size > MAX_PRE_INIT_LOG_COUNT + || (sizeof(pre_init_log) != array_size)) + { + return -1; + } + + ret = memcpy_s(pre_buf, array_size, pre_init_log, array_size); + if (EOK != ret) + { + return -1; + } + return 0; +} + +/***************************************************************************** +* Prototype : get_level_desc +* Description : get the first letter as the level. +* Input : uint32_t level +* ... +* Output : first letter of the level +* Return Value : char * +* Calls : +* Called By : +*****************************************************************************/ +char *get_level_desc(uint32_t level) +{ + switch (level) + { + case NSLOG_DBG: + return "D"; + case NSLOG_INF: + return "I"; + case NSLOG_WAR: + return "W"; + case NSLOG_ERR: + return "E"; + case NSLOG_EMG: + /* PDT use fatal, so here use F */ + return "F"; + default: + return "E"; + } +} + +/***************************************************************************** +* Prototype : nstack_log_get_prefix +* Description : assemble the log prefix content, the content contain the level +* first letter, and timestamp +* Input : uint32_t level +* : char *buffer +* : uint32_t length +* ... +* Output : buffer store the pre_log +* Return Value : >=0 means success, -1 means fail. +* Calls : +* Called By : +*****************************************************************************/ +int nstack_log_get_prefix(uint32_t level, char *buffer, uint32_t length) +{ + if ((NULL == buffer) || length == 0) + { + return -1; + } + + int ret = -1; + char *level_str = "E"; + struct timeval t_val; + struct tm now_time; + + /* limit log file size and log file count- Begin */ + /*gettimeofday is not change to clock_gettime as this is for log and gettimeofday only + makes sense here */ + (void) gettimeofday(&t_val, NULL); + time_t t_sec = (time_t) t_val.tv_sec; + (void) gmtime_r(&t_sec, &now_time); + + level_str = get_level_desc(level); + + /* There are some unsafe function ,need to be replace with safe function */ + /* modify %02d:%02d:%02d:%06ld:%s to "%02d:%02d:%02d.%06ld %s" */ + ret = sprintf_s(buffer, length, "%s%02d%02d %02d:%02d:%02d.%06ld", + level_str, 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 == ret) + { + return -1; + } + + return ret; + +} + +/***************************************************************************** +* Prototype : nstack_log_print_buffer +* Description : get the log prefix content, and assemble the log with format, +* then use glog print direct, as in a single thread, no block. +* Input : uint32_t file_type +* : uint32_t level +* : const char *format +* ... +* Output : NA +* Return Value : void +* Calls : +* Called By : nstack_log_server_process +*****************************************************************************/ +void nstack_log_print_buffer(uint32_t log_type, uint32_t level, + const char *format, ...) +{ + if (NULL == format) + { + return; + } + + va_list ap; + int ret; + char pre_buffer[PRE_INIT_LOG_LENGTH] = { 0 }; + char buffer[MAX_BUFFER_LEN] = { 0 }; + char format_buffer[MAX_BUFFER_LEN] = { 0 }; + + ret = nstack_log_get_prefix(level, pre_buffer, sizeof(pre_buffer)); + if (ret < 0) + { + return; + } + + ret = + sprintf_s(format_buffer, sizeof(format_buffer), "%s %s", pre_buffer, + format); + if (ret < 0) + { + return; + } + + va_start(ap, format); /*no need to check return */ + ret = vsprintf_s(buffer, sizeof(buffer), format_buffer, ap); + if (-1 == ret) + { + va_end(ap); + return; + } + va_end(ap); + + buffer[sizeof(buffer) - 1] = '\0'; + + // print the buf + glog_print_buffer(log_type, buffer, ret); + + return; +} diff --git a/src/framework/log/nstack_log_async.h b/src/framework/log/nstack_log_async.h new file mode 100644 index 0000000..1ae1865 --- /dev/null +++ b/src/framework/log/nstack_log_async.h @@ -0,0 +1,93 @@ +/* +* +* 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_LOG_SOCK_H_ +#define _NSTACK_LOG_SOCK_H_ + +#include <sys/types.h> +#include <unistd.h> +#include <sys/time.h> +#include <sys/syscall.h> +#include <time.h> +#include <errno.h> +#include "types.h" +#include "nstack_log.h" + +#define PRE_INIT_LOG_LENGTH 128 +#define MAX_PRE_INIT_LOG_COUNT 256 +#define MAX_BUFFER_LEN 2048 //buffer len for the domain socket recv + +//Note: need match with _NLOG_TYPE in glog +enum _LOG_TYPE +{ + LOG_TYPE_NSTACK = 0, + LOG_TYPE_OPERATION, + LOG_TYPE_MASTER, + LOG_TYPE_CTRL, + LOG_TYPE_SEGMENT, + LOG_TYPE_APP, + LOG_TYPE_UNRECOGNIZED, + MAX_LOG_TYPE +}; + +/*change the print level, not only has err*/ + +struct pre_init_info +{ + uint32_t level; /**< Log level. */ + char log_buffer[PRE_INIT_LOG_LENGTH]; +}; + +extern __thread unsigned int pre_log_nonreentry; + +/*change the log type check*/ +#define pre_log_shooting(_type,_level) \ + (((_type >= MAX_LOG_TYPE) || (g_nstack_logs[LOGASYNC].level < _level) || (!nstack_log_level_valid(_level))) ? FALSE: TRUE) + +#define NS_PTHREADLOG(_type,_level,fmt, ...) \ +{\ + if (pre_log_shooting(_type, _level) && (0 == pre_log_nonreentry))\ + {\ + pre_log_nonreentry = 1;\ + nstack_log_print_buffer(_type, _level, \ + "%d %s:%d] %d,%s <NSTHREAD>" fmt "\r\n", (int)syscall(SYS_gettid), GET_FILE_NAME(__FILE__), \ + __LINE__, getpid(),__func__, ##__VA_ARGS__);\ + pre_log_nonreentry = 0;\ + }\ +} + +int nstack_log_server_init(int proc_type); + +int nstack_log_client_init(int proc_type); + +int nstack_log_client_send(int file_type, char *buffer, size_t buflen); + +int nstack_log_server_flush(int proc_type, unsigned long long timeout); + +bool nstack_log_level_valid(uint32_t level); + +int get_pre_init_log_count(); + +int get_pre_init_log_buffer(struct pre_init_info *pre_buf, uint32_t size); + +char *get_level_desc(uint32_t level); + +int nstack_log_get_prefix(uint32_t level, char *buffer, uint32_t length); + +void nstack_log_print_buffer(uint32_t log_type, uint32_t level, + const char *format, ...); + +#endif /*_NSTACK_LOG_SOCK_H_*/ diff --git a/src/framework/log/nstack_log_auto_suppress.c b/src/framework/log/nstack_log_auto_suppress.c new file mode 100644 index 0000000..4296b47 --- /dev/null +++ b/src/framework/log/nstack_log_auto_suppress.c @@ -0,0 +1,376 @@ +/* +* +* 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 "nsfw_init_api.h" +#include "nstack_log_async.h" +#include "nstack_log_auto_suppress.h" +#include "nsfw_fd_timer_api.h" +#include "nsfw_mgr_com_api.h" +#include "nstack_securec.h" +#include <unistd.h> +#include "nstack_log_auto_suppress_rb_tree.h" + +/*==============================================* + * project-wide global variables * + *----------------------------------------------*/ +__thread log_sup_table gt_log_sup_table = { 0 }; +NSTACK_STATIC log_sup_summary g_log_sup_summary = { {0, 0, 0, 0, 0, 0, 0, 0} +, 0, 0 +}; + +NSTACK_STATIC u32 g_log_sup_thresh = LOG_SUP_THRESH_DEFAULT; + +/*==============================================* + * routines' or functions' implementations * + *----------------------------------------------*/ +inline bool is_log_sup_switched_off(const u8 module) +{ + return ((MAX_LOG_MODULE > module) && g_nstack_logs[module].suppress_off); +} + +inline log_sup_table *get_log_sup_table_addr() +{ + return >_log_sup_table; +} + +inline int log_entry_cmp(const log_entry * left, const log_entry * right) +{ + u64 key_left = GET_TAG_FROM_FILE_AND_LINE(left->file, left->line); + u64 key_right = GET_TAG_FROM_FILE_AND_LINE(right->file, right->line); + + if (key_left > key_right) + { + return 1; + } + else if (key_left < key_right) + { + return -1; + } + else + { + return 0; + } +} + +/* CAUTION: Only given the limited scenario in regard of `gt_log_sup_table` can we simplify the malloc/free mechanism like below. + * 1. `gt_log_sup_table` is thread-independent; + * 2. there are only 2 possible malloc scenario: + * (a) when table is not full, create a new node; + * (b) when table is full, add a node right after deleting the old one, so we just take its place */ +log_sup_node *malloc_one_node() +{ + if (gt_log_sup_table.count >= gt_log_sup_table.size) + { + /* full or uninited, don't print log here */ + return NULL; + } + log_sup_node *node; + if (gt_log_sup_table.just_been_freed) + { + /* when table is full, add a node right after deleting the old one, so we just take its place */ + node = gt_log_sup_table.just_been_freed; + } + else + { + /* when table is not full, create a new node */ + node = gt_log_sup_table.nodepool + gt_log_sup_table.count; + } + gt_log_sup_table.count++; + + return node; +} + +void free_one_node(log_sup_node * node) +{ + gt_log_sup_table.just_been_freed = node; /* mark the place */ + gt_log_sup_table.count--; +} + +/* CAUTION: log printing can be used in this function ONLY when we have confirmed that + * gt_log_sup_table is initialized, whether successfully or not. */ +log_sup_table *init_sup_table(int table_size) +{ + /* Prevent `g_log_sup_thresh` from being optimized out, so that we can enforce it by gdb. Not needed in UT */ + g_log_sup_thresh = LOG_SUP_THRESH_DEFAULT; + gt_log_sup_table.root = NULL; + gt_log_sup_table.nodepool = NULL; + gt_log_sup_table.just_been_freed = NULL; + gt_log_sup_table.size = 0; + gt_log_sup_table.count = 0; + + if (table_size <= 0 || table_size > LOG_SUP_TABLE_SIZE_UPPER_LIMIT) + { + NSFW_LOGERR("invalid gt_log_sup_table size=%d!", table_size); + return NULL; + } + + gt_log_sup_table.nodepool = + (log_sup_node *) malloc(table_size * sizeof(log_sup_node)); + if (NULL == gt_log_sup_table.nodepool) + { + NSFW_LOGERR("malloc gt_log_sup_table failed!"); + return NULL; + } + + int ret = memset_s(gt_log_sup_table.nodepool, + (table_size * sizeof(log_sup_node)), 0, + (table_size * sizeof(log_sup_node))); + if (EOK != ret) + { + free(gt_log_sup_table.nodepool); + gt_log_sup_table.nodepool = NULL; + NSFW_LOGERR("memset_s gt_log_sup_table failed! ret=%d", ret); + return NULL; + } + + int dlc = 10000; + + while (!__sync_bool_compare_and_swap(&g_log_sup_summary.lock, 0, 1)) //LOCK + { + if (--dlc == 0) + { + free(gt_log_sup_table.nodepool); + gt_log_sup_table.nodepool = NULL; + NSFW_LOGERR("can't get the lock of g_log_sup_summary"); + return NULL; + } + /* use nanosleep() instead of usleep() */ + struct timespec delay; + delay.tv_sec = 0; + delay.tv_nsec = 10000; + (void) nanosleep(&delay, NULL); /* don't care for precission, so no need to check return value or output param */ + } + if (g_log_sup_summary.table_cnt < MAX_NUM_OF_LOG_SUP_TABLE) + { + g_log_sup_summary.tables[g_log_sup_summary.table_cnt] = + >_log_sup_table; + g_log_sup_summary.table_cnt++; + g_log_sup_summary.lock = 0; //UNLOCK + } + else + { + free(gt_log_sup_table.nodepool); + gt_log_sup_table.nodepool = NULL; + g_log_sup_summary.lock = 0; //UNLOCK + NSFW_LOGERR("g_log_sup_summary is full"); + return NULL; + } + + gt_log_sup_table.size = table_size; + NSFW_LOGINF("init gt_log_sup_table succ]nodepool=%p", + gt_log_sup_table.nodepool); + return >_log_sup_table; +} + +/* Mid-layer for datastruture methods. DO NOT print log in these functions - Begin */ +NSTACK_STATIC inline log_sup_node *_log_sup_search(const log_entry * entry, + log_sup_table * table) +{ + return __log_sup_rb_search(entry, table->root); +} + +NSTACK_STATIC inline void _log_sup_erase(log_sup_node * node, + log_sup_table * table) +{ + return __log_sup_rb_erase(node, &(table->root)); +} + +NSTACK_STATIC inline log_sup_node *_log_sup_insert(log_entry * entry, + log_sup_table * table) +{ + return __log_sup_rb_insert(entry, &(table->root)); +} + +/* Mid-layer for datastruture methods. DO NOT print log in these functions - End */ + +static inline int is_node_to_delete(log_entry * entry) +{ + return !ISSET_BITS(entry->ctrl_bits, CTRL_BIT__KEEP); +} + +bool update_sup_table_on_logging(const char *file, const u16 line, + const u8 log_type, const u16 level, + log_sup_table * table, u32 * dup_cnt) +{ + log_entry ent; + ent.ctrl_bits = 0; + ent.level = level; + ent.log_type = log_type; + ent.last_epoch_dup_cnt = 0; + ent.file = file; + ent.line = line; + + if (NULL == table->nodepool) ///not inited, abort + { + return FALSE; + } + + log_sup_node *node = _log_sup_search(&ent, table); + if (NULL == node) //no match found, insert one + { + if (NULL == (node = _log_sup_insert(&ent, table))) //table is full, try to replace + { + log_sup_node *node2del = NULL; + int recur_cnt = table->size; + __log_sup_rb_traversal_preorder(table->root, is_node_to_delete, + &node2del, &recur_cnt); + if (node2del) + { + _log_sup_erase(node2del, table); + node = _log_sup_insert(&ent, table); + if (NULL == node) + { + /* should never happen */ + return FALSE; /* The conservative choice is not to suppress */ + } + } + else + { + /* No entry can be replaced, should happen very rarely */ + return FALSE; + } + } + } + + /* ASSERT: node != NULL when reaching here */ + node->entry.last_epoch_dup_cnt++; + if (dup_cnt) /* can be NULL */ + { + *dup_cnt = node->entry.last_epoch_dup_cnt; + } + SET_BITS(node->entry.ctrl_bits, CTRL_BIT__KEEP); + if (node->entry.last_epoch_dup_cnt > g_log_sup_thresh) + { + SET_BITS(node->entry.ctrl_bits, CTRL_BIT__SUPPRESSED); + } + return ISSET_BITS(node->entry.ctrl_bits, CTRL_BIT__SUPPRESSED); +} + +static inline void print_suppressed_log(log_entry * entry) +{ + if (ISSET_BITS(entry->ctrl_bits, CTRL_BIT__SUPPRESSED)) + { + u16 _level = entry->level; + u8 _module = entry->log_type; + + if (entry->last_epoch_dup_cnt > g_log_sup_thresh) + { + NS_LOGPID(_module, "SUP", _level, "%s:%u repeated %u times", + GET_FILE_NAME(entry->file), entry->line, + entry->last_epoch_dup_cnt); + } + else + { + NS_LOGPID(_module, "SUP", _level, + "%s:%u repeated %u times (may release)", + GET_FILE_NAME(entry->file), entry->line, + entry->last_epoch_dup_cnt); + } + + } +} + +static inline void update_log_sup_ctrl(log_entry * entry) +{ + if (entry->last_epoch_dup_cnt > g_log_sup_thresh) + { + SET_BITS(entry->ctrl_bits, (CTRL_BIT__SUPPRESSED | CTRL_BIT__KEEP)); + } + else + { + CLR_BITS(entry->ctrl_bits, (CTRL_BIT__SUPPRESSED | CTRL_BIT__KEEP)); + } + entry->last_epoch_dup_cnt = 0; +} + +static inline int print_update_sup_entry(log_entry * entry) +{ + print_suppressed_log(entry); + update_log_sup_ctrl(entry); + return 0; +} + +void update_sup_table_on_timer(void) +{ + int i; + for (i = 0; i < g_log_sup_summary.table_cnt; i++) + { + log_sup_table *table = g_log_sup_summary.tables[i]; + int recur_cnt = table->size; + __log_sup_rb_traversal_preorder(table->root, print_update_sup_entry, + NULL, &recur_cnt); + } +} + +int nsfw_log_sup_timeout(u32 timer_type, void *data) +{ + update_sup_table_on_timer(); + struct timespec time_left = { 1, 0 }; + void *ptr = (void *) nsfw_timer_reg_timer(777, NULL, nsfw_log_sup_timeout, + time_left); + if (!ptr) + { + NSFW_LOGERR("re-register log_sup_timer fail!"); + return FALSE; + } + return TRUE; +} + +int nsfw_log_sup_module_init(void *param) +{ + u32 proc_type = (u32) ((long long) param); + int table_size; + + switch (proc_type) + { + case NSFW_PROC_MASTER: + table_size = LOG_SUP_TABLE_SIZE_FOR_MASTER; + break; + case NSFW_PROC_MAIN: + table_size = LOG_SUP_TABLE_SIZE_FOR_MAIN; + break; + default: + return 0; + } + + /* Init log suppression for this thread */ + if (NULL == init_sup_table(table_size)) + { + NSFW_LOGWAR("log suppression init failed in main thread"); + } + + struct timespec time_left = { 1, 0 }; + void *ptr = (void *) nsfw_timer_reg_timer(777, NULL, nsfw_log_sup_timeout, + time_left); + if (!ptr) + { + NSFW_LOGERR("init log_sup_timer fail!"); + return -1; + } + + NSFW_LOGINF("init log_sup_module succ"); + return 0; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_LOG_SUP_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_DEPENDS(NSFW_TIMER_MODULE) +NSFW_MODULE_INIT(nsfw_log_sup_module_init) +/* *INDENT-ON* */ diff --git a/src/framework/log/nstack_log_auto_suppress.h b/src/framework/log/nstack_log_auto_suppress.h new file mode 100644 index 0000000..0c59172 --- /dev/null +++ b/src/framework/log/nstack_log_auto_suppress.h @@ -0,0 +1,67 @@ +/* +* +* 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_LOG_SUPPRESS_H_ +#define _NSTACK_LOG_SUPPRESS_H_ + +#include "types.h" +#include "nstack_log.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#define NSFW_LOG_SUP_MODULE "nsfw_log_sup" + +#define CTRL_BIT__SUPPRESSED (1 << 0) +#define CTRL_BIT__KEEP (1 << 1) + +/* The threshold must be larger than the size of log_sup_table, otherwise the suppress report itself may be suppressed */ +#define LOG_SUP_THRESH_DEFAULT 8192 + +/* Must be larger than the number of threads in non-App processes */ +#define MAX_NUM_OF_LOG_SUP_TABLE 8 + +#define SET_BITS(x,bits) (x)|=(bits) +#define CLR_BITS(x,bits) (x)&=~(bits) +#define ISSET_BITS(x,bits) ((x)&(bits)) + +#define GET_TAG_FROM_FILE_AND_LINE(_file,_line) \ + (u64)(((u64)(_file) & 0x00FFFFFFFFFFFFFF) | ((u64)(_line) << 48)) + +typedef struct _log_sup_summary +{ + log_sup_table *tables[MAX_NUM_OF_LOG_SUP_TABLE]; + int table_cnt; + volatile int lock; +} log_sup_summary; + +extern __thread log_sup_table gt_log_sup_table; + +inline int log_entry_cmp(const log_entry * left, const log_entry * right); +log_sup_node *malloc_one_node(); +void free_one_node(log_sup_node * node); +void update_sup_table_on_timer(void); + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#endif diff --git a/src/framework/log/nstack_log_auto_suppress_rb_tree.c b/src/framework/log/nstack_log_auto_suppress_rb_tree.c new file mode 100644 index 0000000..d067cca --- /dev/null +++ b/src/framework/log/nstack_log_auto_suppress_rb_tree.c @@ -0,0 +1,506 @@ +/* +* +* 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 "nstack_log_auto_suppress.h" +#include "nstack_log_auto_suppress_rb_tree.h" + +#define RB_RED 0 +#define RB_BLACK 1 + +NSTACK_STATIC void ___RB_rotate_left(log_sup_node * X, log_sup_node ** root) +{ + /************************** + * rotate Node X to left * + **************************/ + + log_sup_node *Y = X->rb_right; + + /* estblish X->Right link */ + X->rb_right = Y->rb_left; + if (Y->rb_left != NULL) + Y->rb_left->rb_parent = X; + + /* estblish Y->Parent link */ + Y->rb_parent = X->rb_parent; + if (X->rb_parent) + { + if (X == X->rb_parent->rb_left) + X->rb_parent->rb_left = Y; + else + X->rb_parent->rb_right = Y; + } + else + { + *root = Y; + } + + /* link X and Y */ + Y->rb_left = X; + X->rb_parent = Y; + + return; +} + +NSTACK_STATIC void ___RB_rotate_right(log_sup_node * X, log_sup_node ** root) +{ + /**************************** + * rotate Node X to right * + ****************************/ + + log_sup_node *Y = X->rb_left; + + /* estblish X->Left link */ + X->rb_left = Y->rb_right; + if (Y->rb_right != NULL) + Y->rb_right->rb_parent = X; + + /* estblish Y->Parent link */ + Y->rb_parent = X->rb_parent; + if (X->rb_parent) + { + if (X == X->rb_parent->rb_right) + X->rb_parent->rb_right = Y; + else + X->rb_parent->rb_left = Y; + } + else + { + *root = Y; + } + + /* link X and Y */ + Y->rb_right = X; + X->rb_parent = Y; + + return; +} + +static inline int ___RB_is_color(log_sup_node * node, int color) +{ + return (!node || node->color == color); +} + +static inline void ___RB_set_color(log_sup_node * node, int color) +{ + if (node != NULL) + { + node->color = color; + } +} + +/* Oops... What's the proper name? */ +static inline void ___RB_adjust(log_sup_node * X, log_sup_node ** root, + log_sup_node * node) +{ + log_sup_node *Parent = node->rb_parent; + if (Parent) + { + if (Parent->rb_left == node) + { + Parent->rb_left = X; + } + else + { + Parent->rb_right = X; + } + } + else + { + *root = X; + } +} + +/* X, Y are for application */ +NSTACK_STATIC void ___RB_erase_color(log_sup_node * X, log_sup_node * Parent, + log_sup_node ** root) +{ + /************************************* + * maintain red-black tree balance * + * after deleting node X * + *************************************/ + + while (X != *root && ___RB_is_color(X, RB_BLACK)) + { + + if (Parent == NULL) + { + break; + } + + if (X == Parent->rb_left) + { + log_sup_node *W = Parent->rb_right; + if (W->color == RB_RED) + { + W->color = RB_BLACK; + Parent->color = RB_RED; /* Parent != NIL? */ + ___RB_rotate_left(Parent, root); + W = Parent->rb_right; + } + + if (___RB_is_color(W->rb_left, RB_BLACK) + && ___RB_is_color(W->rb_right, RB_BLACK)) + { + W->color = RB_RED; + X = Parent; + Parent = X->rb_parent; + } + else + { + if (___RB_is_color(W->rb_right, RB_BLACK)) + { + ___RB_set_color(W->rb_left, RB_BLACK); + W->color = RB_RED; + ___RB_rotate_right(W, root); + W = Parent->rb_right; + } + + W->color = Parent->color; + Parent->color = RB_BLACK; + if (W->rb_right->color != RB_BLACK) + { + W->rb_right->color = RB_BLACK; + } + ___RB_rotate_left(Parent, root); + X = *root; + break; + } + } + else + { + + log_sup_node *W = Parent->rb_left; + if (W->color == RB_RED) + { + W->color = RB_BLACK; + Parent->color = RB_RED; /* Parent != NIL? */ + ___RB_rotate_right(Parent, root); + W = Parent->rb_left; + } + + if (___RB_is_color(W->rb_left, RB_BLACK) + && ___RB_is_color(W->rb_right, RB_BLACK)) + { + W->color = RB_RED; + X = Parent; + Parent = X->rb_parent; + } + else + { + if (___RB_is_color(W->rb_left, RB_BLACK)) + { + ___RB_set_color(W->rb_right, RB_BLACK); + W->color = RB_RED; + ___RB_rotate_left(W, root); + W = Parent->rb_left; + } + + W->color = Parent->color; + Parent->color = RB_BLACK; + if (W->rb_left->color != RB_BLACK) + { + W->rb_left->color = RB_BLACK; + } + ___RB_rotate_right(Parent, root); + X = *root; + break; + } + } + } + + if (X) + { + X->color = RB_BLACK; + } + + return; +} + +static void ___RB_insert_color(log_sup_node * X, log_sup_node ** root) +{ + /************************************* + * maintain red-black tree balance * + * after inserting node X * + *************************************/ + + /* check red-black properties */ + while (X != *root && X->rb_parent->color == RB_RED) + { + /* we have a violation */ + if (X->rb_parent == X->rb_parent->rb_parent->rb_left) + { + log_sup_node *Y = X->rb_parent->rb_parent->rb_right; + if (!___RB_is_color(Y, RB_BLACK)) + { + + /* uncle is red */ + X->rb_parent->color = RB_BLACK; + Y->color = RB_BLACK; + X->rb_parent->rb_parent->color = RB_RED; + X = X->rb_parent->rb_parent; + } + else + { + + /* uncle is black */ + if (X == X->rb_parent->rb_right) + { + /* make X a left child */ + X = X->rb_parent; + ___RB_rotate_left(X, root); + } + + /* recolor and rotate */ + X->rb_parent->color = RB_BLACK; + X->rb_parent->rb_parent->color = RB_RED; + ___RB_rotate_right(X->rb_parent->rb_parent, root); + } + } + else + { + + /* miror image of above code */ + log_sup_node *Y = X->rb_parent->rb_parent->rb_left; + if (!___RB_is_color(Y, RB_BLACK)) + { + + /* uncle is red */ + X->rb_parent->color = RB_BLACK; + Y->color = RB_BLACK; + X->rb_parent->rb_parent->color = RB_RED; + X = X->rb_parent->rb_parent; + } + else + { + + /* uncle is black */ + if (X == X->rb_parent->rb_left) + { + X = X->rb_parent; + ___RB_rotate_right(X, root); + } + X->rb_parent->color = RB_BLACK; + X->rb_parent->rb_parent->color = RB_RED; + ___RB_rotate_left(X->rb_parent->rb_parent, root); + } + } + } + + (*root)->color = RB_BLACK; + + return; +} + +static void ___RB_erase(log_sup_node * node, log_sup_node ** root) +{ + log_sup_node *child, *parent; + bool color; + + if (!node->rb_left) + { + child = node->rb_right; + } + else if (!node->rb_right) + { + child = node->rb_left; + } + else + { + log_sup_node *old = node, *left; + + node = node->rb_right; + while ((left = node->rb_left) != NULL) + { + node = left; + } + + ___RB_adjust(node, root, old); + + child = node->rb_right; + parent = node->rb_parent; + color = node->color; + + if (parent == old) + { + parent = node; + } + else + { + if (child) + { + child->rb_parent = parent; + } + + parent->rb_left = child; + + node->rb_right = old->rb_right; + old->rb_right->rb_parent = node; + } + + node->color = old->color; + node->rb_parent = old->rb_parent; + node->rb_left = old->rb_left; + old->rb_left->rb_parent = node; + + if (color == RB_BLACK) + { + ___RB_erase_color(child, parent, root); + } + + return; + + } + + parent = node->rb_parent; + color = node->color; + + if (child) + { + child->rb_parent = parent; + } + + ___RB_adjust(child, root, node); + + if (color == RB_BLACK) + { + ___RB_erase_color(child, parent, root); + } + + return; +} + +inline log_sup_node *__log_sup_rb_insert(log_entry * entry, + log_sup_node ** root) +{ + log_sup_node *node = *root; + log_sup_node *parent = NULL; + int ret = 0; + while (node) + { + parent = node; + ret = log_entry_cmp(&node->entry, entry); + if (0 < ret) + { + node = node->rb_left; + } + else if (0 > ret) + { + node = node->rb_right; + } + else + { + return NULL; + } + } + + node = malloc_one_node(); + if (!node) + { + return NULL; + } + node->entry = *entry; //copy the content, not the ptr + node->rb_parent = parent; + node->rb_left = node->rb_right = NULL; + node->color = RB_RED; + + if (parent) + { + if (ret > 0) + { + parent->rb_left = node; + } + else + { + parent->rb_right = node; + } + } + else + { + *root = node; + } + + ___RB_insert_color(node, root); + return node; +} + +inline log_sup_node *__log_sup_rb_search(const log_entry * entry, + log_sup_node * root) +{ + log_sup_node *node = root; + int ret; + while (node) + { + ret = log_entry_cmp(&node->entry, entry); + if (0 < ret) + { + node = node->rb_left; + } + else if (0 > ret) + { + node = node->rb_right; + } + else + { + return node; + } + } + + return NULL; +} + +inline void __log_sup_rb_erase(log_sup_node * node, log_sup_node ** root) +{ + ___RB_erase(node, root); + free_one_node(node); +} + +void __log_sup_rb_traversal_preorder(log_sup_node * root, + log_entry_worker_fn foo, + log_sup_node ** resnode, int *recur_cnt) +{ + /* avoid infinite recursion or empty tree */ + if (!recur_cnt || (0 > *recur_cnt) || !root) + { + return; + } + + /* NOTE: recur_cnt decreases along with foo call and does not bounce back, + * so it should be the numbur of nodes, not the depth */ + (*recur_cnt)--; + + int ret = foo(&(root->entry)); + if (0 != ret) + { + if (resnode) + { + *recur_cnt = 0; /* immediate return */ + *resnode = root; + } + return; + } + + if ((root->rb_left) != NULL) + { + __log_sup_rb_traversal_preorder(root->rb_left, foo, resnode, + recur_cnt); + } + if ((root->rb_right) != NULL) + { + __log_sup_rb_traversal_preorder(root->rb_right, foo, resnode, + recur_cnt); + } +} diff --git a/src/framework/log/nstack_log_auto_suppress_rb_tree.h b/src/framework/log/nstack_log_auto_suppress_rb_tree.h new file mode 100644 index 0000000..628c466 --- /dev/null +++ b/src/framework/log/nstack_log_auto_suppress_rb_tree.h @@ -0,0 +1,37 @@ +/* +* +* 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_LOG_SUPPRESS_RB_TREE_H_ +#define _NSTACK_LOG_SUPPRESS_RB_TREE_H_ + +#include "nstack_log.h" + +typedef int (*log_entry_worker_fn) (log_entry * entry); +typedef int (*log_entry_cpmpare_fn) (const log_entry * left, + const log_entry * right); + +log_sup_node *__log_sup_rb_insert(log_entry * entry, log_sup_node ** root); + +log_sup_node *__log_sup_rb_search(const log_entry * entry, + log_sup_node * root); + +void __log_sup_rb_erase(log_sup_node * node, log_sup_node ** root); + +void __log_sup_rb_traversal_preorder(log_sup_node * root, + log_entry_worker_fn foo, + log_sup_node ** resnode, int *recur_cnt); + +#endif diff --git a/src/framework/log/nstack_log_base.h b/src/framework/log/nstack_log_base.h new file mode 100644 index 0000000..d43c98e --- /dev/null +++ b/src/framework/log/nstack_log_base.h @@ -0,0 +1,97 @@ +/* +* +* 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_LOG_BASE_H_ +#define _NSTACK_LOG_BASE_H_ + +#include "types.h" +#include "nstack_log.h" + +#define LOG_LEVEL_EMG "emg" +#define LOG_LEVEL_ERR "err" +#define LOG_LEVEL_WAR "war" +#define LOG_LEVEL_DBG "dbg" +#define LOG_LEVEL_INF "inf" + +#define STACKPOOL_LOG_NAME "running.log" + +#define OPERATION_LOG_NAME "operation.log" + +#define MASTER_LOG_NAME "master.log" + +#define OMC_CTRL_LOG_NAME "omc_ctrl.log" + +#define FAILURE_LOG_NAME "fail_dump.log" + +#define FLUSH_TIME 30 + +#define APP_LOG_SIZE 30 +#define APP_LOG_COUNT 10 +#define APP_LOG_PATH "/var/log" +#define APP_LOG_NAME "nStack_nSocket.log" + +struct log_ctrl_info +{ + u32 expire_time; + u32 unprint_count; + struct timespec last_log_time; +}; + +/* NS_LOG_CTRL use to inhibit the repeated log*/ +/* add the non reentry protection */ +extern __thread unsigned int nstack_log_nonreentry; + +/* if buf can't load more data(in other words, sprintf_s return -1 and set buf[pos]='\0'), + print the existing data, and once more try to load the data, to the beginning of the buffer, + if still failed, return -1.*/ +#define NSDFX_CACHE_RETURN(pos, buf, buflen, fmt, ...) do { \ + int cache_ret = 0; \ + if ((pos) < (buflen)) { \ + cache_ret = sprintf_s((buf) + (pos), (buflen) - (pos), fmt, ##__VA_ARGS__); \ + if (-1 == cache_ret) { \ + NSDFX_LOGINF("%s", (buf)); \ + (pos) = 0; \ + cache_ret = sprintf_s((buf), (buflen), fmt, ##__VA_ARGS__); \ + if (-1 == cache_ret){ \ + NSDFX_LOGERR("NSDFX_CACHE_RETURN sprintf_s failed second time"); \ + return -1; \ + } \ + } \ + (pos) += cache_ret; \ + } else { \ + NSDFX_LOGERR("DFX cache buffer overflow!!!!!!"); \ + return -1; \ + } \ +}while(0) + +#define NSDFX_CACHE_FLAG_RETURN(log_flag,pos, buf, buflen, fmt, ...) do { \ + if (log_flag) \ + { \ + NSDFX_CACHE_RETURN(pos, buf, buflen, fmt, ##__VA_ARGS__); \ + } \ +}while(0) + +/* Utilities, placed here for convenience */ +#define STRING_IS_VALID_WITH_LENGTH(str,len) ((str) && (*str) && (strlen(str) < len)) + +#define EACH_OF_2_ITEMS_NOT_NULL(a0,a1) ((a0)&&(a1)) +#define EACH_OF_3_ITEMS_NOT_NULL(a0,a1,a2) ((a0)&&(a1)&&(a2)) +#define EACH_OF_4_ITEMS_NOT_NULL(a0,a1,a2,a3) ((a0)&&(a1)&&(a2)&&(a3)) +#define EACH_OF_5_ITEMS_NOT_NULL(a0,a1,a2,a3,a4) ((a0)&&(a1)&&(a2)&&(a3)&&(a4)) +#define EACH_OF_6_ITEMS_NOT_NULL(a0,a1,a2,a3,a4,a5) ((a0)&&(a1)&&(a2)&&(a3)&&(a4)&&(a5)) +/* Utilities, placed here for convenience */ + +#endif /*_NSTACK_LOG_BASE_H_*/ diff --git a/src/framework/maintain/fw_mt_config.c b/src/framework/maintain/fw_mt_config.c new file mode 100644 index 0000000..27c2ef6 --- /dev/null +++ b/src/framework/maintain/fw_mt_config.c @@ -0,0 +1,78 @@ +/* +* +* 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_maintain_api.h" +#include "nstack_securec.h" + +u32 g_base_cfg_items[MAX_BASE_CFG] = { 0 }; + +u32 g_custom_cfg_items[MAX_CUSTOM_CFG] = { 0 }; + +u32 g_macro_custom_cfg_items[CFG_ITEM_MACRO_CUSTOM_MAX] = { 0 }; + +struct cfg_item_info g_cfg_item_info[CFG_SEG_MAX][MAX_CFG_ITEM]; + +u32 get_cfg_info(int tag, int item) +{ + return (u32) g_cfg_item_info[tag][item].value; +} + +u32 get_cfg_share_mem_size() +{ + return sizeof(g_base_cfg_items) + sizeof(g_custom_cfg_items) + + sizeof(g_macro_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; + } + + char *macro_cfg_mem = custom_cfg_mem + sizeof(g_custom_cfg_items); + if (EOK != + memcpy_s(g_macro_custom_cfg_items, sizeof(g_macro_custom_cfg_items), + macro_cfg_mem, sizeof(g_macro_custom_cfg_items))) + { + return -1; + } + + return 0; +} + +void get_default_base_cfg(u32 thread_num) +{ + g_base_cfg_items[CFG_BASE_THREAD_NUM] = thread_num; + 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] = 1024; + g_base_cfg_items[CFG_BASE_ARP_STALE_TIME] = DEF_ARP_STACLE_TIME; + g_base_cfg_items[CFG_BASE_ARP_BC_RETRANS_NUM] = DEF_ARP_BC_RETRANS_NUM; + + return; +} diff --git a/src/framework/maintain/nsfw_lock_file.c b/src/framework/maintain/nsfw_lock_file.c new file mode 100644 index 0000000..289bdde --- /dev/null +++ b/src/framework/maintain/nsfw_lock_file.c @@ -0,0 +1,174 @@ +/* +* +* 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 <errno.h> +#include <fcntl.h> +#include <unistd.h> + +#include "types.h" +#include "nstack_securec.h" +#include "nsfw_init_api.h" + +#include "nsfw_base_linux_api.h" +#include "nstack_log.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mgr_com_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#define NSFW_FILE_PATH_LEN 128 +#define LOCK_FOLDER "/ip_module/" +#define LOCK_SUFFIX ".pid" + +#define read_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_RDLCK, (offset), (whence), (len)) +#define readw_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len)) +#define write_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_WRLCK, (offset), (whence), (len)) +#define writew_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len)) +#define un_lock(fd, offset, whence, len) nsfw_lock_reg((fd), F_SETLK, F_UNLCK, (offset), (whence), (len)) + +i32 nsfw_lock_reg(i32 fd, i32 cmd, i32 type, off_t offset, i32 whence, + off_t len) +{ + struct flock lock_file; + lock_file.l_type = type; + lock_file.l_start = offset; + lock_file.l_whence = whence; + lock_file.l_len = len; + return (fcntl(fd, cmd, &lock_file)); +} + +/***************************************************************************** +* Prototype : nsfw_proc_start_with_lock +* Description : lock file start +* Input : u8 proc_type +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_proc_start_with_lock(u8 proc_type) +{ + NSFW_LOGINF("lock_file init]type=%u", proc_type); + char *module_name = nsfw_get_proc_name(proc_type); + if (NULL == module_name) + { + NSFW_LOGERR("proc type error]proc_type=%u", proc_type); + return 0; + } + + const char *directory = NSFW_DOMAIN_DIR; + const char *home_dir = get_home_path(); + if (home_dir) + { + directory = home_dir; + } + + int ret = -1; + char lock_fpath[NSFW_FILE_PATH_LEN] = { 0 }; + ret = strcpy_s(lock_fpath, NSFW_FILE_PATH_LEN, directory); + if (EOK != ret) + { + NSFW_LOGERR("lock init strcpy_s failed]ret=%d", ret); + return -1; + } + + ret = strcat_s(lock_fpath, NSFW_FILE_PATH_LEN, LOCK_FOLDER); + if (EOK != ret) + { + NSFW_LOGERR("lock init strcat_s failed]ret=%d", ret); + return -1; + } + + ret = strcat_s(lock_fpath, NSFW_FILE_PATH_LEN, module_name); + if (EOK != ret) + { + NSFW_LOGERR("lock init strcat_s failed]ret=%d", ret); + return -1; + } + + ret = strcat_s(lock_fpath, NSFW_FILE_PATH_LEN, LOCK_SUFFIX); + if (EOK != ret) + { + NSFW_LOGERR("lock init strcat_s failed]ret=%d", ret); + return -1; + } + + i32 fd; + + if ((fd = open(lock_fpath, O_RDWR | O_CREAT, 0640)) == -1) /* file permission no large than 0640 */ + { + NSFW_LOGERR("open lock file error!]path=%s,error = %d", lock_fpath, + errno); + return -1; + } + + /* close on exec */ + int rc = nsfw_set_close_on_exec(fd); + if (rc == -1) + { + (void) nsfw_base_close(fd); + NSFW_LOGERR("set exec err]fd=%d, errno=%d", fd, errno); + return -1; + } + + if (write_lock(fd, 0, SEEK_SET, 0) < 0) + { + (void) nsfw_base_close(fd); + NSFW_LOGERR("get lock file error!]path=%s,error = %d", lock_fpath, + errno); + return -1; + } + + char buf[32] = { 0 }; + if (ftruncate(fd, 0) < 0) + { + (void) nsfw_base_close(fd); + NSFW_LOGERR("ftruncate file error!]path=%s,error = %d", lock_fpath, + errno); + return -1; + } + + ret = + snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%ld", (long) getpid()); + if (-1 == ret) + { + NSTCP_LOGERR("snprintf_s failed]ret=%d", ret); + (void) nsfw_base_close(fd); + return -1; + } + + if (write(fd, buf, strlen(buf)) < 0) + { + (void) nsfw_base_close(fd); + NSFW_LOGERR("write file error!]path=%s,error = %d", lock_fpath, + errno); + return -1; + } +// (void)nsfw_base_close(fd); /*no nee to close fd because its used to lock file*/ + return 0; +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/maintain/nsfw_mem_stat.c b/src/framework/maintain/nsfw_mem_stat.c new file mode 100644 index 0000000..f78f51c --- /dev/null +++ b/src/framework/maintain/nsfw_mem_stat.c @@ -0,0 +1,286 @@ +/* +* +* 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_api.h" + +#include "nstack_log.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mem_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +#define NSFW_MEM_STAT_NUM 512 + +#define NSFW_MEM_STAT_MODULE "nsfw_mem_stat_module" + +typedef struct _nsfw_mem_stat +{ + u8 mem_type; + u8 alloc_flag; + char module[NSFW_MEM_MODULE_LEN]; + char mem_name[NSFW_MEM_NAME_LEN]; + u32 mem_size; +} nsfw_mem_stat_t; + +nsfw_mem_stat_t g_mem_stat[NSFW_MEM_STAT_NUM]; + +#ifdef SYS_MEM_RES_STAT +#define MAX_STAT_ITEM_NUM 20 +typedef struct _mem_stat_item_t +{ + char name[32]; + u64 size; +} mem_stat_item_t; + +typedef struct _mem_stat_mgr_t +{ + u32 item_num; + mem_stat_item_t item[MAX_STAT_ITEM_NUM]; +} mem_stat_mgr; + +mem_stat_mgr g_max_mem_list; +#endif + +/***************************************************************************** +* Prototype : nsfw_mem_stat +* Description : add memory stat +* Input : char *module +* char *mem_name +* u8 mem_type +* u32 mem_size +* Output : None +* Return Value : void +* Calls : +* Called By : +*****************************************************************************/ +void nsfw_mem_stat(char *module, char *mem_name, u8 mem_type, u64 mem_size) +{ + if (NULL == module || NULL == mem_name) + { + NSFW_LOGERR("argv err]module=%p,mem_name=%p", module, mem_name); + return; + } + + int i; + nsfw_mem_stat_t *mem_stat_item = NULL; + for (i = 0; i < NSFW_MEM_STAT_NUM; i++) + { + if (FALSE == g_mem_stat[i].alloc_flag) + { + g_mem_stat[i].alloc_flag = TRUE; + mem_stat_item = &g_mem_stat[i]; + break; + } + } + + if (NULL == mem_stat_item) + { + NSFW_LOGERR("mem stat full]module=%s,type=%u,name=%s,size=%lu", + module, mem_type, mem_name, mem_size); + return; + } + + mem_stat_item->mem_type = mem_type; + mem_stat_item->mem_size = mem_size; + + /* we'd better use `strlen(src)` or `sizeof(dst)` to explain copying length of src string. + it's meaningless using `sizeof(dst) - 1` to reserve 1 byte for '\0'. + if copying length equals to or bigger than dst length, just let strncpy_s() returns failure. */ + + /* change param 'count' from NSFW_MEM_MODULE_LEN to NSFW_MEM_MODULE_LEN-1 */ + if (EOK != strcpy_s(mem_stat_item->module, NSFW_MEM_MODULE_LEN, module)) // remove needless 'count' param and change strncpy_s to strcpy_s + { + NSFW_LOGERR("strncpy_s failed"); + return; + } + + /* change param 'count' from NSFW_MEM_NAME_LEN to NSFW_MEM_NAME_LEN-1 */ + if (EOK != strcpy_s(mem_stat_item->mem_name, NSFW_MEM_NAME_LEN, mem_name)) // remove needless 'count' param and change strncpy_s to strcpy_s + { + NSFW_LOGERR("strncpy_s failed"); + return; + } + + return; +} + +void nsfw_mem_stat_print() +{ + int i; + for (i = 0; i < NSFW_MEM_STAT_NUM; i++) + { + if (TRUE == g_mem_stat[i].alloc_flag) + { + NSFW_LOGINF("mem_module=%s,name=%s,type=%u,size=%u", + g_mem_stat[i].module, g_mem_stat[i].mem_name, + g_mem_stat[i].mem_type, g_mem_stat[i].mem_size); + } + } + +} + +#ifdef SYS_MEM_RES_STAT +void clear_mem_stat_item() +{ + if (EOK != memset_s((char *) &g_max_mem_list, sizeof(mem_stat_mgr), + 0, sizeof(mem_stat_mgr))) + { + NSFW_LOGERR("memset_s failed"); + } +} + +void insert_mem_stat_item(char *name, u64 len) +{ + int j, temp; + + if (g_max_mem_list.item_num == 0) + { + /* copy string should use strcpy_s */ + if (EOK != + strcpy_s(g_max_mem_list.item[0].name, + sizeof(g_max_mem_list.item[0].name), name)) + { + NSFW_LOGERR("strcpy_s failed"); + } + g_max_mem_list.item[0].size = len; + g_max_mem_list.item_num++; + return; + } + else if (g_max_mem_list.item_num < MAX_STAT_ITEM_NUM) + { + if (len <= g_max_mem_list.item[g_max_mem_list.item_num - 1].size) + { + /* copy string should use strcpy_s */ + if (EOK != + strcpy_s(g_max_mem_list.item[g_max_mem_list.item_num].name, + sizeof(g_max_mem_list.item + [g_max_mem_list.item_num].name), name)) + { + NSFW_LOGERR("strcpy_s failed"); + } + g_max_mem_list.item[g_max_mem_list.item_num].size = len; + g_max_mem_list.item_num++; + return; + } + j = 0; + temp = g_max_mem_list.item_num; + while (j < temp) + { + if (len >= g_max_mem_list.item[j].size) + { + goto insert_it; + } + j++; + } + if (j == temp) + { + /* copy string should use strcpy_s */ + if (EOK != + strcpy_s(g_max_mem_list.item[j].name, + sizeof(g_max_mem_list.item[j].name), name)) + { + NSFW_LOGERR("strcpy_s failed"); + } + g_max_mem_list.item[j].size = len; + g_max_mem_list.item_num++; + return; + } + } + else + { + j = 0; + temp = MAX_STAT_ITEM_NUM - 1; + while (j < MAX_STAT_ITEM_NUM) + { + if (len >= g_max_mem_list.item[j].size) + { + goto insert_it; + } + j++; + } + } + + return; + + while (temp - 1 >= j) + { + /* copy string should use strcpy_s */ + if (EOK != + strcpy_s(g_max_mem_list.item[temp].name, + sizeof(g_max_mem_list.item[temp].name), + g_max_mem_list.item[temp - 1].name)) + { + NSFW_LOGERR("strcpy_s failed"); + } + g_max_mem_list.item[temp].size = g_max_mem_list.item[temp - 1].size; + temp--; + } + /* copy string should use strcpy_s */ + if (EOK != + strcpy_s(g_max_mem_list.item[j].name, + sizeof(g_max_mem_list.item[j].name), name)) + { + NSFW_LOGERR("strcpy_s failed"); + } + g_max_mem_list.item[j].size = len; + g_max_mem_list.item_num++; + return; +} + +int get_mem_stat_item(int idx, char **name, u64 * len) +{ + if (idx < 0 || idx >= MAX_STAT_ITEM_NUM) + { + return -1; + } + + *name = g_max_mem_list.item[idx].name; + *len = g_max_mem_list.item[idx].size; + + return 0; +} +#endif + +int nsfw_mem_stat_init(void *param); +int nsfw_mem_stat_init(void *param) +{ + MEM_STAT(NSFW_MEM_STAT_MODULE, "g_mem_stat", NSFW_NSHMEM, + sizeof(g_mem_stat)); + nsfw_mem_stat_print(); +#ifdef SYS_MEM_RES_STAT + clear_mem_stat_item(); +#endif + return 0; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_MEM_STAT_MODULE) +NSFW_MODULE_PRIORITY(99) +NSFW_MODULE_INIT(nsfw_mem_stat_init) +/* *INDENT-ON* */ + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/maintain/nsfw_res_mgr.c b/src/framework/maintain/nsfw_res_mgr.c new file mode 100644 index 0000000..36ce6d4 --- /dev/null +++ b/src/framework/maintain/nsfw_res_mgr.c @@ -0,0 +1,70 @@ +/* +* +* 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_api.h" + +#include "nstack_log.h" +#include "nsfw_maintain_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +nsfw_res_mgr_item_cfg g_all_res_can[NSFW_MAX_RES_SCAN_COUNT]; + +u8 nsfw_res_mgr_reg(nsfw_res_scn_cfg * cfg) +{ + if (NULL == cfg) + { + NSFW_LOGERR("argv err!"); + return FALSE; + } + + u32 i; + for (i = 0; i < NSFW_MAX_RES_SCAN_COUNT; i++) + { + + if ((NULL == g_all_res_can[i].scn_cfg.free_fun) + && + (__sync_bool_compare_and_swap + (&g_all_res_can[i].scn_cfg.free_fun, 0, cfg->free_fun))) + { + g_all_res_can[i].scn_cfg = *cfg; + NSFW_LOGINF("reg res_mgr fun suc]fun=%p,data=%p", cfg->free_fun, + cfg->data); + return TRUE; + } + } + + /* here is fail branch, should log ERR level and return false */ + NSFW_LOGERR + ("reg]type=%u,per=%u,chk=%u,cyc=%u,total=%u,size=%u,offset=%u,fun=%p,data=%p", + cfg->type, cfg->force_free_percent, cfg->force_free_chk_num, + cfg->num_per_cyc, cfg->total_num, cfg->elm_size, cfg->res_mem_offset, + cfg->free_fun, cfg->data); + return FALSE; +} + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/maintain/nsfw_set_log.c b/src/framework/maintain/nsfw_set_log.c new file mode 100644 index 0000000..c8125ec --- /dev/null +++ b/src/framework/maintain/nsfw_set_log.c @@ -0,0 +1,196 @@ +/* +* +* 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_api.h" + +#include "nstack_log.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mem_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +typedef struct _nsfw_log_cfg +{ + u8 proc_type; + char master_log_path[NSFW_LOG_VALUE_LEN]; + char runing_log_path[NSFW_LOG_VALUE_LEN]; + char opr_log_path[NSFW_LOG_VALUE_LEN]; +} nsfw_log_cfg; + +nsfw_log_cfg g_log_cfg; + +const char nsfw_mas_log[NSFW_LOG_VALUE_LEN] = "maspath"; +const char nsfw_flush_name[NSFW_LOG_VALUE_LEN] = "flush"; + +enum _set_log_type +{ + SET_LOG_LEVEL = 0, + SET_LOG_FLUSH, + SET_LOG_MASTER, + SET_LOG_MAIN, + + SET_LOG_INVALID +}; +extern struct log_init_para g_log_init_para; + +int nsfw_set_log_path(const char *param, const char *value) +{ + if (NULL == param || NULL == value) + { + NSFW_LOGERR("log param error!]param=%p,value=%p", param, value); + return 1; + } + + if (strcmp(g_log_init_para.mon_log_path, value) == 0) + { + NSFW_LOGWAR("Enter the address the same as the original address"); + return 0; + } + + /* add the path valid check */ + if (check_log_dir_valid(value) < 0) + { + NSFW_LOGERR("path is invalid]value=%s", value); + return 1; + } + if (EOK != strcpy_s(g_log_cfg.master_log_path, NSFW_LOG_VALUE_LEN, value)) + { + NSFW_LOGERR("strcpy error!"); + return 1; + } + + NSFW_LOGINF("renew log path]%s", g_log_cfg.master_log_path); + /* set log in glog, no need log lock now */ + nstack_modify_log_dir(g_log_cfg.master_log_path); + NSFW_LOGINF("set log sucess]newpath=%s!", g_log_cfg.master_log_path); + return 0; +} + +int nsfw_flush_log_info(const char *param, u8 proc_type) +{ + if (NULL == param) + { + NSFW_LOGERR("log param error!]param=%p", param); + return 1; + } + glogFlushLogFiles(GLOG_LEVEL_DEBUG); + NSFW_LOGINF("flush log sucess]proc_type=%u", proc_type); + return 0; +} + +int nsfw_set_log_msg_proc(nsfw_mgr_msg * msg) +{ + int ret = -1; + int status = -1; + if (NULL == msg) + { + NSFW_LOGERR("msg nul"); + return FALSE; + } + + nsfw_set_log_msg *set_log_msg = GET_USER_MSG(nsfw_set_log_msg, msg); + + /* add the flush branch handle */ + if (0 == strcmp(set_log_msg->module, nsfw_mas_log)) + { + status = SET_LOG_MASTER; + } + else if (0 == strcmp(set_log_msg->module, nsfw_flush_name)) + { + status = SET_LOG_FLUSH; + } + else if (nsfw_isdigitstr(set_log_msg->module)) + { + status = SET_LOG_LEVEL; + } + + switch (status) + { + case SET_LOG_LEVEL: + ret = + setlog_level_value(set_log_msg->module, + set_log_msg->log_level); + break; + case SET_LOG_FLUSH: + ret = + nsfw_flush_log_info(set_log_msg->module, msg->dst_proc_type); + break; + case SET_LOG_MASTER: + ret = + nsfw_set_log_path(set_log_msg->module, + set_log_msg->log_level); + break; + default: + NSFW_LOGERR("default error]status=%d,set_log_msg->module=%s", + status, set_log_msg->module); + break; + } + + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp failed,drop msg!" MSGINFO, PRTMSG(msg)); + return FALSE; + } + nsfw_set_log_msg *log_rsp_msg = GET_USER_MSG(nsfw_set_log_msg, rsp_msg); + log_rsp_msg->rsp_code = ret; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + return TRUE; +} + +static int nsfw_cfg_module_init(void *param); +static int nsfw_cfg_module_init(void *param) +{ + u8 proc_type = (u8) ((long long) param); + NSFW_LOGINF("log cfg module init]type=%u", proc_type); + switch (proc_type) + { + case NSFW_PROC_MAIN: + case NSFW_PROC_MASTER: + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_SET_LOG_REQ, + nsfw_set_log_msg_proc); + g_log_cfg.proc_type = proc_type; + return 0; + default: + if (proc_type < NSFW_PROC_MAX) + { + break; + } + return -1; + } + + return 0; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_LOG_CFG_MODULE) +NSFW_MODULE_PRIORITY(99) +NSFW_MODULE_INIT(nsfw_cfg_module_init) +/* *INDENT-ON* */ + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/maintain/nsfw_soft_param.c b/src/framework/maintain/nsfw_soft_param.c new file mode 100644 index 0000000..c99f785 --- /dev/null +++ b/src/framework/maintain/nsfw_soft_param.c @@ -0,0 +1,289 @@ +/* +* +* 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 <stdlib.h> +#include "types.h" +#include "nstack_securec.h" +#include "nsfw_init_api.h" +#include "nstack_log.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mem_api.h" + +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C"{ +/* *INDENT-ON* */ +#endif /* __cplusplus */ + +typedef struct _nsfw_set_soft_item +{ + void *data; + u32 size; + u64 max; + u64 min; +} nsfw_set_soft_item; + +nsfw_set_soft_fun g_soft_fun[NSFW_MAX_SOFT_PARAM] = { 0 }; + +nsfw_set_soft_item g_soft_int_cfg[NSFW_MAX_SOFT_PARAM]; + +int nsfw_isdigitstr(const char *str) +{ + if (NULL == str || '\0' == str[0]) + return 0; + + while (*str) + { + if (*str < '0' || *str > '9') + return 0; + str++; + } + return 1; +} + +u8 nsfw_soft_param_reg_fun(u32 param_name, nsfw_set_soft_fun fun) +{ + if (NULL == fun || param_name >= NSFW_MAX_SOFT_PARAM) + { + NSFW_LOGERR("argv err]fun=%p,type=%u", fun, param_name); + return FALSE; + } + + g_soft_fun[param_name] = fun; + NSFW_LOGINF("reg]fun=%p,type=%u", fun, param_name); + return TRUE; +} + +int nsfw_soft_set_int(u32 param, char *buf, u32 buf_len) +{ + u64 buf_value = 0; + if (NULL == buf || param >= NSFW_MAX_SOFT_PARAM) + { + NSFW_LOGERR("argv err]buf=%p,param=%u", buf, param); + return FALSE; + } + + if (!nsfw_isdigitstr(buf)) + { + NSFW_LOGERR("argv err]buf=%s,param=%u", buf, param); + return FALSE; + } + + char *parsing_end; + buf_value = (u64) strtol(buf, &parsing_end, 10); + nsfw_set_soft_item *int_item = &g_soft_int_cfg[param]; + if (NULL == int_item->data) + { + NSFW_LOGERR("data err]buf=%s,param=%u,min=%llu,max=%llu", buf, param, int_item->min, int_item->max); //fix type dismatch + return FALSE; + } + + if (buf_value < int_item->min || buf_value > int_item->max) + { + NSFW_LOGERR("argv err]buf=%s,param=%u,min=%llu,max=%llu", buf, param, int_item->min, int_item->max); //fix type dismatch + return FALSE; + } + + u32 size = int_item->size; + if (size >= sizeof(u64)) + { + size = sizeof(u64); + } + + if (EOK != memcpy_s(int_item->data, size, &buf_value, size)) + { + NSFW_LOGERR("memcpy_s failed"); + return FALSE; + } + + NSFW_LOGDBG("set soft param ok]param=%u,value=%llu,size=%u", param, + buf_value, size); + return TRUE; +} + +/***************************************************************************** +* Prototype : nsfw_soft_param_reg_int +* Description : reg int param set +* Input : u32 param_name +* u32 size +* u32 min +* u32 max +* u64 *data +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_soft_param_reg_int(u32 param_name, u32 size, u32 min, u32 max, + u64 * data) +{ + if (NULL == data || param_name >= NSFW_MAX_SOFT_PARAM) + { + NSFW_LOGERR("argv err]data=%p,type=%u", data, param_name); + return FALSE; + } + + g_soft_int_cfg[param_name].data = data; + g_soft_int_cfg[param_name].size = size; + g_soft_int_cfg[param_name].max = max; + g_soft_int_cfg[param_name].min = min; + return nsfw_soft_param_reg_fun(param_name, nsfw_soft_set_int); +} + +void nsfw_set_soft_para(fw_poc_type proc_type, u32 para_name, void *value, + u32 size) +{ + nsfw_mgr_msg *msg = + (nsfw_mgr_msg *) nsfw_mgr_msg_alloc(MGR_MSG_SOF_PAR_REQ, proc_type); + if (NULL == msg) + { + NSFW_LOGERR + ("nsfw_mgr_msg_alloc failed] msg type=%d, proc type=%d, para_name=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name); + return; + } + + nsfw_soft_param_msg *soft_msg = GET_USER_MSG(nsfw_soft_param_msg, msg); + + soft_msg->param_name = para_name; + soft_msg->rsp_code = 0; + + if (EOK != + memcpy_s(soft_msg->param_value, sizeof(soft_msg->param_value), + value, size)) + { + NSFW_LOGERR + ("memcpy_s failed] msg type=%d, proc type=%d, para_name=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name); + nsfw_mgr_msg_free(msg); + return; + } + + nsfw_mgr_msg *rsp = nsfw_mgr_null_rspmsg_alloc(); + if (NULL == rsp) + { + NSFW_LOGERR + ("nsfw_mgr_null_rspmsg_alloc failed] msg type=%d, proc type=%d, para_name=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name); + nsfw_mgr_msg_free(msg); + return; + } + + if (!nsfw_mgr_send_req_wait_rsp(msg, rsp)) + { + NSFW_LOGERR + ("can not get response] msg type=%d, proc type=%d, para_name=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name); + nsfw_mgr_msg_free(msg); + nsfw_mgr_msg_free(rsp); + return; + } + + nsfw_soft_param_msg *soft_rsp_msg = + GET_USER_MSG(nsfw_soft_param_msg, rsp); + if (soft_rsp_msg->rsp_code != NSFW_EXIT_SUCCESS) + { + NSFW_LOGERR + ("set soft param failed] msg type=%d, proc type=%d, para_name=%u, rsp code=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name, + soft_rsp_msg->rsp_code); + nsfw_mgr_msg_free(msg); + nsfw_mgr_msg_free(rsp); + return; + } + + NSFW_LOGDBG + ("set soft param success] msg type=%d, proc type=%d, para_name=%u", + MGR_MSG_SOF_PAR_REQ, proc_type, para_name); + + nsfw_mgr_msg_free(msg); + nsfw_mgr_msg_free(rsp); + return; +} + +int nsfw_softparam_msg_proc(nsfw_mgr_msg * msg) +{ + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp failed,drop msg!" MSGINFO, PRTMSG(msg)); + return FALSE; + } + + nsfw_soft_param_msg *soft_msg = GET_USER_MSG(nsfw_soft_param_msg, msg); + nsfw_soft_param_msg *soft_rsp_msg = + GET_USER_MSG(nsfw_soft_param_msg, rsp_msg); + if ((soft_msg->param_name < NSFW_MAX_SOFT_PARAM) + && (NULL != g_soft_fun[soft_msg->param_name])) + { + soft_msg->param_value[sizeof(soft_msg->param_value) - 1] = 0; + (void) g_soft_fun[soft_msg->param_name] (soft_msg->param_name, + (char *) + soft_msg->param_value, + sizeof + (soft_msg->param_value)); + //NSFW_LOGERR("set soft!]soft=%d,value=%s,ret=%d",soft_msg->param_name,soft_msg->param_value,ret); + soft_rsp_msg->rsp_code = NSFW_EXIT_SUCCESS; + } + else + { + NSFW_LOGERR("set soft failed!]soft=%u", soft_msg->param_name); + soft_rsp_msg->rsp_code = NSFW_EXIT_FAILED; + } + + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + return TRUE; +} + +int nsfw_softparam_module_init(void *param); +int nsfw_softparam_module_init(void *param) +{ + u8 proc_type = (u8) ((long long) param); + NSFW_LOGINF("softparam module init]type=%u", proc_type); + switch (proc_type) + { + case NSFW_PROC_MAIN: + case NSFW_PROC_MASTER: + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_SOF_PAR_REQ, + nsfw_softparam_msg_proc); + return 0; + default: + if (proc_type < NSFW_PROC_MAX) + { + break; + } + return -1; + } + + return 0; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_SOFT_PARAM_MODULE) +NSFW_MODULE_PRIORITY(99) +NSFW_MODULE_INIT(nsfw_softparam_module_init) +/* *INDENT-ON* */ + +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif /* __cplusplus */ diff --git a/src/framework/maintain/nsfw_ver_mgr.c b/src/framework/maintain/nsfw_ver_mgr.c new file mode 100644 index 0000000..993fd49 --- /dev/null +++ b/src/framework/maintain/nsfw_ver_mgr.c @@ -0,0 +1,391 @@ +/* +* +* 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_api.h" +#include "nstack_log.h" +#include "nsfw_maintain_api.h" +#include "nsfw_mem_api.h" + +nsfw_ver_info g_ver_info; + +int g_cur_upg_state = 0; +int g_start_type = 0; + +#define NSFW_VER_UPG_KILL_TIME 5 + +u8 nsfw_init_version_info(u8 proc_type) +{ + int retVal; + char *module_name = nsfw_get_proc_name(proc_type); + if (NULL == module_name) + { + return FALSE; + } + + retVal = + strcpy_s(g_ver_info.module_name, NSTACK_MAX_MODULE_LEN, module_name); + if (EOK != retVal) + { + NSFW_LOGERR("strcpy_s failed]ret=%d.", retVal); + return FALSE; + } + + /* `sizeof(constant string) -1` equals to `strlen(constant string)` */ + retVal = strcpy_s(g_ver_info.version, NSTACK_MAX_VERSION_LEN, NSTACK_GETVER_VERSION); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + return FALSE; + } + + retVal = strcpy_s(g_ver_info.build_time, NSTACK_MAX_BUILDTIME_LEN, NSTACK_GETVER_BUILDTIME); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + return FALSE; + } + NSFW_LOGINF("init version]daemon-stack_version=%s", NSTACK_VERSION); + return TRUE; +} + +/***************************************************************************** +* Prototype : nsfw_srv_ctrl_send +* Description : send service control message +* Input : nsfw_srv_ctrl_state state +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_srv_ctrl_send(nsfw_srv_ctrl_state state, u8 rsp_flag) +{ + nsfw_mgr_msg *req_msg = + nsfw_mgr_msg_alloc(MGR_MSG_SRV_CTL_REQ, NSFW_PROC_MASTER); + if (NULL == req_msg) + { + NSFW_LOGERR("alloc req msg failed]state=%d", state); + return FALSE; + } + + nsfw_mgr_msg *rsp_msg = NULL; + if (TRUE == rsp_flag) + { + rsp_msg = nsfw_mgr_null_rspmsg_alloc(); + if (NULL == rsp_msg) + { + nsfw_mgr_msg_free(req_msg); + NSFW_LOGERR("alloc rsp msg failed]state=%d", state); + return FALSE; + } + } + + nsfw_srv_ctrl_msg *ctrl_msg = GET_USER_MSG(nsfw_srv_ctrl_msg, req_msg); + ctrl_msg->srv_state = state; + + u8 ret; + ret = nsfw_mgr_send_req_wait_rsp(req_msg, rsp_msg); + NSFW_LOGINF("send srv ctrl end msg]state=%d,ret=%u,rsp=%u", state, ret, + rsp_flag); + nsfw_mgr_msg_free(req_msg); + if (NULL != rsp_msg) + { + nsfw_mgr_msg_free(rsp_msg); + } + return ret; +} + +/***************************************************************************** +* Prototype : nsfw_ver_mgr_rsq +* Description : send version mgr message +* Input : u16 rsp_code +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_ver_mgr_rsq(u16 rsp_code, u32 src_pid) +{ + nsfw_mgr_msg *rsp_msg = + nsfw_mgr_msg_alloc(MGR_MSG_VER_MGR_RSP, NSFW_PROC_CTRL); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp msg failed]rsp_code=%u", rsp_code); + return FALSE; + } + + rsp_msg->dst_pid = src_pid; + if (rsp_code != 0) + { + g_cur_upg_state = 0; + } + + nsfw_ver_mgr_msg *ver_msg = GET_USER_MSG(nsfw_ver_mgr_msg, rsp_msg); + ver_msg->rsp_code = rsp_code; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + NSFW_LOGINF("send ver mgr rsp msg]state=%u", rsp_code); + return TRUE; +} + +/***************************************************************************** +* Prototype : nsfw_ver_mgr_req +* Description : send ver mgr request message +* Input : nsfw_ver_mgr_state state +* char *src_ver +* char* dst_ver +* Output : None +* Return Value : u8 +* Calls : +* Called By : +*****************************************************************************/ +u8 nsfw_ver_mgr_req(nsfw_ver_mgr_state state, char *src_ver, char *dst_ver) +{ + nsfw_mgr_msg *req_msg = + nsfw_mgr_msg_alloc(MGR_MSG_VER_MGR_REQ, NSFW_PROC_MAIN); + if (NULL == req_msg) + { + NSFW_LOGERR("alloc rsp msg failed]state=%d", state); + return FALSE; + } + + nsfw_ver_mgr_msg *ver_msg = GET_USER_MSG(nsfw_ver_mgr_msg, req_msg); + ver_msg->ver_state = state; + + /* we'd better use `strlen(src)` or `sizeof(dst)` to explain copying length of src string. + it's meaningless using `sizeof(dst) - 1` to reserve 1 byte for '\0'. + if copying length equals to or bigger than dst length, just let strncpy_s() returns failure. */ + int retVal; + retVal = strcpy_s(ver_msg->src_ver, NSTACK_MAX_VERSION_LEN, src_ver); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + nsfw_mgr_msg_free(req_msg); + return FALSE; + } + + retVal = strcpy_s(ver_msg->dst_ver, NSTACK_MAX_VERSION_LEN, dst_ver); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + nsfw_mgr_msg_free(req_msg); + return FALSE; + } + + (void) nsfw_mgr_send_msg(req_msg); + nsfw_mgr_msg_free(req_msg); + NSFW_LOGINF("send srv ctrl end msg]state=%d", state); + return TRUE; +} + +/***************************************************************************** +* Prototype : nsfw_ver_mgr_msg_proc +* Description : version info query message process +* Input : nsfw_mgr_msg* msg +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int nsfw_ver_mgr_msg_proc(nsfw_mgr_msg * msg) +{ + if (NULL == msg) + { + NSFW_LOGERR("msg nul"); + return FALSE; + } + + nsfw_ver_mgr_msg *ver_mgr_msg = GET_USER_MSG(nsfw_ver_mgr_msg, msg); + NSFW_LOGDBG("recv ver mgr msg]state=%d,src_ver=%s,dst_ver=%s", + ver_mgr_msg->ver_state, ver_mgr_msg->src_ver, + ver_mgr_msg->dst_ver); + + if (NSFW_VER_QRY == ver_mgr_msg->ver_state) + { + nsfw_mgr_msg *rsp_msg = nsfw_mgr_rsp_msg_alloc(msg); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp failed,drop msg!" MSGINFO, PRTMSG(msg)); + return FALSE; + } + + nsfw_ver_mgr_msg *ver_rsp_msg = + GET_USER_MSG(nsfw_ver_mgr_msg, rsp_msg); + + /* we'd better use `strlen(src)` or `sizeof(dst)` to explain copying length of src string. + it's meaningless using `sizeof(dst) - 1` to reserve 1 byte for '\0'. + if copying length equals to or bigger than dst length, just let strncpy_s() returns failure. */ + + /* change strncpy_s's param 'count' from XXX to XXX-1 */ + int retVal; + retVal = strcpy_s(ver_rsp_msg->module_name, NSTACK_MAX_MODULE_LEN, g_ver_info.module_name); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + nsfw_mgr_msg_free(rsp_msg); + return FALSE; + } + + retVal = strcpy_s(ver_rsp_msg->src_ver, NSTACK_MAX_VERSION_LEN, g_ver_info.version); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + nsfw_mgr_msg_free(rsp_msg); + return FALSE; + } + + retVal = strcpy_s(ver_rsp_msg->build_time, NSTACK_MAX_BUILDTIME_LEN, g_ver_info.build_time); //remove needless 'count' param and change strncpy_s to strcpy_s + if (EOK != retVal) + { + NSFW_LOGERR("strncpy_s failed]ret=%d.", retVal); + nsfw_mgr_msg_free(rsp_msg); + return FALSE; + } + + ver_rsp_msg->ver_state = ver_mgr_msg->ver_state; + (void) nsfw_mgr_send_msg(rsp_msg); + nsfw_mgr_msg_free(rsp_msg); + } + + return TRUE; +} + +/***************************************************************************** +* Prototype : nsfw_ver_mgr_upg_msg_proc +* Description : master upg +* Input : nsfw_mgr_msg* msg +* Output : None +* Return Value : int +* Calls : +* Called By : +*****************************************************************************/ +int nsfw_ver_mgr_upg_msg_proc(nsfw_mgr_msg * msg) +{ + if (NULL == msg) + { + NSFW_LOGERR("msg nul"); + return FALSE; + } + + nsfw_ver_mgr_msg *ver_mgr_msg = GET_USER_MSG(nsfw_ver_mgr_msg, msg); /*not redeclared */ + NSFW_LOGDBG("recv ver mgr msg]state=%d,src_ver=%s,dst_ver=%s", + ver_mgr_msg->ver_state, ver_mgr_msg->src_ver, + ver_mgr_msg->dst_ver); + + if ((NSFW_VER_UPG != ver_mgr_msg->ver_state) + && (NSFW_VER_RBK != ver_mgr_msg->ver_state)) + { + return FALSE; + } + + if (TRUE == nsfw_ver_mgr_rsq(0, msg->src_pid)) + { + int i = 0; + while (i < NSFW_VER_UPG_KILL_TIME) + { + NSFW_LOGINF("wait nStackKill!]i=%d", i); + (void) sleep(1); + i++; + } + + exit(0); + } + return TRUE; +} + +u8 nsfw_init_result_send(u8 local_proc, nsfw_init_state state, u8 rsp_flag) +{ + nsfw_mgr_msg *req_msg = + nsfw_mgr_msg_alloc(MGR_MSG_INIT_NTY_REQ, NSFW_PROC_MASTER); + if (NULL == req_msg) + { + NSFW_LOGERR("alloc req msg failed]state=%d", state); + return FALSE; + } + + nsfw_mgr_msg *rsp_msg = NULL; + if (TRUE == rsp_flag) + { + rsp_msg = nsfw_mgr_rsp_msg_alloc(req_msg); + if (NULL == rsp_msg) + { + NSFW_LOGERR("alloc rsp msg failed]state=%d", state); + nsfw_mgr_msg_free(req_msg); + return FALSE; + } + } + + if (TRUE == req_msg->from_mem) + { + req_msg->src_proc_type = local_proc; + } + + nsfw_init_nty_msg *init_msg = GET_USER_MSG(nsfw_init_nty_msg, req_msg); + init_msg->init_state = state; + + u8 ret; + ret = nsfw_mgr_send_req_wait_rsp(req_msg, rsp_msg); + NSFW_LOGINF("send init end msg]state=%d,ret=%u,rsp=%u", state, ret, + rsp_flag); + nsfw_mgr_msg_free(req_msg); + if (NULL != rsp_msg) + { + nsfw_mgr_msg_free(rsp_msg); + } + + return ret; +} + +int nsfw_vermgr_module_init(void *param); +int nsfw_vermgr_module_init(void *param) +{ + u8 proc_type = (u8) ((long long) param); + if (proc_type != NSFW_PROC_CTRL) + { + NSFW_LOGINF("verupg module init]type=%d", proc_type); + } + (void) nsfw_init_version_info(proc_type); + switch (proc_type) + { + case NSFW_PROC_MASTER: + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_VER_MGR_REQ, + nsfw_ver_mgr_upg_msg_proc); + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_VER_MGR_REQ, + nsfw_ver_mgr_msg_proc); + return 0; + case NSFW_PROC_MAIN: + case NSFW_PROC_CTRL: + (void) nsfw_mgr_reg_msg_fun(MGR_MSG_VER_MGR_REQ, + nsfw_ver_mgr_msg_proc); + return 0; + default: + if (proc_type < NSFW_PROC_MAX) + { + break; + } + return -1; + } + + return 0; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_VER_MGR_MODULE) +NSFW_MODULE_PRIORITY(99) +NSFW_MODULE_INIT(nsfw_vermgr_module_init) +/* *INDENT-ON* */ diff --git a/src/framework/mem/basic_mem/dmm_fshm.c b/src/framework/mem/basic_mem/dmm_fshm.c new file mode 100644 index 0000000..ab8665f --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_fshm.c @@ -0,0 +1,200 @@ +/* +* +* 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 <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/mman.h> +#include <errno.h> + +#include "nstack_securec.h" +#include "nstack_log.h" +#include "nsfw_base_linux_api.h" + +#include "dmm_config.h" +#include "dmm_share.h" +#include "dmm_fs.h" + +#define DMM_FSHM_FMT "%s/dmm-fshm-%d" /* VAR_DIR pid */ + +inline static void set_fshm_path(char path[DMM_SHARE_PATH_MAX], pid_t pid) +{ + (void) snprintf_s(path, DMM_SHARE_PATH_MAX, DMM_SHARE_PATH_MAX - 1, + DMM_FSHM_FMT, DMM_VAR_DIR, pid); + + path[DMM_SHARE_PATH_MAX - 1] = 0; +} + +/* +input: share->path, share->size, share->pid +output: share->base +*/ +int dmm_fshm_create(struct dmm_share *share) +{ + int fd, ret; + void *base, *hint = (void *) DMM_MAIN_SHARE_BASE; + + if (share->type != DMM_SHARE_FSHM) + { + NSFW_LOGERR("type error, type:%d", share->type); + return -1; + } + + set_fshm_path(share->path, share->pid); + + NSFW_LOGINF("Start create share memory, path:'%s' size:%lu", + share->path, share->size); + + fd = open(share->path, O_RDWR | O_CREAT, 0666); + if (fd < 0) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + return -1; + } + + ret = ftruncate(fd, (off_t) share->size); + if (ret < 0) + { + NSFW_LOGERR("Set file size failed, path:'%s', errno=%d", + share->path, errno); + (void) nsfw_base_close(fd); + return -1; + } + + base = mmap(hint, share->size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (base == MAP_FAILED) + { + NSFW_LOGERR("Map failed, path:'%s' size:%lu, errno=%d", + share->path, share->size, errno); + (void) nsfw_base_close(fd); + return -1; + } + else if (hint && hint != MAP_FAILED && base != hint) + { + NSFW_LOGERR + ("Map address failed, path:'%s' hint:%p size:%lu, base:%p", + share->path, hint, share->size, base); + (void) munmap(base, share->size); + (void) nsfw_base_close(fd); + return -1; + } + + share->base = base; + + NSFW_LOGINF("Share memory created, size:%lu, base=%p", share->size, base); + + (void) nsfw_base_close(fd); + return 0; + +} + +int dmm_fshm_delete(struct dmm_share *share) +{ + (void) munmap(share->base, share->size); + (void) unlink(share->path); + + return 0; +} + +/* +input: share->path, share->size, share->base(OPT) +output: share->base(if-null) +*/ +int dmm_fshm_attach(struct dmm_share *share) +{ + int fd; + void *base; + + NSFW_LOGINF("Start attach, share:%p" + " {type:%d pid:%d base:%p size:%lu path:'%s'}", + share, share->type, share->pid, + share->base, share->size, share->path); + + if (share->type != DMM_SHARE_FSHM) + { + NSFW_LOGERR("type error, type:%d", share->type); + return -1; + } + + char *real_path = realpath(share->path, NULL); + if (NULL == real_path) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + return -1; + } + fd = open(real_path, O_RDWR); + if (fd < 0) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + (void) free(real_path); + return -1; + } + + if (share->size <= 0) + { + share->size = dmm_file_size(fd); + if (share->size == 0) + { + NSFW_LOGERR("No file size '%s'", share->path); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + } + + base = mmap(share->base, share->size, PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + if (base == MAP_FAILED) + { + NSFW_LOGERR("Map failed, path:'%s' base:%p size:%lu, errno=%d", + share->path, share->base, share->size, errno); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + + if (NULL == share->base) + { + share->base = base; + } + else if (base != share->base) + { + NSFW_LOGERR("Map address error, path:'%s' share->base:%p, base:%p", + share->path, share->base, base); + (void) munmap(base, share->size); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + + NSFW_LOGINF("Memory attached, base=%p", base); + + (void) nsfw_base_close(fd); + (void) free(real_path); + return 0; +} + +int dmm_fshm_detach(struct dmm_share *share) +{ + (void) munmap(share->base, share->size); + + return 0; +} diff --git a/src/framework/mem/basic_mem/dmm_group.c b/src/framework/mem/basic_mem/dmm_group.c new file mode 100644 index 0000000..8a2d318 --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_group.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 <stdio.h> +#include <stdlib.h> +#include <errno.h> +#include <unistd.h> +#include <limits.h> +#include <sys/types.h> +#include <signal.h> +#include <fcntl.h> +#include <sys/mman.h> + +#include "nsfw_base_linux_api.h" +#include "nstack_log.h" +#include "dmm_config.h" +#include "dmm_group.h" +#include "dmm_pause.h" +#include "nstack_securec.h" + +#define DMM_GROUP_ACTIVE 0x55D5551 +#define DMM_GROUP_GLOBAL "global" +#define DMM_GROUP_ENV "DMM_GROUP" +#define DMM_GROUP_FMT "%s/dmm-group-%s" /* VAR_DIR group-name */ + +static struct flock group_lock = { + .l_type = F_WRLCK, + .l_whence = SEEK_SET, + .l_start = 0, + .l_len = sizeof(struct dmm_group), +}; + +static int group_fd = -1; +struct dmm_group *main_group = NULL; + +inline static const char *get_group_path() +{ + static char group_path[PATH_MAX] = ""; + + if (!group_path[0]) + { + const char *group = getenv(DMM_GROUP_ENV); + + if (!group || !group[0]) + group = DMM_GROUP_GLOBAL; + + (void) snprintf_s(group_path, sizeof(group_path), + sizeof(group_path) - 1, DMM_GROUP_FMT, + DMM_VAR_DIR, group); + group_path[sizeof(group_path) - 1] = 0; + } + + return group_path; +} + +void dmm_group_active() +{ + main_group->group_init = DMM_GROUP_ACTIVE; + NSFW_LOGINF("main group actived"); +} + +int dmm_group_create_main() +{ + int ret; + const char *path = get_group_path(); + + NSFW_LOGINF("start create main group '%s'", path); + + group_fd = open(path, O_RDWR | O_CREAT, 0600); + if (group_fd < 0) + { + NSFW_LOGERR("open file failed, path:'%s', errno=%d", path, errno); + return -1; + } + + ret = ftruncate(group_fd, sizeof(struct dmm_group)); + if (ret < 0) + { + NSFW_LOGERR("set size failed, path:'%s' size:%lu, errno=%d", + path, sizeof(struct dmm_group), errno); + (void) nsfw_base_close(group_fd); + group_fd = -1; + return -1; + } + + ret = fcntl(group_fd, F_SETLK, &group_lock); + if (ret < 0) + { + NSFW_LOGERR("lock file failed, path:'%s', errno=%d", path, errno); + (void) nsfw_base_close(group_fd); + group_fd = -1; + return -1; + } + + main_group = (struct dmm_group *) mmap(NULL, sizeof(struct dmm_group), + PROT_READ | PROT_WRITE, + MAP_SHARED, group_fd, 0); + + if (main_group == MAP_FAILED) + { + NSFW_LOGERR("mmap failed, path:'%s' size:%lu, errno:%d", + path, sizeof(struct dmm_group), errno); + (void) nsfw_base_close(group_fd); + group_fd = -1; + return -1; + } + + NSFW_LOGINF("main group created, main_group:%p size:%lu", + main_group, sizeof(struct dmm_group)); + + return 0; +} + +int dmm_group_delete_main() +{ + if (main_group) + { + (void) munmap(main_group, sizeof(struct dmm_group)); + main_group = NULL; + } + + if (group_fd >= 0) + { + (void) nsfw_base_close(group_fd); + group_fd = -1; + } + + (void) unlink(get_group_path()); + + return 0; +} + +int dmm_group_attach_main() +{ + const char *path = get_group_path(); + + NSFW_LOGINF("Start attach main group '%s'", path); + + group_fd = open(path, O_RDONLY); + if (group_fd < 0) + { + //NSFW_LOGERR ("open group file failed, path:'%s', errno=%d", + //path, errno); + return -1; + } + + main_group = (struct dmm_group *) mmap(NULL, sizeof(struct dmm_group), + PROT_READ, MAP_SHARED, group_fd, + 0); + if (main_group == MAP_FAILED) + { + NSFW_LOGERR("mmap failed, path:'%s', errno=%d", path, errno); + (void) nsfw_base_close(group_fd); + group_fd = -1; + return -1; + } + + while (main_group->group_init != DMM_GROUP_ACTIVE) + { + dmm_pause(); + } + + if (kill(main_group->share.pid, 0)) + { + NSFW_LOGERR + ("main group process not exist, path:'%s' pid:%d errno=%d", path, + main_group->share.pid, errno); + (void) munmap(main_group->share.base, main_group->share.size); + (void) nsfw_base_close(group_fd); + (void) unlink(path); + group_fd = -1; + return -1; + } + + NSFW_LOGINF("main group attached, main_group=%p" + " {type=%d pid=%d base=%p size=%zd path='%s'}", + main_group, main_group->share.type, main_group->share.pid, + main_group->share.base, main_group->share.size, + main_group->share.path); + + return 0; +} + +int dmm_group_detach_main() +{ + if (main_group) + { + (void) munmap(main_group, sizeof(struct dmm_group)); + main_group = NULL; + } + + if (group_fd >= 0) + { + (void) nsfw_base_close(group_fd); + group_fd = -1; + } + + return 0; +} diff --git a/src/framework/mem/dmm_group.h b/src/framework/mem/basic_mem/dmm_group.h index b11a22b..a07c8d6 100644 --- a/src/framework/mem/dmm_group.h +++ b/src/framework/mem/basic_mem/dmm_group.h @@ -21,16 +21,16 @@ struct dmm_group { - volatile int group_init; - struct dmm_share share; + volatile int group_init; + struct dmm_share share; }; extern struct dmm_group *main_group; -void dmm_group_active (); -int dmm_group_create_main (); -int dmm_group_delete_main (); -int dmm_group_attach_main (); -int dmm_group_detach_main (); +void dmm_group_active(); +int dmm_group_create_main(); +int dmm_group_delete_main(); +int dmm_group_attach_main(); +int dmm_group_detach_main(); #endif /* _DMM_GROUP_H_ */ diff --git a/src/framework/mem/basic_mem/dmm_heap.c b/src/framework/mem/basic_mem/dmm_heap.c new file mode 100644 index 0000000..0efd0b4 --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_heap.c @@ -0,0 +1,82 @@ +/* +* +* 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 <sys/types.h> + +#include "dmm_config.h" +#include "dmm_share.h" + +struct heap_path +{ + void *base; + size_t size; +}; + +int dmm_heap_create(struct dmm_share *share) +{ + share->base = malloc(share->size); + + if (share->base) + { + struct heap_path *hp = (struct heap_path *) share->path; + hp->base = share->base; + hp->size = share->size; + return 0; + } + + return -1; +} + +int dmm_heap_delete(struct dmm_share *share) +{ + void *point = share->base; + share->base = NULL; + free(point); + return 0; +} + +int dmm_heap_attach(struct dmm_share *share) +{ + struct heap_path *hp = (struct heap_path *) share->path; + + if (share->base) + { + if (hp->base != share->base) + return -1; + } + else + { + share->base = hp->base; + } + + if (share->size) + { + if (share->size != hp->size) + return -1; + } + else + { + share->size = hp->size; + } + + return 0; +} + +int dmm_heap_detach(struct dmm_share *share) +{ + return 0; +} diff --git a/src/framework/mem/basic_mem/dmm_huge.c b/src/framework/mem/basic_mem/dmm_huge.c new file mode 100644 index 0000000..6267b6c --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_huge.c @@ -0,0 +1,192 @@ +/* +* +* 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 <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/mman.h> +#include <errno.h> + +#include "nstack_securec.h" +#include "nstack_log.h" +#include "nsfw_base_linux_api.h" + +#include "dmm_config.h" +#include "dmm_share.h" +#include "dmm_fs.h" + +#define DMM_HUGE_FMT "%s/dmm-%d-%d" /* HUGE_DIR/dmm-pid-index */ + +inline static void +huge_set_path(char path[DMM_SHARE_PATH_MAX], pid_t pid, int index) +{ + (void) snprintf_s(path, DMM_SHARE_PATH_MAX, DMM_SHARE_PATH_MAX - 1, + DMM_HUGE_FMT, DMM_HUGE_DIR, pid, index); + path[DMM_SHARE_PATH_MAX - 1] = 0; +} + +int dmm_huge_create(struct dmm_share *share) +{ + int fd, ret; + void *base, *hint = (void *) DMM_MAIN_SHARE_BASE; + + if (share->type != DMM_SHARE_HUGE) + { + NSFW_LOGERR("Type error, type:%d", share->type); + return -1; + } + + huge_set_path(share->path, share->pid, 0); + + NSFW_LOGINF("Start create share memory, path:'%s' size:%lu", + share->path, share->size); + + fd = open(share->path, O_RDWR | O_CREAT, 0666); + if (fd < 0) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + return -1; + } + + ret = ftruncate(fd, (off_t) share->size); + if (ret < 0) + { + NSFW_LOGERR("Set file size failed, path:'%s', errno=%d", + share->path, errno); + (void) nsfw_base_close(fd); + return -1; + } + + base = mmap(hint, share->size, PROT_READ | PROT_WRITE, + MAP_HUGETLB | MAP_SHARED | MAP_POPULATE, fd, 0); + if (base == MAP_FAILED) + { + NSFW_LOGERR("Map failed, path:'%s' size:%lu, errno=%d", + share->path, share->size, errno); + (void) nsfw_base_close(fd); + return -1; + } + else if (hint && hint != MAP_FAILED && hint != base) + { + NSFW_LOGERR + ("Map address failed, path:'%s' hint:%p size:%lu, base:%p", + share->path, hint, share->size, base); + (void) munmap(base, share->size); + (void) nsfw_base_close(fd); + return -1; + } + + share->base = base; + + NSFW_LOGINF("Share memory created, size:%lu, base=%p", share->size, base); + + (void) nsfw_base_close(fd); + return 0; +} + +int dmm_huge_delete(struct dmm_share *share) +{ + (void) munmap(share->base, share->size); + (void) unlink(share->path); + + return 0; +} + +int dmm_huge_attach(struct dmm_share *share) +{ + int fd; + void *base; + + NSFW_LOGINF("Start attach, share:%p" + " {type:%d pid:%d base:%p size:%lu path:'%s'}", + share, share->type, share->pid, + share->base, share->size, share->path); + + if (share->type != DMM_SHARE_HUGE) + { + NSFW_LOGERR("Type error, type:%d", share->type); + return -1; + } + + char *real_path = realpath(share->path, NULL); + if (NULL == real_path) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + return -1; + } + fd = open(real_path, O_RDWR); + if (fd < 0) + { + NSFW_LOGERR("Open file failed, path:'%s', errno=%d", + share->path, errno); + (void) free(real_path); + return -1; + } + + if (share->size <= 0) + { + share->size = dmm_file_size(fd); + if (share->size == 0) + { + NSFW_LOGERR("No file size '%s'", share->path); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + } + + base = mmap(share->base, share->size, PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + if (base == MAP_FAILED) + { + NSFW_LOGERR("mmap failed, path:'%s' base:%p size:%lu, errno=%d", + share->path, share->base, share->size, errno); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + + if (NULL == share->base) + { + share->base = base; + } + else if (base != share->base) + { + NSFW_LOGERR("mmap address error, path:'%s' share->base:%p, base:%p", + share->path, share->base, base); + (void) munmap(base, share->size); + (void) nsfw_base_close(fd); + (void) free(real_path); + return -1; + } + + NSFW_LOGINF("Memory attached, base=%p", base); + + (void) nsfw_base_close(fd); + (void) free(real_path); + return 0; +} + +int dmm_huge_detach(struct dmm_share *share) +{ + (void) munmap(share->base, share->size); + + return 0; +} diff --git a/src/framework/mem/basic_mem/dmm_memory.c b/src/framework/mem/basic_mem/dmm_memory.c new file mode 100644 index 0000000..affa0f6 --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_memory.c @@ -0,0 +1,284 @@ +/* +* +* 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 <sys/types.h> +#include <unistd.h> +#include <stdlib.h> + +#include "types.h" +#include "dmm_config.h" +#include "dmm_memory.h" +#include "dmm_group.h" + +#include "nsfw_init_api.h" +#include "nsfw_mgr_com_api.h" +#include "nstack_log.h" +#include "nsfw_mem_api.h" + +#define DMM_MEGABYTE (1024 * 1024) + +/* shared from main process */ +static struct dmm_share *main_share = NULL; +struct dmm_segment *main_seg = NULL; + +/* shared by process tree */ +static struct dmm_share base_share = { 0 }; + +struct dmm_segment *base_seg = NULL; + +int dmm_mem_main_init() +{ + int ret; + + ret = dmm_group_create_main(); + if (ret) + { + return -1; + } + + main_share = &main_group->share; + main_share->type = DMM_MAIN_SHARE_TYPE; + main_share->size = DMM_MAIN_SHARE_SIZE; + main_share->size *= DMM_MEGABYTE; + main_share->base = NULL; + main_share->pid = getpid(); + ret = dmm_share_create(main_share); + if (ret) + { + return -1; + } + + main_seg = dmm_seg_create(main_share->base, main_share->size); + if (!main_seg) + { + return -1; + } + + base_seg = main_seg; + + dmm_group_active(); + + return 0; +} + +int dmm_mem_main_exit() +{ + dmm_group_delete_main(); + return 0; +} + +int dmm_mem_app_init() +{ + int ret; + + ret = dmm_group_attach_main(); + if (0 == ret) + { + main_share = &main_group->share; + ret = dmm_share_attach(main_share); + if (ret) + { + NSFW_LOGERR + ("share attach failed, type:%d pid:%d base:%p size:%lu path:%s", + main_share->type, main_share->pid, main_share->base, + main_share->size, main_share->path); + return -1; + } + + main_seg = dmm_seg_attach(main_share->base, main_share->size); + if (!main_seg) + { + NSFW_LOGERR("segment attach failed, base:%p size:%lu", + main_share->base, main_share->size); + return -1; + } + + /* now share main process share-memory */ + base_seg = main_seg; + } + else + { + base_share.type = DMM_SHARE_TYPE; + base_share.size = 128 * DMM_MEGABYTE; + base_share.base = NULL; + base_share.pid = getpid(); + ret = dmm_share_create(&base_share); + if (ret) + { + return -1; + } + + base_seg = dmm_seg_create(base_share.base, base_share.size); + if (!base_seg) + { + return -1; + } + } + + return 0; +} + +void dmm_share_destroy() +{ + (void) dmm_share_delete(&base_share); + return; +} + +int dmm_mem_app_exit() +{ + dmm_group_detach_main(); + + if (base_share.base) + dmm_share_delete(&base_share); + + base_share.base = NULL; + base_seg = NULL; + main_seg = NULL; + + return 0; +} + +struct dmm_ring *dmm_create_ring(int num, int flag, + const char name[DMM_MEM_NAME_SIZE]) +{ + struct dmm_ring *ring; + const size_t bufsize = dmm_ring_bufsize(num); + + dmm_lock_map(); + + ring = dmm_map(bufsize, name); + + if (ring) + { + if (0 != dmm_ring_init(ring, num, 0, flag, NSFW_SHMEM)) + { + (void) dmm_unmap(ring); + ring = NULL; + } + } + + dmm_unlock_map(); + + return ring; +} + +struct dmm_ring *dmm_attach_ring(const char name[DMM_MEM_NAME_SIZE]) +{ + return (struct dmm_ring *) dmm_lookup(name); +} + +struct dmm_ring *dmm_malloc_ring(int num, int flag) +{ + const size_t size = dmm_ring_bufsize(num); + if (0 == size) + { + return NULL; + } + struct dmm_ring *ring = malloc(size); + + if (!ring) + return NULL; + + if (0 != dmm_ring_init(ring, num, 0, flag, NSFW_NSHMEM)) + { + free(ring); + return NULL; + } + + return ring; +} + +struct dmm_ring *dmm_create_pool(size_t elt_size, int num, int flag, + const char name[DMM_MEM_NAME_SIZE]) +{ + struct dmm_ring *pool; + const size_t pool_size = dmm_pool_bufsize(num, elt_size); + + dmm_lock_map(); + + pool = dmm_map(pool_size, name); + + if (pool) + { + if (0 != dmm_pool_init(pool, elt_size, num, flag, NSFW_SHMEM)) + { + (void) dmm_unmap(pool); + pool = NULL; + } + } + + dmm_unlock_map(); + + return pool; +} + +struct dmm_ring *dmm_attach_pool(const char name[DMM_MEM_NAME_SIZE]) +{ + return (struct dmm_ring *) dmm_lookup(name); +} + +struct dmm_ring *dmm_malloc_pool(size_t elt_size, int num, int flag) +{ + const size_t size = dmm_pool_bufsize(num, elt_size); + + if (0 == size) + { + return NULL; + } + struct dmm_ring *pool = malloc(size); + + if (!pool) + { + return NULL; + } + + if (0 != dmm_pool_init(pool, elt_size, num, flag, NSFW_NSHMEM)) + { + free(pool); + return NULL; + } + + return pool; +} + +int dmm_mem_module_init(void *param) +{ + int ret; + const u32 proc_type = (u32) ((long) param); + + NSFW_LOGINF("dmm mem module init]type=%u", proc_type); + + switch (proc_type) + { + case NSFW_PROC_MAIN: + ret = dmm_mem_main_init(); + break; + case NSFW_PROC_NULL: + ret = 0; + break; + default: + ret = dmm_mem_app_init(); + break; + } + + return ret; +} + +/* *INDENT-OFF* */ +//NSFW_MODULE_NAME (DMM_MEMORY_MODULE) +//NSFW_MODULE_PRIORITY (10) +//NSFW_MODULE_INIT (dmm_mem_module_init) +/* *INDENT-ON* */ diff --git a/src/framework/mem/basic_mem/dmm_memory.h b/src/framework/mem/basic_mem/dmm_memory.h new file mode 100644 index 0000000..6fc6a24 --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_memory.h @@ -0,0 +1,126 @@ +/* +* +* 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 _DMM_MEMORY_H_ +#define _DMM_MEMORY_H_ +#include <stdio.h> +#include <stdarg.h> +#include "dmm_share.h" +#include "dmm_segment.h" +#include "dmm_ring.h" +#include "nstack_securec.h" + +#define DMM_MEMORY_MODULE "DMM_MEMORY_MODULE" + +extern struct dmm_segment *main_seg; +extern struct dmm_segment *base_seg; + +inline static void dmm_lock_map() +{ + dmm_seg_lock(base_seg); +} + +inline static void dmm_unlock_map() +{ + dmm_seg_unlock(base_seg); +} + +inline static int dmm_unmap(void *mem) +{ + return dmm_mem_unmap(base_seg, mem); +} + +inline static void *dmm_locked_map(size_t size, + const char name[DMM_MEM_NAME_SIZE]) +{ + void *mem; + dmm_lock_map(); + mem = dmm_mem_map(base_seg, size, name); + dmm_unlock_map(); + return mem; +} + +inline static void *dmm_map(size_t size, const char name[DMM_MEM_NAME_SIZE]) +{ + return dmm_mem_map(base_seg, size, name); +} + +inline static void *dmm_mapv(size_t size, const char *name_fmt, ...) +{ + int len; + char name[DMM_MEM_NAME_SIZE]; + va_list ap; + + va_start(ap, name_fmt); + len = + vsnprintf_s(name, DMM_MEM_NAME_SIZE, DMM_MEM_NAME_SIZE - 1, name_fmt, + ap); + va_end(ap); + + if (len >= DMM_MEM_NAME_SIZE) + return NULL; + + return dmm_map(size, name); +} + +inline static void *dmm_lookup(const char name[DMM_MEM_NAME_SIZE]) +{ + return dmm_mem_lookup(base_seg, name); +} + +inline static void *dmm_lookupv(const char *name_fmt, ...) +{ + int len; + char name[DMM_MEM_NAME_SIZE]; + va_list ap; + + va_start(ap, name_fmt); + len = + vsnprintf_s(name, DMM_MEM_NAME_SIZE, DMM_MEM_NAME_SIZE - 1, name_fmt, + ap); + va_end(ap); + + if (len >= DMM_MEM_NAME_SIZE) + return NULL; + + return dmm_mem_lookup(base_seg, name); +} + +int dmm_mem_main_init(); +int dmm_mem_main_exit(); +int dmm_mem_app_init(); +int dmm_mem_app_exit(); + +struct dmm_ring *dmm_create_ring(int num, int flag, + const char name[DMM_MEM_NAME_SIZE]); + +struct dmm_ring *dmm_attach_ring(const char name[DMM_MEM_NAME_SIZE]); + +struct dmm_ring *dmm_malloc_ring(int num, int flag); + +struct dmm_ring *dmm_create_pool(size_t elt_size, int num, int flag, + const char name[DMM_MEM_NAME_SIZE]); + +struct dmm_ring *dmm_attach_pool(const char name[DMM_MEM_NAME_SIZE]); + +/* allocate pool from heap */ +struct dmm_ring *dmm_malloc_pool(size_t elt_size, int num, int flag); + +int dmm_mem_module_init(void *param); + +void dmm_share_destroy(); + +#endif /* _DMM_MEMORY_H_ */ diff --git a/src/framework/mem/basic_mem/dmm_segment.c b/src/framework/mem/basic_mem/dmm_segment.c new file mode 100644 index 0000000..3b92a55 --- /dev/null +++ b/src/framework/mem/basic_mem/dmm_segment.c @@ -0,0 +1,536 @@ +/* +* +* 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 <string.h> +#include <limits.h> +#include "dmm_common.h" +#include "dmm_rwlock.h" +#include "dmm_segment.h" +#include "nstack_log.h" +#include "nstack_securec.h" + +#define BLOCK_SIZE 64 /* cache line size */ +#define BLOCK_MASK (BLOCK_SIZE - 1) + +#define FIRST_NAME "FIRST SECTION FOR SEGMENT" +#define LAST_NAME "LAST SECTION FOR FREE HEAD" + +#define MEM_ERR(fmt, ...) \ + NS_LOGPID(LOGFW, "DMM-MEM", NSLOG_ERR, fmt, ##__VA_ARGS__) + +typedef struct +{ + char _dummy_block_size[BLOCK_SIZE]; +} _dmm_packed __BLOCK; + +/* +init create: + \--total number + /--head no align \ can be used \--tail no align + / ___________________/\___________________ \ +/\/ \/\ +__<F>{S}[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]<L>__ +^ \ /\ /\____________ ________________/\ / +| | | \ / | +| | +--the segment | +--last section(free:0 used:0) +| +--first section(prev_rel:0 used:2 free:11 req_size:sizeof(dmm_segment)) ++--base address + +init: <F>{S}[ ]<L> +alloc A: <F>{S}[ ]<A>#########<L> +alloc B: <F>{S}[ ]<B>#########<A>#########<L> +free A: <F>{S}[ ]<B>#########[ ]<L> +alloc C: <F>{S}[ ]<C>###<B>#########[ ]<L> +*/ + +typedef struct dmm_section +{ + int prev_rel; + int used_num; + int free_num; + int flags; /* reserved */ + size_t req_size; /* in bytes */ + int less_rel; /* for free list */ + int more_rel; /* for free list */ + char name[DMM_MEM_NAME_SIZE]; +} _dmm_cache_aligned section_t; + +/* dmm_section struct hold blocks number */ +#define SECTION_HOLD ((sizeof(struct dmm_section) + (BLOCK_SIZE - 1)) / BLOCK_SIZE) + +struct dmm_segment +{ + void *base; /* base address(maybe not align) */ + size_t size; /* full size */ + section_t *first; /* aligned 64 */ + section_t *last; /* last section used to handle free list */ + dmm_rwlock_t lock; + int total_num; /* MAX:2147483647 ==> MAX size: 128M-64 */ + int used_num; + int sec_num; + size_t used_size; /* real alloc size bytes */ +}; + +/* calculate segment number, auto align 64, include 1 section_t */ +inline static int CALC_NUM(size_t size) +{ + if (size) + { + return SECTION_HOLD + (size + BLOCK_MASK) / BLOCK_SIZE; + } + + return SECTION_HOLD + 1; /* if size is 0, then alloc 1 block */ +} + +inline static int SEC_REL(const section_t * base, const section_t * sec) +{ + return (__BLOCK *) sec - (__BLOCK *) base; +} + +section_t *REL_SEC(section_t * base, int rel) +{ + return (section_t *) ((__BLOCK *) base + rel); +} + +inline static int SEC_INDEX(struct dmm_segment *seg, section_t * sec) +{ + return SEC_REL(seg->first, sec); +} + +inline static section_t *LESS_SEC(section_t * sec) +{ + return REL_SEC(sec, sec->less_rel); +} + +inline static section_t *MORE_SEC(section_t * sec) +{ + return REL_SEC(sec, sec->more_rel); +} + +inline static section_t *PREV_SEC(section_t * sec) +{ + return REL_SEC(sec, sec->prev_rel); +} + +inline static section_t *NEXT_SEC(section_t * sec) +{ + return REL_SEC(sec, sec->free_num + sec->used_num); +} + +inline static int CHECK_ADDR(struct dmm_segment *seg, void *mem) +{ + if (mem < (void *) seg->first) + return -1; + if (mem > (void *) seg->last) + return -1; + if ((long) mem & BLOCK_MASK) + return -1; + + return 0; +} + +inline static section_t *mem_lookup(struct dmm_segment *seg, + const char name[DMM_MEM_NAME_SIZE]) +{ + section_t *sec; + + /* caller ensures the validity of the name */ + + for (sec = seg->last; sec != seg->first; sec = PREV_SEC(sec)) + { + if (sec->name[0] == 0) + continue; + if (0 == strcmp(sec->name, name)) + return sec; + } + + return NULL; +} + +static section_t *mem_alloc(struct dmm_segment *seg, size_t size) +{ + const int num = CALC_NUM(size); + section_t *sec, *pos, *next, *less, *more; + + if (num > seg->total_num - seg->used_num) + { + /* no enough memory */ + return NULL; + } + + /* find enough free space */ + pos = seg->last; + do + { + pos = MORE_SEC(pos); + if (pos == seg->last) + { + /* no enough memory */ + return NULL; + } + } + while (num > pos->free_num); + + /* allocate from pos section's tail */ + + /* change next section's prev possion */ + next = NEXT_SEC(pos); + next->prev_rel = -num; + + /* create new section */ + sec = PREV_SEC(next); + sec->prev_rel = SEC_REL(sec, pos); + sec->used_num = num; + sec->req_size = size; + sec->free_num = 0; /* no free space */ + sec->less_rel = 0; + sec->more_rel = 0; + sec->name[0] = 0; + + /* adjust pos section */ + pos->free_num -= num; + + less = LESS_SEC(pos); + more = MORE_SEC(pos); + + /* remove from free list */ + less->more_rel = SEC_REL(less, more); + more->less_rel = SEC_REL(more, less); + pos->more_rel = 0; + pos->less_rel = 0; + + /* find position */ + while (less != seg->last) + { + if (pos->free_num >= less->free_num) + break; + less = LESS_SEC(less); + } + + /* insert into free list */ + more = MORE_SEC(less); + less->more_rel = SEC_REL(less, pos); + more->less_rel = SEC_REL(more, pos); + pos->more_rel = SEC_REL(pos, more); + pos->less_rel = SEC_REL(pos, less); + + /* adjust segment */ + seg->used_size += size; + seg->used_num += num; + seg->sec_num++; + + /* victory */ + return sec; +} + +static void mem_free(struct dmm_segment *seg, section_t * sec) +{ + const int num = sec->used_num + sec->free_num; + section_t *next = NEXT_SEC(sec); + section_t *prev = PREV_SEC(sec); + section_t *more, *less; + + /* adjust next section's prev */ + next->prev_rel = SEC_REL(next, prev); + + if (sec->free_num) + { + /* remove from free list */ + more = MORE_SEC(sec); + less = LESS_SEC(sec); + more->less_rel = SEC_REL(more, less); + less->more_rel = SEC_REL(less, more); + } + + if (prev->free_num) + { + /* remove from free list */ + more = MORE_SEC(prev); + less = LESS_SEC(prev); + more->less_rel = SEC_REL(more, less); + less->more_rel = SEC_REL(less, more); + } + else + { + more = MORE_SEC(seg->last); + } + + /* put the space to prev's free space */ + prev->free_num += num; + + while (more != seg->last) + { + if (prev->free_num <= more->free_num) + break; + more = MORE_SEC(more); + } + less = LESS_SEC(more); + + /* insert */ + less->more_rel = SEC_REL(less, prev); + more->less_rel = SEC_REL(more, prev); + prev->more_rel = SEC_REL(prev, more); + prev->less_rel = SEC_REL(prev, less); + + /* adjust segment */ + seg->used_size -= sec->req_size; + seg->used_num -= sec->used_num; + seg->sec_num--; +} + +void dmm_seg_lock(struct dmm_segment *seg) +{ + dmm_write_lock(&seg->lock); +} + +void dmm_seg_unlock(struct dmm_segment *seg) +{ + dmm_write_unlock(&seg->lock); +} + +void dmm_seg_dump(struct dmm_segment *seg) +{ + section_t *sec; + + dmm_read_lock(&seg->lock); + + NSFW_LOGINF + ("---- segment:%p base:%p size:%lu ---- BS:%u SS:%lu SH:%lu ----\n" + " first[%d]:%p last[%d]:%p total_num:%d used_num:%d\n" + " sec_num:%d used_size:%lu use%%:%lu%% free%%:%lu%%\n", seg, + seg->base, seg->size, BLOCK_SIZE, sizeof(struct dmm_section), + SECTION_HOLD, SEC_INDEX(seg, seg->first), seg->first, + SEC_INDEX(seg, seg->last), seg->last, seg->total_num, seg->used_num, + seg->sec_num, seg->used_size, seg->used_size * 100 / seg->size, + (seg->total_num - seg->used_num) * (BLOCK_SIZE * 100) / seg->size); + + NSFW_LOGINF("----------------------------------------\n" + "%18s %9s %9s %9s %9s %10s %9s %9s %s\n", + "PHYSICAL-ORDER", "section", "prev_rel", "used_num", + "free_num", "req_size", "less_rel", "more_rel", "name"); + + sec = seg->first; + while (1) + { + NSFW_LOGINF("%18p %9d %9d %9d %9d %10lu %9d %9d '%s'\n", + sec, SEC_INDEX(seg, sec), + sec->prev_rel, sec->used_num, sec->free_num, + sec->req_size, sec->less_rel, sec->more_rel, sec->name); + if (sec == seg->last) + break; + sec = NEXT_SEC(sec); + } + + NSFW_LOGINF("----------------------------------------\n" + "%18s %9s %9s\n", "FREE-ORDER", "section", "free_num"); + for (sec = MORE_SEC(seg->last); sec != seg->last; sec = MORE_SEC(sec)) + { + NSFW_LOGINF("%18p %9d %9d\n", + sec, SEC_INDEX(seg, sec), sec->free_num); + } + + NSFW_LOGINF("----------------------------------------\n"); + + dmm_read_unlock(&seg->lock); + +} + +inline static int align_section(void *base, size_t size, section_t ** first) +{ + const int SEG_NUM = CALC_NUM(sizeof(struct dmm_segment)); + + const long align = (long) base; + const long addr = (align + BLOCK_MASK) & (~BLOCK_MASK); + const size_t total = (size - (addr - align)) / BLOCK_SIZE; + + if (total > INT_MAX) + return -1; + if (total < SEG_NUM + SECTION_HOLD) /* first+segment + last */ + return -1; + + *first = (section_t *) addr; + return (int) total; +} + +struct dmm_segment *dmm_seg_create(void *base, size_t size) +{ + section_t *first, *last; + struct dmm_segment *seg; + const int total = align_section(base, size, &first); + const int SEG_NUM = CALC_NUM(sizeof(struct dmm_segment)); + + if (total <= 0) + return NULL; + + last = first + (total - SECTION_HOLD); + + /* first section */ + first->prev_rel = 0; + first->used_num = SEG_NUM; + first->req_size = sizeof(struct dmm_segment); + first->free_num = total - (SEG_NUM + SECTION_HOLD); + first->less_rel = SEC_REL(first, last); + first->more_rel = SEC_REL(first, last); + first->name[0] = 0; + (void) strncpy_s(&first->name[1], DMM_MEM_NAME_SIZE, FIRST_NAME, + sizeof(first->name) - 1); + + /* last section */ + last->prev_rel = SEC_REL(last, first); + last->used_num = 0; + last->req_size = 0; + last->free_num = 0; + last->less_rel = SEC_REL(last, first); + last->more_rel = SEC_REL(last, first); + last->name[0] = 0; + (void) strncpy_s(&last->name[1], DMM_MEM_NAME_SIZE, LAST_NAME, + sizeof(first->name) - 1); + + /* segment */ + seg = (struct dmm_segment *) (first + 1); + dmm_rwlock_init(&seg->lock); + seg->base = base; + seg->size = size; + seg->first = first; + seg->last = last; + seg->total_num = total; + seg->sec_num = 2; /* first and tail */ + seg->used_size = sizeof(struct dmm_segment); + seg->used_num = first->used_num + SECTION_HOLD; + + return seg; +} + +struct dmm_segment *dmm_seg_attach(void *base, size_t size) +{ + section_t *first, *last; + struct dmm_segment *seg; + const int total = align_section(base, size, &first); + + if (total <= 0) + return NULL; + + last = first + (total - SECTION_HOLD); + seg = (struct dmm_segment *) (first + 1); + + if (seg->base != base) + return NULL; + if (seg->size != size) + return NULL; + if (seg->total_num != total) + return NULL; + + if (seg->first != first) + return NULL; + if (first->name[0] != 0) + return NULL; + if (strncmp(&first->name[1], FIRST_NAME, sizeof(first->name) - 1)) + return NULL; + + if (seg->last != last) + return NULL; + if (last->name[0] != 0) + return NULL; + if (strncmp(&last->name[1], LAST_NAME, sizeof(last->name) - 1)) + return NULL; + + return seg; +} + +void *dmm_mem_alloc(struct dmm_segment *seg, size_t size) +{ + section_t *sec; + + dmm_seg_lock(seg); + sec = mem_alloc(seg, size); + dmm_seg_unlock(seg); + + return sec ? sec + 1 : NULL; +} + +int dmm_mem_free(struct dmm_segment *seg, void *mem) +{ + if (CHECK_ADDR(seg, mem)) + { + MEM_ERR("Invalid address:%p", mem); + return -1; + } + + dmm_seg_lock(seg); + mem_free(seg, ((section_t *) mem) - 1); + dmm_seg_unlock(seg); + + return 0; +} + +void *dmm_mem_lookup(struct dmm_segment *seg, + const char name[DMM_MEM_NAME_SIZE]) +{ + section_t *sec; + + if (!name || !name[0]) + return NULL; + + dmm_read_lock(&seg->lock); + sec = mem_lookup(seg, name); + dmm_read_unlock(&seg->lock); + + return sec ? sec + 1 : NULL; +} + +void *dmm_mem_map(struct dmm_segment *seg, size_t size, + const char name[DMM_MEM_NAME_SIZE]) +{ + void *mem; + section_t *sec; + + if (!name || !name[0] || strlen(name) >= DMM_MEM_NAME_SIZE) + return NULL; + + sec = mem_lookup(seg, name); + if (sec) + { + MEM_ERR("Map '%s' exist", name); + mem = NULL; + } + else if (NULL != (sec = mem_alloc(seg, size))) + { + (void) strncpy_s(sec->name, DMM_MEM_NAME_SIZE, name, + sizeof(sec->name) - 1); + mem = sec + 1; + } + else + { + MEM_ERR("alloc '%s' failed for size %lu", name, size); + mem = NULL; + } + + return mem; +} + +int dmm_mem_unmap(struct dmm_segment *seg, void *mem) +{ + if (CHECK_ADDR(seg, mem)) + { + MEM_ERR("Invalid address:%p", mem); + return -1; + } + + mem_free(seg, ((section_t *) mem) - 1); + + return 0; +} diff --git a/src/framework/mem/dmm_segment.h b/src/framework/mem/basic_mem/dmm_segment.h index 135f347..f8b3dca 100644 --- a/src/framework/mem/dmm_segment.h +++ b/src/framework/mem/basic_mem/dmm_segment.h @@ -13,23 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_SEGMENT_H_ #define _DMM_SEGMENT_H_ +#include <stdlib.h> + #define DMM_MEM_NAME_SIZE 32 -struct dmm_segment *dmm_seg_create (void *base, size_t size); -struct dmm_segment *dmm_seg_attach (void *base, size_t size); -void dmm_seg_dump (struct dmm_segment *seg); +struct dmm_segment; + +void dmm_seg_lock(struct dmm_segment *seg); +void dmm_seg_unlock(struct dmm_segment *seg); + +struct dmm_segment *dmm_seg_create(void *base, size_t size); +struct dmm_segment *dmm_seg_attach(void *base, size_t size); +void dmm_seg_dump(struct dmm_segment *seg); -void *dmm_mem_alloc (struct dmm_segment *seg, size_t size); -int dmm_mem_free (struct dmm_segment *seg, void *mem); +void *dmm_mem_alloc(struct dmm_segment *seg, size_t size); +int dmm_mem_free(struct dmm_segment *seg, void *mem); -void *dmm_mem_lookup (struct dmm_segment *seg, - const char name[DMM_MEM_NAME_SIZE]); -void *dmm_mem_map (struct dmm_segment *seg, size_t size, - const char name[DMM_MEM_NAME_SIZE]); -int dmm_mem_unmap (struct dmm_segment *seg, - const char name[DMM_MEM_NAME_SIZE]); +void *dmm_mem_lookup(struct dmm_segment *seg, + const char name[DMM_MEM_NAME_SIZE]); +void *dmm_mem_map(struct dmm_segment *seg, size_t size, + const char name[DMM_MEM_NAME_SIZE]); +int dmm_mem_unmap(struct dmm_segment *seg, void *mem); #endif /* #ifndef _DMM_SEGMENT_H_ */ diff --git a/src/framework/mem/dmm_share.h b/src/framework/mem/basic_mem/dmm_share.h index 0d0ff8f..8db19fc 100644 --- a/src/framework/mem/dmm_share.h +++ b/src/framework/mem/basic_mem/dmm_share.h @@ -13,43 +13,48 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _DMM_SHARE_H_ #define _DMM_SHARE_H_ +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> + #define DMM_SHARE_PATH_MAX 100 enum dmm_share_type { - DMM_SHARE_HEAP, - DMM_SHARE_FSHM, - DMM_SHARE_HUGE, + DMM_SHARE_HEAP, + DMM_SHARE_FSHM, + DMM_SHARE_HUGE, - DMM_SHARE_ANY = -1 + DMM_SHARE_ANY = -1 }; struct dmm_share { - int type; /* share type enum dmm_share_type */ - pid_t pid; /* owner/creator pid */ - void *base; /* base logical address */ - size_t size; /* memory size */ - char path[DMM_SHARE_PATH_MAX]; /* share path */ + int type; /* share type enum dmm_share_type */ + pid_t pid; /* owner/creator pid */ + void *base; /* base logical address */ + size_t size; /* memory size */ + char path[DMM_SHARE_PATH_MAX]; /* share path */ }; -int dmm_heap_create (struct dmm_share *share); -int dmm_heap_delete (struct dmm_share *share); -int dmm_heap_attach (struct dmm_share *share); -int dmm_heap_detach (struct dmm_share *share); +int dmm_heap_create(struct dmm_share *share); +int dmm_heap_delete(struct dmm_share *share); +int dmm_heap_attach(struct dmm_share *share); +int dmm_heap_detach(struct dmm_share *share); -int dmm_fshm_create (struct dmm_share *share); -int dmm_fshm_delete (struct dmm_share *share); -int dmm_fshm_attach (struct dmm_share *share); -int dmm_fshm_detach (struct dmm_share *share); +int dmm_fshm_create(struct dmm_share *share); +int dmm_fshm_delete(struct dmm_share *share); +int dmm_fshm_attach(struct dmm_share *share); +int dmm_fshm_detach(struct dmm_share *share); -int dmm_huge_create (struct dmm_share *share); -int dmm_huge_delete (struct dmm_share *share); -int dmm_huge_attach (struct dmm_share *share); -int dmm_huge_detach (struct dmm_share *share); +int dmm_huge_create(struct dmm_share *share); +int dmm_huge_delete(struct dmm_share *share); +int dmm_huge_attach(struct dmm_share *share); +int dmm_huge_detach(struct dmm_share *share); #define DMM_SHARE_DISPATCH(share, action) \ ({ \ @@ -75,38 +80,34 @@ int dmm_huge_detach (struct dmm_share *share); input: share->type, share->size, share->pid output: share->base, share->path */ -inline static int -dmm_share_create (struct dmm_share *share) +inline static int dmm_share_create(struct dmm_share *share) { - return DMM_SHARE_DISPATCH (share, create); + return DMM_SHARE_DISPATCH(share, create); } /* delete share memory input: share->type, share->base, share->size, share->path */ -inline static int -dmm_share_delete (struct dmm_share *share) +inline static int dmm_share_delete(struct dmm_share *share) { - return DMM_SHARE_DISPATCH (share, delete); + return DMM_SHARE_DISPATCH(share, delete); } /* attach share memory input: share->type share->path [share->size] [share->base] output: share->base, share->size */ -inline static int -dmm_share_attach (struct dmm_share *share) +inline static int dmm_share_attach(struct dmm_share *share) { - return DMM_SHARE_DISPATCH (share, attach); + return DMM_SHARE_DISPATCH(share, attach); } /* attach share memory input: share->type share->size share->base */ -inline static int -dmm_share_detach (struct dmm_share *share) +inline static int dmm_share_detach(struct dmm_share *share) { - return DMM_SHARE_DISPATCH (share, detach); + return DMM_SHARE_DISPATCH(share, detach); } #undef DMM_SHARE_DISPATCH diff --git a/src/framework/mem/dmm_fshm.c b/src/framework/mem/dmm_fshm.c deleted file mode 100644 index 605c728..0000000 --- a/src/framework/mem/dmm_fshm.c +++ /dev/null @@ -1,144 +0,0 @@ -/* -* -* 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 <sys/types.h> -#include <sys/stat.h> -#include <unistd.h> -#include <fcntl.h> -#include <sys/mman.h> - -#include "dmm_config.h" -#include "dmm_share.h" -#include "dmm_fs.h" - -#define DMM_FSHM_FMT "%s/dmm-fshm-%d" /* VAR_DIR pid */ - -inline static void -set_fshm_path (struct dmm_share *share) -{ - (void) snprintf (share->path, sizeof (share->path), DMM_FSHM_FMT, - DMM_VAR_DIR, share->pid); -} - -/* -input: share->path, share->size, share->pid -output: share->base -*/ -int -dmm_fshm_create (struct dmm_share *share) -{ - int fd, ret; - void *base; - - set_fshm_path (share); - - fd = open (share->path, O_RDWR | O_CREAT, 0666); - if (fd < 0) - { - return -1; - } - - ret = ftruncate (fd, share->size); - if (ret < 0) - { - (void) close (fd); - return -1; - } - - base = mmap (NULL, share->size, - PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, 0); - if (base == MAP_FAILED) - { - (void) close (fd); - return -1; - } - - share->base = base; - - (void) close (fd); - return 0; -} - -int -dmm_fshm_delete (struct dmm_share *share) -{ - (void) munmap (share->base, share->size); - (void) unlink (share->path); - - return 0; -} - -/* -input: share->path, share->size, share->base(OPT) -output: share->base(if-null) -*/ -int -dmm_fshm_attach (struct dmm_share *share) -{ - int fd; - void *base; - - if (share->type != DMM_SHARE_FSHM) - { - return -1; - } - - fd = open (share->path, O_RDWR); - if (fd < 0) - { - return -1; - } - - if (share->size <= 0) - { - share->size = dmm_file_size (fd); - if (share->size == 0) - { - (void) close (fd); - return -1; - } - } - - base = mmap (share->base, share->size, - PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, 0); - if (base == MAP_FAILED) - { - (void) close (fd); - return -1; - } - - if (NULL == share->base) - { - share->base = base; - } - else if (base != share->base) - { - (void) munmap (base, share->size); - (void) close (fd); - return -1; - } - - (void) close (fd); - return 0; -} - -int -dmm_fshm_detach (struct dmm_share *share) -{ - (void) munmap (share->base, share->size); - - return 0; -} diff --git a/src/framework/mem/dmm_group.c b/src/framework/mem/dmm_group.c deleted file mode 100644 index 35e6100..0000000 --- a/src/framework/mem/dmm_group.c +++ /dev/null @@ -1,185 +0,0 @@ -/* -* -* 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 <unistd.h> -#include <limits.h> -#include <sys/types.h> -#include <signal.h> -#include <fcntl.h> -#include <sys/mman.h> - -//#include "dmm_memory.h" -#include "dmm_config.h" -#include "dmm_group.h" -#include "dmm_pause.h" - -#define DMM_GROUP_ACTIVE 0x55D5551 -#define DMM_GROUP_GLOBAL "global" -#define DMM_GROUP_ENV "DMM_GROUP" -#define DMM_GROUP_FMT "%s/dmm-group-%s" /* VAR_DIR group-name */ - -static struct flock group_lock = { - .l_type = F_WRLCK, - .l_whence = SEEK_SET, - .l_start = 0, - .l_len = sizeof (struct dmm_group), -}; - -static int group_fd = -1; -struct dmm_group *main_group = NULL; - -inline static const char * -get_group_path () -{ - static char group_path[PATH_MAX] = ""; - - if (!group_path[0]) - { - const char *group = getenv (DMM_GROUP_ENV); - - if (!group || !group[0]) - group = DMM_GROUP_GLOBAL; - - (void) snprintf (group_path, sizeof (group_path), DMM_GROUP_FMT, - DMM_VAR_DIR, group); - group_path[sizeof (group_path) - 1] = 0; - } - - return group_path; -} - -void -dmm_group_active () -{ - main_group->group_init = DMM_GROUP_ACTIVE; -} - -int -dmm_group_create_main () -{ - int ret; - const char *path = get_group_path (); - - group_fd = open (path, O_RDWR | O_CREAT, 0664); - if (group_fd < 0) - { - return -1; - } - - ret = ftruncate (group_fd, sizeof (struct dmm_group)); - if (ret < 0) - { - (void) close (group_fd); - group_fd = -1; - return -1; - } - - ret = fcntl (group_fd, F_SETLK, &group_lock); - if (ret < 0) - { - (void) close (group_fd); - group_fd = -1; - return -1; - } - - main_group = (struct dmm_group *) mmap (NULL, sizeof (struct dmm_group), - PROT_READ | PROT_WRITE, MAP_SHARED, - group_fd, 0); - - if (main_group == MAP_FAILED) - { - (void) close (group_fd); - group_fd = -1; - return -1; - } - - return 0; -} - -int -dmm_group_delete_main () -{ - if (main_group) - { - (void) munmap (main_group, sizeof (struct dmm_group)); - main_group = NULL; - } - - if (group_fd >= 0) - { - (void) close (group_fd); - group_fd = -1; - } - - (void) unlink (get_group_path ()); - - return 0; -} - -int -dmm_group_attach_main () -{ - const char *path = get_group_path (); - - group_fd = open (path, O_RDONLY); - if (group_fd < 0) - { - return -1; - } - - main_group = (struct dmm_group *) mmap (NULL, sizeof (struct dmm_group *), - PROT_READ, MAP_SHARED, group_fd, 0); - if (main_group == MAP_FAILED) - { - (void) close (group_fd); - group_fd = -1; - return -1; - } - - while (main_group->group_init != DMM_GROUP_ACTIVE) - { - dmm_pause (); - } - - if (kill (main_group->share.pid, 0)) - { - (void) munmap (main_group->share.base, main_group->share.size); - (void) close (group_fd); - group_fd = -1; - return -1; - } - - return 0; -} - -int -dmm_group_detach_main () -{ - if (main_group) - { - (void) munmap (main_group, sizeof (struct dmm_group)); - main_group = NULL; - } - - if (group_fd >= 0) - { - (void) close (group_fd); - group_fd = -1; - } - - return 0; -} diff --git a/src/framework/mem/dmm_heap.c b/src/framework/mem/dmm_heap.c deleted file mode 100644 index bc966ef..0000000 --- a/src/framework/mem/dmm_heap.c +++ /dev/null @@ -1,83 +0,0 @@ -/* -* -* 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 <sys/types.h> - -#include "dmm_config.h" -#include "dmm_share.h" - -struct heap_path -{ - void *base; - size_t size; -}; - -int -dmm_heap_create (struct dmm_share *share) -{ - share->base = malloc (share->size); - - if (share->base) - { - struct heap_path *hp = (struct heap_path *) share->path; - hp->base = share->base; - hp->size = share->size; - return 0; - } - - return -1; -} - -int -dmm_heap_delete (struct dmm_share *share) -{ - free (share->base); - return 0; -} - -int -dmm_heap_attach (struct dmm_share *share) -{ - struct heap_path *hp = (struct heap_path *) share->path; - - if (share->base) - { - if (hp->base != share->base) - return -1; - } - else - { - share->base = hp->base; - } - - if (share->size) - { - if (share->size != hp->size) - return -1; - } - else - { - share->size = hp->size; - } - - return 0; -} - -int -dmm_heap_detach (struct dmm_share *share) -{ - return 0; -} diff --git a/src/framework/mem/dmm_huge.c b/src/framework/mem/dmm_huge.c deleted file mode 100644 index 735c507..0000000 --- a/src/framework/mem/dmm_huge.c +++ /dev/null @@ -1,53 +0,0 @@ -/* -* -* 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 <sys/types.h> - -#include "dmm_config.h" -#include "dmm_share.h" - -#define DMM_HUGE_FMT "%s/dmm-%d-%d" /* HUGE_DIR pid index */ - -inline static void -huge_set_path (struct dmm_share *share, int index) -{ - (void) snprintf (share->path, sizeof (share->path), DMM_HUGE_FMT, - DMM_HUGE_DIR, share->pid, index); -} - -int -dmm_huge_create (struct dmm_share *share) -{ - return -1; -} - -int -dmm_huge_delete (struct dmm_share *share) -{ - return -1; -} - -int -dmm_huge_attach (struct dmm_share *share) -{ - return -1; -} - -int -dmm_huge_detach (struct dmm_share *share) -{ - return -1; -} diff --git a/src/framework/mem/dmm_memory.c b/src/framework/mem/dmm_memory.c deleted file mode 100644 index 0352432..0000000 --- a/src/framework/mem/dmm_memory.c +++ /dev/null @@ -1,133 +0,0 @@ -/* -* -* 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 <sys/types.h> -#include <unistd.h> - -#include "dmm_config.h" -#include "dmm_memory.h" -#include "dmm_group.h" - -#define DMM_MEGABYTE (1024 * 1024) - -/* shared from main process */ -static struct dmm_share *main_share = NULL; -struct dmm_segment *main_seg = NULL; - -/* shared by process tree */ -static struct dmm_share base_share = { 0 }; - -struct dmm_segment *base_seg = NULL; - -int -dmm_mem_main_init () -{ - int ret; - - ret = dmm_group_create_main (); - if (ret) - { - return -1; - } - - main_share = &main_group->share; - main_share->type = DMM_MAIN_SHARE_TYPE; - main_share->size = DMM_MAIN_SHARE_SIZE * DMM_MEGABYTE; - main_share->base = NULL; - main_share->pid = getpid (); - ret = dmm_share_create (main_share); - if (ret) - { - return -1; - } - - main_seg = dmm_seg_create (main_share->base, main_share->size); - if (!main_seg) - { - return -1; - } - - dmm_group_active (); - - return 0; -} - -int -dmm_mem_main_exit () -{ - dmm_group_delete_main (); - return 0; -} - -int -dmm_mem_app_init () -{ - int ret; - - ret = dmm_group_attach_main (); - if (0 == ret) - { - main_share = &main_group->share; - ret = dmm_share_attach (main_share); - if (ret) - { - return -1; - } - - main_seg = dmm_seg_attach (main_share->base, main_share->size); - if (!main_seg) - { - return -1; - } - - /* now share main process share-memory */ - base_seg = main_seg; - } - else - { - base_share.type = DMM_SHARE_TYPE; - base_share.size = DMM_SHARE_SIZE * DMM_MEGABYTE; - base_share.base = NULL; - base_share.pid = getpid (); - ret = dmm_share_create (&base_share); - if (ret) - { - return -1; - } - - base_seg = dmm_seg_create (base_share.base, base_share.size); - if (!base_seg) - { - return -1; - } - } - - return 0; -} - -int -dmm_mem_app_exit () -{ - dmm_group_detach_main (); - - if (base_share.base) - dmm_share_delete (&base_share); - - base_share.base = NULL; - base_seg = NULL; - main_seg = NULL; - - return 0; -} diff --git a/src/framework/mem/dmm_memory.h b/src/framework/mem/dmm_memory.h deleted file mode 100644 index 2fac118..0000000 --- a/src/framework/mem/dmm_memory.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* -* 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 _DMM_MEMORY_H_ -#define _DMM_MEMORY_H_ -#include <stdio.h> -#include <stdarg.h> -#include "dmm_share.h" -#include "dmm_segment.h" - -int dmm_mem_main_init (); -int dmm_mem_main_exit (); - -int dmm_mem_app_init (); -int dmm_mem_app_exit (); - -extern struct dmm_segment *main_seg; -extern struct dmm_segment *base_seg; - -inline static void * -dmm_map (size_t size, const char name[DMM_MEM_NAME_SIZE]) -{ - return dmm_mem_map (base_seg, size, name); -} - -inline static void * -dmm_mapv (size_t size, const char *name_fmt, ...) -{ - int len; - char name[DMM_MEM_NAME_SIZE]; - va_list ap; - - va_start (ap, name_fmt); - len = vsnprintf (name, DMM_MEM_NAME_SIZE, name_fmt, ap); - va_end (ap); - - if (len >= DMM_MEM_NAME_SIZE) - return NULL; - - return dmm_map (size, name); -} - -inline static void * -dmm_lookup (const char name[DMM_MEM_NAME_SIZE]) -{ - return dmm_mem_lookup (base_seg, name); -} - -inline static void * -dmm_lookupv (const char *name_fmt, ...) -{ - int len; - char name[DMM_MEM_NAME_SIZE]; - va_list ap; - - va_start (ap, name_fmt); - len = vsnprintf (name, DMM_MEM_NAME_SIZE, name_fmt, ap); - va_end (ap); - - if (len >= DMM_MEM_NAME_SIZE) - return NULL; - - return dmm_mem_lookup (base_seg, name); -} - -#endif /* _DMM_MEMORY_H_ */ diff --git a/src/framework/mem/dmm_nshmem_mng.c b/src/framework/mem/dmm_nshmem_mng.c new file mode 100644 index 0000000..515975c --- /dev/null +++ b/src/framework/mem/dmm_nshmem_mng.c @@ -0,0 +1,126 @@ +/* +* +* 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 "nsfw_mem_api.h" +#include "dmm_ring.h" +#include "dmm_memory.h" +#include "dmm_nshmem_mng.h" + +i32 dmm_nshmem_init(nsfw_mem_para * para) +{ + return NSFW_MEM_OK; +} + +/* + * memory destory + */ +void dmm_nshmem_destory(void) +{ + return; +} + +mzone_handle dmm_nshmem_create(nsfw_mem_zone * pinfo) +{ + if (!pinfo->lenth) + { + return NULL; + } + return calloc(1, pinfo->lenth); +} + +mring_handle dmm_nshmem_spcreate(nsfw_mem_sppool * pmpinfo) +{ + struct dmm_ring *ring; + + ring = + dmm_malloc_pool(pmpinfo->useltsize, (int) pmpinfo->usnum, + DMM_RING_INIT_MPMC); + if (ring == NULL) + { + NSSOC_LOGERR("nshmem sp create faild num:%u eltsize:%u", + pmpinfo->usnum, pmpinfo->useltsize); + return NULL; + } + return (mring_handle) (ring); +} + +i32 dmm_nshmem_sprelease(nsfw_mem_name * pname) +{ + return NSFW_MEM_OK; +} + +mring_handle dmm_nshmem_ringcreate(nsfw_mem_mring * pringinfo) +{ + struct dmm_ring *ring = NULL; + + ring = dmm_malloc_ring((int) pringinfo->usnum, DMM_RING_INIT_MPMC); + if (ring == NULL) + { + NSSOC_LOGERR("nshmem ring create faild num:%u", pringinfo->usnum); + return NULL; + } + return (mring_handle) (ring); +} + +i32 dmm_nshmem_ringrelease(nsfw_mem_name * pname) +{ + return NSFW_MEM_OK; +} + +ssize_t dmm_nshmem_sppool_statics(mring_handle sppool) +{ + size_t size = 0; + struct dmm_ring *ring = (struct dmm_ring *) sppool; + if (ring == NULL) + { + NSSOC_LOGERR("nshmem sppool stat para errer"); + return 0; + } + + size = dmm_ring_bufsize(ring->size - 1); + size = size + dmm_pool_arraysize((ring->size - 1), ring->eltsize); + + return size; +} + +ssize_t dmm_nshmem_ring_statics(mring_handle handle) +{ + struct dmm_ring *ring = (struct dmm_ring *) handle; + if (ring == NULL) + { + NSSOC_LOGERR("nshmem ring stat para errer"); + return 0; + } + + return dmm_ring_bufsize(ring->size - 1); +} + +ssize_t dmm_nshmem_stactic(void *handle, nsfw_mem_struct_type type) +{ + switch (type) + { + case NSFW_MEM_MBUF: + return -1; + case NSFW_MEM_SPOOL: + return dmm_nshmem_sppool_statics(handle); + case NSFW_MEM_RING: + return dmm_nshmem_ring_statics(handle); + default: + break; + } + return -1; +} diff --git a/src/framework/mem/dmm_nshmem_mng.h b/src/framework/mem/dmm_nshmem_mng.h new file mode 100644 index 0000000..d25c365 --- /dev/null +++ b/src/framework/mem/dmm_nshmem_mng.h @@ -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. +*/ + +#ifndef _DMM_NSHMEM_MNG_H +#define _DMM_NSHMEM_MNG_H + +#include "nsfw_mem_api.h" +#include "types.h" +#include <unistd.h> + +i32 dmm_nshmem_init(nsfw_mem_para * para); +void dmm_nshmem_destory(void); +mzone_handle dmm_nshmem_create(nsfw_mem_zone * pinfo); +mring_handle dmm_nshmem_spcreate(nsfw_mem_sppool * pmpinfo); +i32 dmm_nshmem_sprelease(nsfw_mem_name * pname); +mring_handle dmm_nshmem_ringcreate(nsfw_mem_mring * pringinfo); +i32 dmm_nshmem_ringrelease(nsfw_mem_name * pname); +ssize_t dmm_nshmem_sppool_statics(mring_handle sppool); +ssize_t dmm_nshmem_ring_statics(mring_handle handle); +ssize_t dmm_nshmem_stactic(void *handle, nsfw_mem_struct_type type); + +#endif diff --git a/src/framework/mem/dmm_segment.c b/src/framework/mem/dmm_segment.c deleted file mode 100644 index 6358506..0000000 --- a/src/framework/mem/dmm_segment.c +++ /dev/null @@ -1,543 +0,0 @@ -/* -* -* 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 <string.h> -#include "dmm_rwlock.h" -#include "dmm_segment.h" -#include "nstack_log.h" - -#define SECTION_SIZE 64 /* cache line size */ - -#define FIRST_NAME "FIRST SECTION FOR SEGMENT" -#define LAST_NAME "LAST SECTION FOR FREE HEAD" - -#define MEM_ERR(fmt, ...) \ - NS_LOGPID(LOGFW, "DMM-MEM", NSLOG_ERR, fmt, ##__VA_ARGS__) - -/* -init create: - \--total number - /--head no align \ can be used \--tail no align - / ___________________/\___________________ \ -/\/ \/\ -__<F>{S}[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]<L>__ -^ \ /\ /\____________ ________________/\ / -| | | \ / | -| | +--the segment | +--last section(free:0 used:0) -| +--first section(prev_rel:0 used:2 free:11 req_size:sizeof(dmm_segment)) -+--base address - -init: <F>{S}[ ]<L> -alloc A: <F>{S}[ ]<A>#########<L> -alloc B: <F>{S}[ ]<B>#########<A>#########<L> -free A: <F>{S}[ ]<B>#########[ ]<L> -alloc C: <F>{S}[ ]<C>###<B>#########[ ]<L> -*/ - -typedef struct dmm_section -{ - int prev_rel; - int used_num; - int free_num; - int __flags; /* reserved */ - size_t req_size; /* in bytes */ - int less_rel; /* for free list */ - int more_rel; /* for free list */ - char name[DMM_MEM_NAME_SIZE]; -} __attribute__ ((__aligned__ (SECTION_SIZE))) section_t; -SIZE_OF_TYPE_EQUAL_TO (section_t, SECTION_SIZE); - -struct dmm_segment -{ - void *base; /* base address(maybe not align) */ - size_t size; /* full size */ - section_t *first; /* aligned 64 */ - section_t *last; /* last section used to handle free list */ - dmm_rwlock_t lock; - int total_num; /* MAX:2147483647 ==> MAX size: 128M-64 */ - int used_num; - int sec_num; - size_t used_size; /* real alloc size bytes */ -}; - -/* calculate segment number, auto align 64, include 1 section_t */ -inline static int -CALC_NUM (size_t size) -{ - if (size) - { - const size_t MASK = SECTION_SIZE - 1; - return (size + MASK) / SECTION_SIZE + 1; - } - - return 2; /* if size is 0, then alloc 1 block */ -} - -inline static int -SEC_REL (const section_t * base, const section_t * sec) -{ - return sec - base; -} - -section_t * -REL_SEC (section_t * base, int rel) -{ - return base + rel; -} - -inline static int -SEC_INDEX (struct dmm_segment *seg, section_t * sec) -{ - return SEC_REL (seg->first, sec); -} - -inline static section_t * -LESS_SEC (section_t * sec) -{ - return sec + sec->less_rel; -} - -inline static section_t * -MORE_SEC (section_t * sec) -{ - return sec + sec->more_rel; -} - -inline static section_t * -PREV_SEC (section_t * sec) -{ - return sec + sec->prev_rel; -} - -inline static section_t * -NEXT_SEC (section_t * sec) -{ - return sec + (sec->free_num + sec->used_num); -} - -inline static int -CHECK_ADDR (struct dmm_segment *seg, void *mem) -{ - if (mem < (void *) seg->first) - return -1; - if (mem > (void *) seg->last) - return -1; - if ((long) mem & (SECTION_SIZE - 1)) - return -1; - - return 0; -} - -inline static section_t * -mem_lookup (struct dmm_segment *seg, const char name[DMM_MEM_NAME_SIZE]) -{ - section_t *sec; - - /* caller ensures the validity of the name */ - - for (sec = seg->last; sec != seg->first; sec = PREV_SEC (sec)) - { - if (sec->name[0] == 0) - continue; - if (0 == strcmp (sec->name, name)) - return sec; - } - - return NULL; -} - -static section_t * -mem_alloc (struct dmm_segment *seg, size_t size) -{ - const int num = CALC_NUM (size); - section_t *sec, *pos, *next, *less, *more; - - if (num > seg->total_num - seg->used_num) - { - /* no enough memory */ - return NULL; - } - - /* find enough free space */ - pos = seg->last; - do - { - pos = MORE_SEC (pos); - if (pos == seg->last) - { - /* no enough memory */ - return NULL; - } - } - while (num > pos->free_num); - - /* allocate pos pos section tail */ - - /* change next section's prev possion */ - next = NEXT_SEC (pos); - next->prev_rel = -num; - - /* create new section */ - sec = PREV_SEC (next); - sec->prev_rel = SEC_REL (sec, pos); - sec->used_num = num; - sec->req_size = size; - sec->free_num = 0; /* no free space */ - sec->less_rel = 0; - sec->more_rel = 0; - sec->name[0] = 0; - - /* adjust pos */ - pos->free_num -= num; - - less = LESS_SEC (pos); - more = MORE_SEC (pos); - - /* remove pos free list */ - less->more_rel = SEC_REL (less, more); - more->less_rel = SEC_REL (more, less); - pos->more_rel = 0; - pos->less_rel = 0; - - /* find position */ - while (less != seg->last) - { - if (pos->free_num >= less->free_num) - break; - less = LESS_SEC (less); - } - - /* insert into free list */ - more = MORE_SEC (less); - less->more_rel = SEC_REL (less, pos); - more->less_rel = SEC_REL (more, pos); - pos->more_rel = SEC_REL (pos, more); - pos->less_rel = SEC_REL (pos, less); - - /* adjust segment */ - seg->used_size += size; - seg->used_num += num; - seg->sec_num++; - - /* victory */ - return sec; -} - -static void -mem_free (struct dmm_segment *seg, section_t * sec) -{ - const int num = sec->used_num + sec->free_num; - section_t *next = NEXT_SEC (sec); - section_t *prev = PREV_SEC (sec); - section_t *more, *less; - - /* adjust next section's prev */ - next->prev_rel = SEC_REL (next, prev); - - if (sec->free_num) - { - /* remove from free list */ - more = MORE_SEC (sec); - less = LESS_SEC (sec); - more->less_rel = SEC_REL (more, less); - less->more_rel = SEC_REL (less, more); - } - - if (prev->free_num) - { - /* remove from free list */ - more = MORE_SEC (prev); - less = LESS_SEC (prev); - more->less_rel = SEC_REL (more, less); - less->more_rel = SEC_REL (less, more); - } - else - { - more = MORE_SEC (seg->last); - } - - /* put the space to prev's free space */ - prev->free_num += num; - - while (more != seg->last) - { - if (prev->free_num <= more->free_num) - break; - more = MORE_SEC (more); - } - less = LESS_SEC (more); - - /* insert */ - less->more_rel = SEC_REL (less, prev); - more->less_rel = SEC_REL (more, prev); - prev->more_rel = SEC_REL (prev, more); - prev->less_rel = SEC_REL (prev, less); - - /* adjust segment */ - seg->used_size -= sec->req_size; - seg->used_num -= sec->used_num; - seg->sec_num--; -} - -void -dmm_seg_dump (struct dmm_segment *seg) -{ - section_t *sec; - - dmm_read_lock (&seg->lock); - - (void) printf ("---- segment:%p base:%p size:%lu --------------\n" - " first[%d]:%p last[%d]:%p total_num:%d used_num:%d\n" - " sec_num:%d used_size:%lu use%%:%lu%% free%%:%lu%%\n", - seg, seg->base, seg->size, - SEC_INDEX (seg, seg->first), seg->first, - SEC_INDEX (seg, seg->last), seg->last, - seg->total_num, seg->used_num, - seg->sec_num, seg->used_size, - seg->used_size * 100 / seg->size, - (seg->total_num - - seg->used_num) * SECTION_SIZE * 100 / seg->size); - - (void) printf ("----------------------------------------\n" - "%18s %9s %9s %9s %9s %10s %9s %9s %s\n", - "PHYSICAL-ORDER", "section", "prev_rel", "used_num", - "free_num", "req_size", "less_rel", "more_rel", "name"); - - sec = seg->first; - while (1) - { - (void) printf ("%18p %9d %9d %9d %9d %10lu %9d %9d '%s'\n", - sec, SEC_INDEX (seg, sec), - sec->prev_rel, sec->used_num, sec->free_num, - sec->req_size, sec->less_rel, sec->more_rel, sec->name); - if (sec == seg->last) - break; - sec = NEXT_SEC (sec); - } - - (void) printf ("----------------------------------------\n" - "%18s %9s %9s\n", "FREE-ORDER", "section", "free_num"); - for (sec = MORE_SEC (seg->last); sec != seg->last; sec = MORE_SEC (sec)) - { - (void) printf ("%18p %9d %9d\n", - sec, SEC_INDEX (seg, sec), sec->free_num); - } - - (void) printf ("----------------------------------------\n"); - - dmm_read_unlock (&seg->lock); -} - -inline static int -align_section (void *base, size_t size, section_t ** first) -{ - const long MASK = ((long) SECTION_SIZE - 1); - const int SEG_NUM = CALC_NUM (sizeof (struct dmm_segment)); - - const long align = (long) base; - const long addr = (align + MASK) & (~MASK); - const size_t total = (size - (addr - align)) / SECTION_SIZE; - - if (total > 0x7fffFFFF) - return -1; - if (total < SEG_NUM + 1) /* first+segment + last */ - return -1; - - *first = (section_t *) addr; - return (int) total; -} - -struct dmm_segment * -dmm_seg_create (void *base, size_t size) -{ - const int SEG_NUM = CALC_NUM (sizeof (struct dmm_segment)); - section_t *first, *last; - struct dmm_segment *seg; - int total = align_section (base, size, &first); - - if (total <= 0) - return NULL; - - last = first + (total - 1); - - /* first section */ - first->prev_rel = 0; - first->used_num = SEG_NUM; - first->req_size = sizeof (struct dmm_segment); - first->free_num = total - (SEG_NUM + 1); - first->less_rel = SEC_REL (first, last); - first->more_rel = SEC_REL (first, last); - first->name[0] = 0; - (void) strncpy (&first->name[1], FIRST_NAME, sizeof (first->name) - 1); - - /* last section */ - last->prev_rel = SEC_REL (last, first); - last->used_num = 0; - last->req_size = 0; - last->free_num = 0; - last->less_rel = SEC_REL (last, first); - last->more_rel = SEC_REL (last, first); - last->name[0] = 0; - (void) strncpy (&last->name[1], LAST_NAME, sizeof (first->name) - 1); - - /* segment */ - seg = (struct dmm_segment *) (first + 1); - dmm_rwlock_init (&seg->lock); - seg->base = base; - seg->size = size; - seg->first = first; - seg->last = last; - seg->total_num = total; - seg->sec_num = 2; - seg->used_size = sizeof (struct dmm_segment); - seg->used_num = first->used_num; - - return seg; -} - -struct dmm_segment * -dmm_seg_attach (void *base, size_t size) -{ - section_t *first, *last; - struct dmm_segment *seg; - int total = align_section (base, size, &first); - - if (total <= 0) - return NULL; - - last = first + (total - 1); - seg = (struct dmm_segment *) (first + 1); - - if (seg->base != base) - return NULL; - if (seg->size != size) - return NULL; - if (seg->total_num != total) - return NULL; - - if (seg->first != first) - return NULL; - if (first->name[0] != 0) - return NULL; - if (strncmp (&first->name[1], FIRST_NAME, sizeof (first->name) - 1)) - return NULL; - - if (seg->last != last) - return NULL; - if (last->name[0] != 0) - return NULL; - if (strncmp (&last->name[1], LAST_NAME, sizeof (last->name) - 1)) - return NULL; - - return seg; -} - -void * -dmm_mem_alloc (struct dmm_segment *seg, size_t size) -{ - section_t *sec; - - dmm_write_lock (&seg->lock); - sec = mem_alloc (seg, size); - dmm_write_unlock (&seg->lock); - - return sec ? sec + 1 : NULL; -} - -int -dmm_mem_free (struct dmm_segment *seg, void *mem) -{ - if (CHECK_ADDR (seg, mem)) - { - MEM_ERR ("Invalid address:%p", mem); - return -1; - } - - dmm_write_lock (&seg->lock); - mem_free (seg, ((section_t *) mem) - 1); - dmm_write_unlock (&seg->lock); - - return 0; -} - -void * -dmm_mem_lookup (struct dmm_segment *seg, const char name[DMM_MEM_NAME_SIZE]) -{ - section_t *sec; - - if (!name || !name[0]) - return NULL; - - dmm_read_lock (&seg->lock); - sec = mem_lookup (seg, name); - dmm_read_unlock (&seg->lock); - - return sec ? sec + 1 : NULL; -} - -void * -dmm_mem_map (struct dmm_segment *seg, size_t size, - const char name[DMM_MEM_NAME_SIZE]) -{ - void *mem; - section_t *sec; - - if (!name || !name[0] || strlen (name) >= DMM_MEM_NAME_SIZE) - return NULL; - - dmm_write_lock (&seg->lock); - - sec = mem_lookup (seg, name); - if (sec) - { - MEM_ERR ("Map '%s' exist", name); - mem = NULL; - } - else if (!(sec = mem_alloc (seg, size))) - { - MEM_ERR ("alloc '%s' failed for size %lu", name, size); - mem = NULL; - } - else - { - (void) strncpy (sec->name, name, sizeof (sec->name)); - mem = sec + 1; - } - - dmm_write_unlock (&seg->lock); - - return mem; -} - -int -dmm_mem_unmap (struct dmm_segment *seg, const char name[DMM_MEM_NAME_SIZE]) -{ - section_t *sec; - - if (!name || !name[0]) - return -1; - - dmm_write_lock (&seg->lock); - - sec = mem_lookup (seg, name); - if (sec) - mem_free (seg, sec); - - dmm_write_unlock (&seg->lock); - - return sec != NULL ? 0 : -1; -} diff --git a/src/framework/mem/dmm_shmem_mng.c b/src/framework/mem/dmm_shmem_mng.c new file mode 100644 index 0000000..7dee6dc --- /dev/null +++ b/src/framework/mem/dmm_shmem_mng.c @@ -0,0 +1,287 @@ +/* +* +* 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_mem_api.h" +#include "dmm_memory.h" +#include "dmm_ring.h" +#include "dmm_shmem_mng.h" +#include "nstack_securec.h" + +/* + *share memory mng module init + * + */ +i32 dmm_shmem_init(nsfw_mem_para * para) +{ + i32 iret = NSFW_MEM_OK; + + NSSOC_LOGINF("shmem init begin"); + + if (NSFW_PROC_APP != para->enflag) + { + NSSOC_LOGERR("shmem init with error proc type"); + return NSFW_MEM_ERR; + } + else + { + iret = dmm_mem_module_init((void *) ((u64) (para->enflag))); + } + + if (NSFW_MEM_OK != iret) + { + NSSOC_LOGERR("shmem init fail]ret=0x%x", iret); + return NSFW_MEM_RTP_FAIL; + } + + NSRTP_LOGINF("shmem init end]flag=%d", para->enflag); + return NSFW_MEM_OK; +} + +/* + *module destroy + */ +void dmm_shmem_destroy(void) +{ + (void) dmm_share_destroy(); + + return; +} + +/* + * create a shared memory + * nsfw_mem_zone::stname memory name + * nsfw_mem_zone::isize + */ +mzone_handle dmm_shmem_create(nsfw_mem_zone * pinfo) +{ + return dmm_locked_map(pinfo->lenth, pinfo->stname.aname); +} + +/* + *create some memory + *inum must be equal iarray_num + */ +i32 dmm_shmem_createv(nsfw_mem_zone * pmeminfo, i32 inum, + mzone_handle * paddr_array, i32 iarray_num) +{ + return NSFW_MEM_OK; +} + +mzone_handle dmm_shmem_lookup(nsfw_mem_name * pname) +{ + return dmm_lookup(pname->aname); +} + +i32 dmm_shmem_release(nsfw_mem_name * pname) +{ + void *ptr = NULL; + + ptr = dmm_lookup(pname->aname); + if (ptr == NULL) + { + NSSOC_LOGERR("shmem[%s] release fail", pname->aname); + return NSFW_MEM_ERR; + } + + return dmm_unmap(ptr); +} + +mpool_handle dmm_shmem_mbfmpcreate(nsfw_mem_mbfpool * pbufinfo) +{ + return NULL; +} + +/* + *create some mbuf pools + */ +i32 dmm_shmem_mbfmpcreatev(nsfw_mem_mbfpool * pmbfname, i32 inum, + mpool_handle * phandle_array, i32 iarray_num) +{ + return 0; +} + +mpool_handle dmm_shmem_mbfmplookup(nsfw_mem_name * pmbfname) +{ + return NULL; +} + +i32 dmm_shmem_mbfmprelease(nsfw_mem_name * pname) +{ + return NSFW_MEM_OK; +} + +mring_handle dmm_shmem_spcreate(nsfw_mem_sppool * pmpinfo) +{ + struct dmm_ring *ring; + + ring = + dmm_create_pool(pmpinfo->useltsize, (int) pmpinfo->usnum, + DMM_RING_INIT_MPMC, pmpinfo->stname.aname); + if (ring == NULL) + { + NSSOC_LOGERR("shmem sp create faild num:%u eltsize:%u", + pmpinfo->usnum, pmpinfo->useltsize); + return NULL; + } + + return (mring_handle) (ring); +} + +i32 dmm_shmem_spcreatev(nsfw_mem_sppool * pmpinfo, i32 inum, + mring_handle * pringhandle_array, i32 iarray_num) +{ + return NSFW_MEM_OK; +} + +i32 dmm_shmem_sp_ringcreate(nsfw_mem_mring * prpoolinfo, + mring_handle * pringhandle_array, i32 iringnum) +{ + i32 i = 0; + size_t eltsize = 0; + mring_handle ring = NULL; + size_t ring_size = 0; + nsfw_mem_sppool mpinfo; + char *pool = NULL; + + eltsize = dmm_ring_bufsize((int) prpoolinfo->usnum); + mpinfo.useltsize = eltsize; + mpinfo.usnum = iringnum; + (void) strncpy_s(mpinfo.stname.aname, sizeof(mpinfo.stname.aname), + prpoolinfo->stname.aname, + sizeof(mpinfo.stname.aname) - 1); + + ring = dmm_shmem_spcreate(&mpinfo); + if (ring == NULL) + { + NSSOC_LOGERR("shmem spring create faild num:%u eltsize:%u", + mpinfo.usnum, mpinfo.useltsize); + return NSFW_MEM_ERR; + } + + ring_size = dmm_ring_bufsize(iringnum); + pool = (char *) ring + ring_size; + for (i = 0; i < iringnum; i++) + { + pringhandle_array[i] = pool; + if (0 != + dmm_ring_init((struct dmm_ring *) pringhandle_array[i], + (int) prpoolinfo->usnum, eltsize, + DMM_RING_INIT_MPMC, NSFW_SHMEM)) + { + NSSOC_LOGERR("ring init faild index:%d", i); + return NSFW_MEM_ERR; + } + pool = pool + eltsize; + } + + return NSFW_MEM_OK; +} + +i32 dmm_shmem_sprelease(nsfw_mem_name * pname) +{ + return dmm_shmem_release(pname); +} + +mring_handle dmm_shmem_sp_lookup(nsfw_mem_name * pname) +{ + return dmm_lookup(pname->aname); +} + +mring_handle dmm_shmem_ringcreate(nsfw_mem_mring * pringinfo) +{ + struct dmm_ring *ring; + + ring = + dmm_create_ring((int) pringinfo->usnum, DMM_RING_INIT_MPMC, + pringinfo->stname.aname); + + return (mring_handle) (ring); +} + +mring_handle dmm_shmem_ring_lookup(nsfw_mem_name * pname) +{ + return dmm_lookup(pname->aname); +} + +i32 dmm_shmem_ringrelease(nsfw_mem_name * pname) +{ + return dmm_shmem_release(pname); +} + +size_t dmm_shmem_sppool_statics(mring_handle sppool) +{ + size_t size = 0; + struct dmm_ring *ring = (struct dmm_ring *) sppool; + if (ring == NULL) + { + NSSOC_LOGERR("shmem sppool stat para errer"); + return 0; + } + + size = dmm_ring_bufsize(ring->size - 1); + size = size + dmm_pool_arraysize((ring->size - 1), ring->eltsize); + + return size; +} + +size_t dmm_shmem_ring_statics(mring_handle handle) +{ + struct dmm_ring *ring = (struct dmm_ring *) handle; + if (ring == NULL) + { + NSSOC_LOGERR("shmem ring stat para errer"); + return 0; + } + + return dmm_ring_bufsize(ring->size - 1); +} + +ssize_t dmm_shmem_stactic(void *handle, nsfw_mem_struct_type type) +{ + switch (type) + { + case NSFW_MEM_MBUF: + return 0; + case NSFW_MEM_SPOOL: + return dmm_shmem_sppool_statics(handle); + case NSFW_MEM_RING: + return dmm_shmem_ring_statics(handle); + default: + break; + } + return -1; +} + +i32 dmm_shmem_sp_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv) +{ + return 0; +} + +void *dmm_shmem_shddr_to_laddr(void *addr) +{ + return addr; +} + +uint64_t dmm_shmem_laddr_to_shddr(void *addr) +{ + return (uint64_t) (addr); +} + +int dmm_attach_core_id(nsfw_mem_name * name) +{ + return 0; +} diff --git a/src/framework/mem/dmm_shmem_mng.h b/src/framework/mem/dmm_shmem_mng.h new file mode 100644 index 0000000..c267858 --- /dev/null +++ b/src/framework/mem/dmm_shmem_mng.h @@ -0,0 +1,54 @@ +/* +* +* 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 _DMM_SHMEM_MNG_H +#define _DMM_SHMEM_MNG_H + +#include <unistd.h> +#include <stdlib.h> +#include "nsfw_mem_api.h" +#include "types.h" + +i32 dmm_shmem_init(nsfw_mem_para * para); +void dmm_shmem_destroy(void); +mzone_handle dmm_shmem_create(nsfw_mem_zone * pinfo); +i32 dmm_shmem_createv(nsfw_mem_zone * pmeminfo, i32 inum, + mzone_handle * paddr_array, i32 iarray_num); +mzone_handle dmm_shmem_lookup(nsfw_mem_name * pname); +i32 dmm_shmem_release(nsfw_mem_name * pname); +mpool_handle dmm_shmem_mbfmpcreate(nsfw_mem_mbfpool * pbufinfo); +i32 dmm_shmem_mbfmpcreatev(nsfw_mem_mbfpool * pmbfname, i32 inum, + mpool_handle * phandle_array, i32 iarray_num); +mpool_handle dmm_shmem_mbfmplookup(nsfw_mem_name * pmbfname); +i32 dmm_shmem_mbfmprelease(nsfw_mem_name * pname); +i32 dmm_shmem_spcreatev(nsfw_mem_sppool * pmpinfo, i32 inum, + mring_handle * pringhandle_array, i32 iarray_num); +i32 dmm_shmem_sp_ringcreate(nsfw_mem_mring * prpoolinfo, + mring_handle * pringhandle_array, i32 iringnum); +i32 dmm_shmem_sprelease(nsfw_mem_name * pname); +mring_handle dmm_shmem_sp_lookup(nsfw_mem_name * pname); +mring_handle dmm_shmem_ringcreate(nsfw_mem_mring * pringinfo); +mring_handle dmm_shmem_ring_lookup(nsfw_mem_name * pname); +i32 dmm_shmem_ringrelease(nsfw_mem_name * pname); +size_t dmm_shmem_sppool_statics(mring_handle sppool); +size_t dmm_shmem_ring_statics(mring_handle handle); +ssize_t dmm_shmem_stactic(void *handle, nsfw_mem_struct_type type); +i32 dmm_shmem_sp_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv); +void *dmm_shmem_shddr_to_laddr(void *addr); +uint64_t dmm_shmem_laddr_to_shddr(void *addr); +int dmm_attach_core_id(nsfw_mem_name * name); +#endif diff --git a/src/framework/mem/nsfw_mem_api.c b/src/framework/mem/nsfw_mem_api.c new file mode 100644 index 0000000..7517faa --- /dev/null +++ b/src/framework/mem/nsfw_mem_api.c @@ -0,0 +1,932 @@ +/* +* +* 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 <sys/types.h> +#include <unistd.h> +#include <dlfcn.h> +#include "nsfw_mem_api.h" +#include "nstack_securec.h" +#include "nsfw_ring_data.h" +#include "nsfw_init_api.h" + +#define MEM_OP_CALL_OK_RET(mtype, fun, para) { \ + if (g_nsfw_mem_ops[mtype].stmemop->fun) \ + { \ + return g_nsfw_mem_ops[mtype].stmemop->fun para; \ + } \ + } +#define NSFW_MEM_NAME_CHECK_RET_ERR(pname, desc) {\ + if ((NULL == (pname)) || ((pname)->entype >= NSFW_MEM_TYPEMAX)) \ + { \ + NSRTP_LOGERR("input para error]desc=%s,pname=%p,mtype=%d", desc, pname, (pname) ? (pname)->entype:-1); \ + return NSFW_MEM_ERR; \ + } \ + } + +#define NSFW_MEM_NAME_CHECK_RET_NULL(pname, desc) {\ + if ((NULL == (pname)) || ((pname)->entype >= NSFW_MEM_TYPEMAX)) \ + { \ + NSRTP_LOGERR("input para error]desc=%s,pname=%p,mtype=%d", desc, pname, (pname) ? (pname)->entype:-1); \ + return NULL; \ + } \ + } + +#define NSFW_MEM_RING_CHECK_RET(pringinfo, pringhandle_array, iringnum) {\ + if ((NULL == pringinfo) || (NULL == pringhandle_array) || (pringinfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) \ + { \ + NSRTP_LOGERR("input para error]pringinfo=%p,iringnum=%d,pringhandle_array=%p,mtype=%d", \ + pringinfo, iringnum, pringhandle_array, pringinfo ? pringinfo[0].stname.entype : (-1)); \ + return NSFW_MEM_ERR; \ + } \ + } + +#define NSFW_MEM_RINGV_CHECK_RET(pmpinfo, inum, pringhandle_array, iarray_num) { \ + if ((NULL == pmpinfo) || (NULL == pringhandle_array) \ + || (inum != iarray_num) || (inum <= 0) || (pmpinfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) \ + { \ + NSRTP_LOGERR("input para error]pmpinfo=%p,inum=%d,pringhandle_array=%p,iarray_num=%d,entype=%d", \ + pmpinfo, inum, pringhandle_array, iarray_num, pmpinfo ? pmpinfo[0].stname.entype : (-1)); \ + return NSFW_MEM_ERR; \ + } \ + } + +#ifndef FOR_ATTACH_COREID +/* + * attach core id when malloc resource + */ +static int nsfw_attach_core_id(nsfw_mem_name * name) +{ + MEM_OP_CALL_OK_RET(NSFW_SHMEM, mem_ops_attach_core_id, (name)); + NSRTP_LOGINF + ("nsfw_attach_core_id failed]field mem_ops_attach_core_id is NULL"); + return -1; +} +#endif + +i32 nsfw_mem_init(void *para) +{ + nsfw_mem_para *ptempara = NULL; + i32 iret = NSFW_MEM_OK; + i32 icount = 0; + i32 iindex = 0; + + if (NULL == para) + { + NSRTP_LOGERR("ns mem init input error"); + return NSFW_MEM_ERR; + } + + ptempara = (nsfw_mem_para *) para; + + if (ptempara->enflag >= NSFW_PROC_MAX) + { + NSRTP_LOGERR("ns mem init input enflag invalid]enflag=%d", + ptempara->enflag); + return NSFW_MEM_ERR; + } + + NSRTP_LOGINF("ns mem init begin]enflag=%d,iargsnum=%d", ptempara->enflag, + ptempara->iargsnum); + + for (iindex = 0; iindex < ptempara->iargsnum; iindex++) + { + NSRTP_LOGINF("%s", ptempara->pargs[iindex]); + } + + for (icount = 0; icount < g_mem_type_num; icount++) + { + if ((NULL != g_nsfw_mem_ops[icount].stmemop) + && (NULL != g_nsfw_mem_ops[icount].stmemop->mem_ops_init)) + { + iret = g_nsfw_mem_ops[icount].stmemop->mem_ops_init(ptempara); + + if (NSFW_MEM_OK != iret) + { + NSRTP_LOGERR("mem init failed]index=%d,memtype=%d", icount, + g_nsfw_mem_ops[icount].entype); + break; + } + } + } + + /* if some module init fail, destory the modules that succeeded */ + if (icount < g_mem_type_num) + { + for (iindex = 0; iindex < icount; iindex++) + { + if (g_nsfw_mem_ops[icount].stmemop->mem_ops_destroy) + { + g_nsfw_mem_ops[icount].stmemop->mem_ops_destroy(); + } + } + + return iret; /* return errcode to caller */ + } + + NSRTP_LOGINF("mem init end"); + return NSFW_MEM_OK; +} + +/***************************************************************************** +* Prototype : nsfw_mem_zone_create +* Description : create a block memory with name +* nsfw_mem_zone::stname +* nsfw_mem_zone::isize +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_zone* pinfo +* Output : None +* Return Value : mzone_handle +* Calls : +* Called By : +*****************************************************************************/ +mzone_handle nsfw_mem_zone_create(nsfw_mem_zone * pinfo) +{ + if ((NULL == pinfo) || (pinfo->stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR("zone create input para error] pinfo=%p, mtype=%d", + pinfo, pinfo ? pinfo->stname.entype : (-1)); + return NULL; + } + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(&pinfo->stname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pinfo->stname.entype, mem_ops_zone_creae, (pinfo)); + NSRTP_LOGINF("mem create fail] memtype=%d, name=%s, size=%zu", + pinfo->stname.entype, pinfo->stname.aname, pinfo->lenth); + return NULL; +} + +/***************************************************************************** +* Prototype : nsfw_mem_zone_createv +* Description : create some memory blocks +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_zone* pmeminfo +* i32 inum +* mzone_handle* paddr_array +* i32 iarray_num +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_zone_createv(nsfw_mem_zone * pmeminfo, i32 inum, + mzone_handle * paddr_array, i32 iarray_num) +{ + if ((NULL == pmeminfo) || (NULL == paddr_array) + || (inum != iarray_num) || (inum <= 0) + || (pmeminfo[0].stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR + ("input para error] pmeminfo=%p, inum=%d, paddr_array=%p, iarray_num=%d, mtype=%d", + pmeminfo, inum, paddr_array, iarray_num, + pmeminfo ? pmeminfo[0].stname.entype : (-1)); + return NSFW_MEM_ERR; + } + +#ifndef FOR_ATTACH_COREID + i32 i; + for (i = 0; i < inum; ++i) + { + if (nsfw_attach_core_id(&pmeminfo[i].stname) != 0) + { + return NSFW_MEM_ERR; + } + } +#endif + + MEM_OP_CALL_OK_RET(pmeminfo[0].stname.entype, mem_ops_zone_createv, + (pmeminfo, inum, paddr_array, iarray_num)); + NSRTP_LOGINF("mem create fail] memtype=%d", pmeminfo[0].stname.entype); + return NSFW_MEM_ERR; +} + +/***************************************************************************** +* Prototype : nsfw_mem_zone_lookup +* Description : look up a memory +* 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* 2. if the memory is shared, pname->enowner indicate that who create this memory. +* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, +* end with none created by nStackMaster, and end with _<pid> created by other. +* 2. pname->enowner is available only when call look up shared memory. +* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, +* the name must be full name. +* for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, +* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add +* _(pid) at the end of name, nstack_123. +* Input : nsfw_mem_name* pname +* Output : None +* Return Value : mzone_handle +* Calls : +* Called By : +*****************************************************************************/ +mzone_handle nsfw_mem_zone_lookup(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_NULL(pname, "mem zone look up"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_zone_lookup, (pname)); + NSRTP_LOGERR("mem lookup fail] memtype=%d, name=%s ", pname->entype, + pname->aname); + return NULL; +} + +i32 nsfw_mem_zone_release(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_ERR(pname, "mem zone release"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NSFW_MEM_ERR; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_mzone_release, (pname)); + NSRTP_LOGERR("mem release fail] memtype=%d, name=%s", pname->entype, + pname->aname); + return NSFW_MEM_ERR; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_mbfmp_create +* Description : create a mbuf pool +* Input : nsfw_mem_mbfpool* pbufinfo +* Output : None +* Return Value : mpool_handle +* Calls : +* Called By : +*****************************************************************************/ +mpool_handle nsfw_mem_mbfmp_create(nsfw_mem_mbfpool * pbufinfo) +{ + if ((NULL == pbufinfo) || (pbufinfo->stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR("input para error] pbufinfo=%p, mtype=%d", pbufinfo, + pbufinfo ? pbufinfo->stname.entype : (-1)); + return NULL; + } + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(&pbufinfo->stname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pbufinfo->stname.entype, mem_ops_mbfmp_create, + (pbufinfo)); + NSRTP_LOGERR("mbufmp create fail] memtype=%d, name=%s ", + pbufinfo->stname.entype, pbufinfo->stname.aname); + return NULL; +} + +/***************************************************************************** +* Prototype : nsfw_mem_mbfmp_createv +* Description : create some mbuf pools +* 1. the name of lenth must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_mbfpool* pmbfname +* i32 inum +* mpool_handle* phandle_array +* i32 iarray_num +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_mbfmp_createv(nsfw_mem_mbfpool * pmbfname, i32 inum, + mpool_handle * phandle_array, i32 iarray_num) +{ + if ((NULL == pmbfname) || (NULL == phandle_array) + || (inum != iarray_num) || (inum <= 0) + || (pmbfname[0].stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR + ("input para error] pmbfname=%p, inum=%d, phandle_array=%p, iarray_num=%d,entype=%d", + pmbfname, inum, phandle_array, iarray_num, + pmbfname ? pmbfname[0].stname.entype : (-1)); + return NSFW_MEM_ERR; + } + +#ifndef FOR_ATTACH_COREID + i32 i; + for (i = 0; i < inum; ++i) + { + if (nsfw_attach_core_id(&pmbfname[i].stname) != 0) + { + return NSFW_MEM_ERR; + } + } +#endif + + MEM_OP_CALL_OK_RET(pmbfname[0].stname.entype, mem_ops_mbfmp_createv, + (pmbfname, inum, phandle_array, iarray_num)); + NSRTP_LOGERR("mbufmp createv fail] memtype=%d", + pmbfname[0].stname.entype); + return NSFW_MEM_ERR; +} + +/***************************************************************************** +* Prototype : nsfw_mem_mbfmp_lookup +* Description : look up mbuf mpool +* 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* 2. if the memory is shared, pname->enowner indicate that who create this memory. +* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, +* end with none created by nStackMaster, and end with _<pid> created by other. +* 2. pname->enowner is available only when call look up shared memory. +* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, +* the name must be full name. +* for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, +* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add +* _(pid) at the end of name, nstack_123. +* Input : nsfw_mem_name* pmbfname +* Output : None +* Return Value : mpool_handle +* Calls : +* Called By : +*****************************************************************************/ +mpool_handle nsfw_mem_mbfmp_lookup(nsfw_mem_name * pmbfname) +{ + NSFW_MEM_NAME_CHECK_RET_NULL(pmbfname, "mbuf pool look up"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pmbfname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pmbfname->entype, mem_ops_mbfmp_lookup, (pmbfname)); + NSRTP_LOGERR("mbufmp lookup fail] memtype=%d, name=%s ", + pmbfname->entype, pmbfname->aname); + return NULL; +} + +/***************************************************************************** +* Prototype : nsfw_mem_mbfmp_release +* Description : release mbuf pool +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_name* pname +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_mbfmp_release(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_ERR(pname, "mbuf mp release"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NSFW_MEM_ERR; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_mbfmp_release, (pname)); + NSRTP_LOGERR("mbfmp release fail] memtype=%d, name=%s", pname->entype, + pname->aname); + return NSFW_MEM_ERR; +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_create +* Description : create a simple pool +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_sppool* pmpinfo +* Output : None +* Return Value : mring_handle +* Calls : +* Called By : +*****************************************************************************/ +mring_handle nsfw_mem_sp_create(nsfw_mem_sppool * pmpinfo) +{ + if ((NULL == pmpinfo) || (pmpinfo->stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR("input para error] pmpinfo=%p, mtype=%d", pmpinfo, + pmpinfo ? pmpinfo->stname.entype : (-1)); + return NULL; + } + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(&pmpinfo->stname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pmpinfo->stname.entype, mem_ops_sp_create, (pmpinfo)); + NSRTP_LOGERR("sp create fail] memtype=%d, name=%s ", + pmpinfo->stname.entype, pmpinfo->stname.aname); + return NULL; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_createv +* Description : create some simple pools one time +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_sppool* pmpinfo +* i32 inum +* mring_handle* pringhandle_array +* i32 iarray_num +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_sp_createv(nsfw_mem_sppool * pmpinfo, i32 inum, + mring_handle * pringhandle_array, i32 iarray_num) +{ + NSFW_MEM_RINGV_CHECK_RET(pmpinfo, inum, pringhandle_array, iarray_num); + +#ifndef FOR_ATTACH_COREID + i32 i; + for (i = 0; i < inum; ++i) + { + if (nsfw_attach_core_id(&pmpinfo[i].stname) != 0) + { + return NSFW_MEM_ERR; + } + } +#endif + + MEM_OP_CALL_OK_RET(pmpinfo[0].stname.entype, mem_ops_sp_createv, + (pmpinfo, inum, pringhandle_array, iarray_num)); + NSRTP_LOGERR("sp createv fail] memtype=%d", pmpinfo[0].stname.entype); + return NSFW_MEM_ERR; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_ring_create +* Description : create a simple pool with many rings +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_mring* pringinfo +* mring_handle* pringhandle_array +* i32 iringnum +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_sp_ring_create(nsfw_mem_mring * pringinfo, + mring_handle * pringhandle_array, i32 iringnum) +{ + NSFW_MEM_RING_CHECK_RET(pringinfo, pringhandle_array, iringnum); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(&pringinfo->stname) != 0) + { + return NSFW_MEM_ERR; + } +#endif + + MEM_OP_CALL_OK_RET(pringinfo[0].stname.entype, mem_ops_spring_create, + (pringinfo, pringhandle_array, iringnum)); + NSRTP_LOGERR("mppool spring creat fail] memtype=%d", + pringinfo[0].stname.entype); + return NSFW_MEM_ERR; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_release +* Description : release a simple mempool +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* Input : nsfw_mem_name* pname +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_sp_release(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_ERR(pname, "sp release"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NSFW_MEM_ERR; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_sp_release, (pname)); + NSRTP_LOGERR("sp release fail] memtype=%d, name=%s ", pname->entype, + pname->aname); + return NSFW_MEM_ERR; +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_lookup +* Description : look up a simpile ring +* 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* 2. if the memory is shared, pname->enowner indicate that who create this memory. +* note : 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, +* end with none created by nStackMaster, and end with _<pid> created by other. +* 2. pname->enowner is available only when call look up shared memory. +* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, +* the name must be full name. +* for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, +* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add +* _(pid) at the end of name, nstack_123. +* Input : nsfw_mem_name* pname +* Output : None +* Return Value : mring_handle +* Calls : +* Called By : +*****************************************************************************/ +mring_handle nsfw_mem_sp_lookup(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_NULL(pname, "sp look up"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_sp_lookup, (pname)); + NSRTP_LOGERR("sp lookup fail] memtype=%d, name=%s", pname->entype, + pname->aname); + return NULL; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_ring_create +* Description : create a ring +* note : 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* 2. shared memory ring (NSFW_SHMEM) just can put a pointor into the queue, the queue also point to a shared block memory. +* no shared memory ring(NSFW_NSHMEM) is other wise. +* Input : nsfw_mem_mring* pringinfo +* Output : None +* Return Value : mring_handle +* Calls : +* Called By : +*****************************************************************************/ +mring_handle nsfw_mem_ring_create(nsfw_mem_mring * pringinfo) +{ + if ((NULL == pringinfo) || (pringinfo->stname.entype >= NSFW_MEM_TYPEMAX)) + { + NSRTP_LOGERR("input para error] pmpinfo=%p, mtype=%d", pringinfo, + pringinfo ? pringinfo->stname.entype : (-1)); + return NULL; + } + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(&pringinfo->stname) != 0) + { + NSRTP_LOGERR + ("nsfw_attach_core_id failed] type=%d, owner=%d, name=%s", + pringinfo->stname.entype, pringinfo->stname.enowner, + pringinfo->stname.aname); + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pringinfo->stname.entype, mem_ops_ring_create, + (pringinfo)); + NSRTP_LOGERR("ring create fail] memtype=%d, name=%s ", + pringinfo->stname.entype, pringinfo->stname.aname); + return NULL; +} + +/***************************************************************************** +* Prototype : nsfw_mem_ring_lookup +* Description : look up a ring by name +* 1. the lenth of name must be less than NSFW_MEM_APPNAME_LENTH. +* 2. if the memory is shared, pname->enowner indicate that who create this memory. +* note: +* 1. when calling any shared memory create inferface, the name of memory end with _0 created by daemon-stack, +* end with none created by nStackMaster, and end with _<pid> created by other. +* 2. pname->enowner is available only when call look up shared memory. +* 3. if the roles of process is NSFW_PROC_MASTER but the memory was created by others, or pname->enowner is NSFW_PROC_NULL, +* the name must be full name. +* for examles if the memory was created by daemon-stack and pname->enowner is NSFW_PROC_NULL, +* must add '_0' at the end of name, if the memory was created by app and the role of process is NSFW_PROC_MASTER, must add +* _(pid) at the end of name, nstack_123. +* Input : nsfw_mem_name* pname +* Output : None +* Return Value : mring_handle +* Calls : +* Called By : +*****************************************************************************/ +mring_handle nsfw_mem_ring_lookup(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_NULL(pname, "ring lookup"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NULL; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_ring_lookup, (pname)); + NSRTP_LOGERR("ring lookup fail] memtype=%d, name=%s", pname->entype, + pname->aname); + return NULL; +} + +/***************************************************************************** +* Prototype : nsfw_mem_ring_reset +* Description : reset the number of producer and consumer, also, the +* state of ring reset to empty +* notes : must be called before doing any operations base on the ring +* Input : mring_handle mhandle +* nsfw_mpool_type entype +* Output : None +* Return Value : void +* Calls : +* Called By : +*****************************************************************************/ +void nsfw_mem_ring_reset(mring_handle mhandle, nsfw_mpool_type entype) +{ + u32 loop = 0; + struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) mhandle; + + if (!ring) + { + return; + } + + ring->prod.head = 0; + ring->cons.tail = 0; + ring->ringflag = (u8) entype; + + /*init Ring */ + for (loop = 0; loop < ring->size; loop++) + { + /* + for a empty ring, version is the mapping head val - size + so the empty ring's ver is loop-size; + */ + ring->ring[loop].data_s.ver = (loop - ring->size); + ring->ring[loop].data_s.val = 0; + } + + return; +} + +/***************************************************************************** +* Prototype : nsfw_mem_ring_free_count +* Description : get the free number of ring +* Input : mring_handle mhandle +* Output : None +* Return Value : u32 +* Calls : +* Called By : +*****************************************************************************/ +u32 nsfw_mem_ring_free_count(mring_handle mhandle) +{ + struct nsfw_mem_ring *temp = NULL; + u32 thead = 0; + u32 ttail = 0; + u32 using_count = 0; + if (NULL == mhandle) + { + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return 0; + } + + temp = (struct nsfw_mem_ring *) mhandle; + + /* avoid multi-thread issue, here we should get cons.tail firstly, get prod.head later + because tail and head is always ++ */ + /* optimize nsfw_mem_ring_using_count(), avoid return abnormal value */ + ttail = temp->cons.tail; + thead = temp->prod.head; + + using_count = thead - ttail; + if (using_count > temp->size) + { + /* nsfw_mem_ring_using_count will return abnormal lagre value */ + using_count = 0; + } + + return temp->size - (using_count); +} + +/***************************************************************************** +* Prototype : nsfw_mem_ring_using_count +* Description : get the in using number of ring +* Input : mring_handle mhandle +* Output : None +* Return Value : u32 +* Calls : +* Called By : +*****************************************************************************/ +u32 nsfw_mem_ring_using_count(mring_handle mhandle) +{ + struct nsfw_mem_ring *temp = NULL; + u32 thead = 0; + u32 ttail = 0; + u32 using_count = 0; + if (NULL == mhandle) + { + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return 0; + } + + temp = (struct nsfw_mem_ring *) mhandle; + /* avoid multi-thread issue, here we should get cons.tail firstly, get prod.head later + because tail and head is always ++ */ + /* optimize nsfw_mem_ring_using_count(), avoid return abnormal value */ + + ttail = temp->cons.tail; + thead = temp->prod.head; + + using_count = thead - ttail; + if (using_count > temp->size) + { + /* nsfw_mem_ring_using_count will return abnormal lagre value */ + using_count = 0; + } + + return using_count; +} + +u32 nsfw_mem_ring_size(mring_handle mhandle) +{ + struct nsfw_mem_ring *temp = NULL; + + if (NULL == mhandle) + { + NSRTP_LOGERR("input para error] mhandle=%p", mhandle); + return 0; + } + + temp = (struct nsfw_mem_ring *) mhandle; + + return temp->size; +} + +i32 nsfw_mem_ring_release(nsfw_mem_name * pname) +{ + NSFW_MEM_NAME_CHECK_RET_ERR(pname, "ring release"); + +#ifndef FOR_ATTACH_COREID + if (nsfw_attach_core_id(pname) != 0) + { + return NSFW_MEM_ERR; + } +#endif + + MEM_OP_CALL_OK_RET(pname->entype, mem_ops_ring_release, (pname)); + NSRTP_LOGERR("ring release fail] name=%s, type=%d", pname->aname, + pname->entype); + return NSFW_MEM_ERR; + +} + +/***************************************************************************** +* Prototype : nsfw_mem_get_len +* Description : statics mbufpool, sppool, ring mem size. +* return: <=0, err happen, >0 mem size +* NSFW_MEM_MZONE: not surport because you already know the lenth when create +* Input : void * handle +* nsfw_mem_struct_type type +* Output : None +* Return Value : ssize_t +* Calls : +* Called By : +*****************************************************************************/ +ssize_t nsfw_mem_get_len(void *handle, nsfw_mem_struct_type type) +{ + if (NULL == handle) + { + NSRTP_LOGERR("input para error] handle=%p", handle); + return -1; + } + if ((NSFW_MEM_SPOOL == type) || (NSFW_MEM_RING == type)) + { + struct nsfw_mem_ring *ring = (struct nsfw_mem_ring *) handle; + if (ring->memtype >= NSFW_MEM_TYPEMAX) + { + NSRTP_LOGERR("invalid ring] ring type=%u ,handle=%p", + ring->memtype, handle); + return -1; + } + MEM_OP_CALL_OK_RET(ring->memtype, mem_ops_mem_statics, + (handle, type)); + } + else + { + MEM_OP_CALL_OK_RET(NSFW_SHMEM, mem_ops_mem_statics, (handle, type)); + } + return -1; +} + +/***************************************************************************** +* Prototype : nsfw_mem_sp_iterator +* Description : spool iterator +* Input : mpool_handle handle +* u32 start +* u32 end +* nsfw_mem_item_fun fun +* void *argv +* Output : None +* Return Value : i32 +* Calls : +* Called By : +*****************************************************************************/ +i32 nsfw_mem_sp_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv) +{ + MEM_OP_CALL_OK_RET(NSFW_SHMEM, mem_ops_sp_iterator, + (handle, start, end, fun, argv)); + return -1; +} + +i32 nsfw_mem_mbuf_iterator(mpool_handle handle, u32 start, u32 end, + nsfw_mem_item_fun fun, void *argv) +{ + MEM_OP_CALL_OK_RET(NSFW_SHMEM, mem_ops_mbuf_iterator, + (handle, start, end, fun, argv)); + return -1; +} + +i32 nsfw_mem_ring_iterator(mpool_handle handle, nsfw_mem_item_fun fun, + void *argv) +{ + MEM_OP_CALL_OK_RET(NSFW_SHMEM, mem_ops_ring_iterator, + (handle, fun, argv)); + return -1; +} + +/***************************************************************************** +* Prototype : nsfw_mem_get_health_info +* Description : get overflow flag and other info +* Input : mring_handle mhandle +* Output : None +* Return Value : +* Calls : +* Called By : +*****************************************************************************/ +nsfw_mem_ring_health_info nsfw_mem_get_health_info(mring_handle mhandle) +{ + struct nsfw_mem_ring *temp = (struct nsfw_mem_ring *) mhandle; + nsfw_mem_ring_health_info ring_health_info; + + ring_health_info.overflow_count = 0; + ring_health_info.overflow_time.tv_sec = 0; + ring_health_info.overflow_time.tv_usec = 0; + + ring_health_info.prod.head = 0; + ring_health_info.prod.tail = 0; + + ring_health_info.cons.head = 0; + ring_health_info.cons.tail = 0; + + ring_health_info.size = 0; + ring_health_info.mask = 0; + + if (NULL == temp) + { + NSRTP_LOGERR("invalid parameter]"); + return ring_health_info; + } + ring_health_info.overflow_count = temp->overflow_count; + ring_health_info.overflow_time = temp->overflow_time; + ring_health_info.prod.head = temp->prod.head; + ring_health_info.prod.tail = temp->prod.tail; + + ring_health_info.cons.head = temp->cons.head; + ring_health_info.cons.tail = temp->cons.tail; + + ring_health_info.size = temp->size; + ring_health_info.mask = temp->mask; + + return ring_health_info; +} + +/* *INDENT-OFF* */ +NSFW_MODULE_NAME(NSFW_MEM_MGR_MODULE) +NSFW_MODULE_PRIORITY(10) +NSFW_MODULE_INIT(nsfw_mem_init) +/* *INDENT-ON* */ diff --git a/src/framework/mem/nsfw_mem_desc.c b/src/framework/mem/nsfw_mem_desc.c new file mode 100644 index 0000000..ddb9c94 --- /dev/null +++ b/src/framework/mem/nsfw_mem_desc.c @@ -0,0 +1,104 @@ +/* +* +* 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 <sys/types.h> +#include <unistd.h> +#include "nsfw_mem_api.h" +#include "dmm_shmem_mng.h" +#include "dmm_nshmem_mng.h" +#include "dmm_ring.h" + +/* *INDENT-OFF* */ +/*the inferaces accessing memory*/ +static nsfw_mem_ops dmm_shmem_ops = +{ + dmm_shmem_init, + dmm_shmem_destroy, + dmm_shmem_create, + NULL,//nsfw_shmem_createv, + dmm_shmem_lookup, + dmm_shmem_release, + NULL,//dmm_shmem_mbfmpcreate, + NULL,//dmm_shmem_mbfmpcreatev, + NULL,//dmm_shmem_mbfmplookup, + NULL,//dmm_shmem_mbfmprelease, + NULL,//dmm_shmem_spcreate, + NULL,//dmm_shmem_spcreatev, + dmm_shmem_sp_ringcreate, + dmm_shmem_sprelease, + dmm_shmem_sp_lookup, + dmm_shmem_ringcreate, + dmm_shmem_ring_lookup, + dmm_shmem_ringrelease, + dmm_shmem_stactic, + NULL,//dmm_shmem_sp_iterator, + NULL,//nsfw_shmem_mbuf_iterator, + NULL,//nsfw_shmem_ring_iterator, + dmm_shmem_shddr_to_laddr, + dmm_shmem_laddr_to_shddr, + dmm_attach_core_id +}; + +/*no share memory access inferface*/ +static nsfw_mem_ops dmm_nshmem_ops = +{ + dmm_nshmem_init, + dmm_nshmem_destory, + dmm_nshmem_create, + NULL, + NULL,//nsfw_nshmem_lookup, + NULL,//nsfw_nshmem_release, + NULL, + NULL, + NULL, + NULL, + dmm_nshmem_spcreate, + NULL, + NULL, + dmm_nshmem_sprelease, + NULL,//nsfw_nshmem_sp_lookup, + dmm_nshmem_ringcreate, + NULL, + dmm_nshmem_ringrelease, + dmm_nshmem_stactic, + //NULL, + NULL,/*mem_ops_sp_iterator*/ + NULL,/*mem_ops_mbuf_iterator*/ +}; + +/*the order you add must be NSFW_SHMEM, NSFW_NSHMEM*/ +nsfw_mem_attr g_nsfw_mem_ops[] = +{ + {NSFW_SHMEM, &dmm_shmem_ops}, + {NSFW_NSHMEM, &dmm_nshmem_ops} +}; +/* *INDENT-ON* */ + +i32 g_mem_type_num = sizeof(g_nsfw_mem_ops) / sizeof(nsfw_mem_attr); + +nsfw_ring_ops g_ring_ops_arry[NSFW_MEM_TYPEMAX][NSFW_MPOOL_TYPEMAX] = { + { + [NSFW_MRING_MPMC] = { + .ring_ops_enqueue = dmm_mem_enqueue, + .ring_ops_dequeue = dmm_mem_dequeue} + } + , + { + [NSFW_MRING_MPMC] = { + .ring_ops_enqueue = dmm_mem_enqueue, + .ring_ops_dequeue = dmm_mem_dequeue} + } +}; diff --git a/src/framework/rd/nstack_rd_api.c b/src/framework/rd/nstack_rd_api.c new file mode 100644 index 0000000..e791e04 --- /dev/null +++ b/src/framework/rd/nstack_rd_api.c @@ -0,0 +1,766 @@ +/* +* +* 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 <arpa/inet.h> +#include "nstack_rd_api.h" +#include "nstack_rd_data.h" +#include "nsfw_mem_api.h" +#include "nsfw_recycle_api.h" +#include "nstack_log.h" +#include "nstack_securec.h" +#include "nsfw_common_defs.h" +#include "nstack_ip_addr.h" + +#define RD_AGE_MAX_TIME 3 + +rd_route_table *g_rd_table_handle[NSTACK_MAX_MODULE_NUM]; + +void *nstack_rd_malloc(const char *name) +{ + void *p = NULL; + + if (!name) + { + NSSOC_LOGERR("NULL pointer is not allowed!"); + return NULL; + } + if (strlen(name) >= NSFW_MEM_NAME_LENTH) + { + NSSOC_LOGERR("name length overflow!"); + return NULL; + } + + nsfw_mem_zone zone = { + {NSFW_SHMEM, NSFW_PROC_APP, {0} + } + , + sizeof(rd_route_table), + NSFW_SOCKET_ANY, + 0 + }; + + if (EOK != strcpy_s(zone.stname.aname, NSFW_MEM_NAME_LENTH, name)) + { + NSSOC_LOGERR("strcpy_s failed!"); + return NULL; + } + + p = nsfw_mem_zone_create(&zone); + if (!p) + { + NSSOC_LOGERR("nstack_rd_malloc failed!"); + return NULL; + } + + nstack_rd_table_clear(p); + + return p; +} + +void *nstack_local_rd_malloc(void) +{ + void *p; + + p = malloc(sizeof(rd_route_table)); + if (!p) + { + return NULL; + } + nstack_rd_table_clear(p); + return p; +} + +void nstack_local_rd_free(void *p) +{ + if (p) + free(p); +} + +int nstack_rd_free(const char *name) +{ + if (!name) + { + NSSOC_LOGERR("NULL pointer is not allowed!"); + return -1; + } + if (strlen(name) >= NSFW_MEM_NAME_LENTH) + { + NSSOC_LOGERR("name length overflow!"); + return -1; + } + + nsfw_mem_name pname = { + NSFW_SHMEM, + NSFW_PROC_APP, + {0} + }; + + if (EOK != strcpy_s(pname.aname, NSFW_MEM_NAME_LENTH, name)) + { + NSSOC_LOGERR("strcpy_s failed!"); + return -1; + } + + return nsfw_mem_zone_release(&pname); +} + +void nstack_rd_table_clear(void *p) +{ + rd_route_table *table = (rd_route_table *) p; + + (void) memset_s(table, sizeof(rd_route_table), 0, sizeof(rd_route_table)); + table->size = NSTACK_RD_DATA_MAX; + table->icnt = 0; + table->rdtbl_ver = 0; + DMM_SPINLOCK_MALLOC(table->rd_lock, 1); +} + +/***************************************************************************** +* Prototype : nstack_rd_ip_node_insert +* Description : insert a rd_ip_data into list +* Input : char *name +* rd_ip_data *data +* Output : None +* Return Value : int +* Calls : +* Called By : daemon-stack +*****************************************************************************/ +int nstack_rd_ip_node_insert(const char *name, rd_ip_data * data, void *table) +{ + rd_route_table *handle = (rd_route_table *) table; + if (!handle) + { + NSSOC_LOGERR("nstack rd mng not inited"); + return -1; + } + int iindex = 0; + rd_route_node *pnode = NULL; + int agetime = 0; + int ageindex = -1; + int freeindex = -1; + int repeatflag = 0; + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + /*record the index of first free element */ + if (RD_NODE_USELESS == pnode->flag) + { + if (-1 == freeindex) + { + freeindex = iindex; + NSSOC_LOGINF("nstack rd ip free element index:%d was found", + iindex); + } + continue; + } + + /*if is using, and repeat just set flag */ + if (RD_NODE_USING == pnode->flag) + { + if (MASK_V(pnode->data.ipdata.addr, pnode->data.ipdata.masklen) + == MASK_V(data->addr, data->masklen)) + { + NSSOC_LOGWAR + ("stack=%s, ip addr=*.*.%u.%u, masklen:%u was repeat", + name, FUZZY_IP_VAR(&data->addr), data->masklen); + repeatflag = 1; + } + continue; + } + + /*if flag is deleting, just update the age time, if agetime is on, just set flag to free */ + if (RD_NODE_DELETING == pnode->flag) + { + pnode->agetime++; + if (pnode->agetime >= RD_AGE_MAX_TIME) + { + pnode->flag = RD_NODE_USELESS; + NSSOC_LOGINF + ("nstack rd ip element index=%d,addr=*.*.%u.%u,masklen=%u was delete and set to free", + iindex, FUZZY_IP_VAR(&pnode->data.ipdata.addr), + pnode->data.ipdata.masklen); + } + /*record delete time */ + if (agetime < pnode->agetime) + { + agetime = pnode->agetime; + ageindex = iindex; + } + continue; + } + } + + /*if repeat, just return */ + if (1 == repeatflag) + { + return 0; + } + if (-1 == freeindex) + { + if (-1 != ageindex) + { + freeindex = ageindex; + } + else + { + NSSOC_LOGERR + ("the rd table is full,nstack=%s, rd addr=*.*.%u.%u, masklen=%u can't be inserted", + name, FUZZY_IP_VAR(&data->addr), data->masklen); + return -1; + } + } + pnode = &(handle->node[freeindex]); + /*if no free found, just reuse the big agetime */ + dmm_spin_lock_with_pid(&handle->rd_lock); + if (EOK != strcpy_s(pnode->data.stack_name, RD_PLANE_NAMELEN, name)) + { + NSSOC_LOGERR("strcpy_s failed]copy_name=%s", name); + } + pnode->data.type = RD_DATA_TYPE_IP; + pnode->agetime = 0; + pnode->data.ipdata.addr = data->addr; + pnode->data.ipdata.masklen = data->masklen; + pnode->data.ipdata.resev[0] = 0; + pnode->data.ipdata.resev[1] = 0; + pnode->flag = RD_NODE_USING; /*last set */ + handle->icnt++; + __sync_fetch_and_add(&handle->rdtbl_ver, 1); /*[MISRA 2004 Rule 14.2] */ + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF + ("nstack=%s, rd addr=*.*.%u.%u, masklen=%u index was inserted", name, + FUZZY_IP_VAR(&data->addr), data->masklen); + return 0; +} + +/***************************************************************************** +* Prototype : nstack_rd_ip_node_delete +* Description : rd data delete +* Input : rd_ip_data *data +* Output : None +* Return Value : int +* Calls : +* Called By : daemon-stack +*****************************************************************************/ +int nstack_rd_ip_node_delete(rd_ip_data * data, void *table) +{ + int iindex = 0; + rd_route_table *handle = (rd_route_table *) table; + rd_route_node *pnode = NULL; + + if (!handle) + { + NSSOC_LOGERR("nstack rd mng not inited"); + return -1; + } + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + if ((RD_NODE_USING == pnode->flag) + && (MASK_V(pnode->data.ipdata.addr, pnode->data.ipdata.masklen) + == MASK_V(data->addr, data->masklen))) + { + dmm_spin_lock_with_pid(&handle->rd_lock); + pnode->flag = RD_NODE_DELETING; /*just set deleting state */ + pnode->agetime = 0; + handle->icnt--; + NSSOC_LOGINF + ("nstack rd delete:%s, addr=*.*.%u.%u, masklen=%u index:%d was delete", + pnode->data.stack_name, FUZZY_IP_VAR(&data->addr), + data->masklen, iindex); + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF + ("nstack rd delete:%s, addr:0x%x, masklen:%u index:%d was delete", + pnode->data.stack_name, ntohl(data->addr), data->masklen, + iindex); + return 0; + } + } + NSSOC_LOGINF + ("nstack rd delete, addr=*.*.%u.%u, masklen=%u index was not found", + FUZZY_IP_VAR(&data->addr), data->masklen); + return 0; +} + +char *ipv6_ntop(ip6_addr_t host_addr) +{ + static char buf[INET6_ADDRSTRLEN]; + ip6_addr_t net_addr; + + net_addr = host_addr; + if (inet_ntop(AF_INET6, &net_addr.addr32, buf, INET6_ADDRSTRLEN) == NULL) + { + return "invalid IPv6 address"; + } + return buf; +} + +/***************************************************************************** +* Description : insert a rd_ip6_data into list +* Called By : daemon-stack +* Notice : the IP insert is in network order byte +*****************************************************************************/ +int nstack_rd_ip6_node_insert(const char *name, rd_ip6_data * data, + void *table) +{ + rd_route_table *handle = (rd_route_table *) table; + if (!handle) + { + NSSOC_LOGERR("nstack rd mng not inited"); + return -1; + } + int iindex = 0; + rd_route_node *pnode = NULL; + int agetime = 0; + int ageindex = -1; + int freeindex = -1; + int repeatflag = 0; + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + /*record the index of first free element */ + if (RD_NODE_USELESS == pnode->flag) + { + if (-1 == freeindex) + { + freeindex = iindex; + NSSOC_LOGINF("nstack rd ip free element index:%d was found", + iindex); + } + continue; + } + + /*if is using, and repeat just set flag */ + if (RD_NODE_USING == pnode->flag) + { + if (ip6_addr_match + (&pnode->data.ip6data.addr, &data->addr, data->masklen)) + { + NSSOC_LOGWAR + ("nstack:%s, index:%d, old_addr:%s, masklen:%u was repeat", + name, iindex, ipv6_ntop(pnode->data.ip6data.addr), + data->masklen); + repeatflag = 1; + } + continue; + } + + /*if flag is deleting, just update the age time, if agetime is on, just set flag to free */ + if (RD_NODE_DELETING == pnode->flag) + { + pnode->agetime++; + if (pnode->agetime >= RD_AGE_MAX_TIME) + { + pnode->flag = RD_NODE_USELESS; + NSSOC_LOGINF + ("nstack rd ip element index:%d addr:%s, masklen:%u was delete and set to free", + iindex, ipv6_ntop(pnode->data.ip6data.addr), + pnode->data.ipdata.masklen); + } + /*record delete time */ + if (agetime < pnode->agetime) + { + agetime = pnode->agetime; + ageindex = iindex; + } + continue; + } + } + + /*if repeat, just return */ + if (1 == repeatflag) + { + return 0; + } + if (-1 == freeindex) + { + if (-1 != ageindex) + { + freeindex = ageindex; + } + else + { + NSSOC_LOGERR + ("the rd table is full,nstack:%s, rd addr:%s, masklen:%u can't be inserted", + name, ipv6_ntop(data->addr), data->masklen); + return -1; + } + } + pnode = &(handle->node[freeindex]); + /*if no free found, just reuse the big agetime */ + dmm_spin_lock_with_pid(&handle->rd_lock); + if (EOK != strcpy_s(pnode->data.stack_name, RD_PLANE_NAMELEN, name)) + { + NSSOC_LOGERR("strcpy_s failed]copy_name=%s", name); + } + pnode->data.type = RD_DATA_TYPE_IP6; + pnode->agetime = 0; + pnode->data.ip6data.addr.addr32[0] = data->addr.addr32[0]; + pnode->data.ip6data.addr.addr32[1] = data->addr.addr32[1]; + pnode->data.ip6data.addr.addr32[2] = data->addr.addr32[2]; + pnode->data.ip6data.addr.addr32[3] = data->addr.addr32[3]; + pnode->data.ip6data.masklen = data->masklen; + pnode->flag = RD_NODE_USING; /*last set */ + handle->icnt++; + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF("nstack:%s, rd addr:%s, masklen:%u index was inserted", + name, ipv6_ntop(data->addr), data->masklen); + return 0; +} + +/***************************************************************************** +* Prototype : nstack_rd_ip6_node_delete +* Description : rd data delete, only set flag +* Called By : daemon-stack +* Notice : the IP delete is in network order byte +*****************************************************************************/ +int nstack_rd_ip6_node_delete(rd_ip6_data * data, void *table) +{ + int iindex = 0; + rd_route_table *handle = (rd_route_table *) table; + rd_route_node *pnode = NULL; + + if (!handle) + { + NSSOC_LOGERR("nstack rd mng not inited"); + return -1; + } + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + if ((RD_NODE_USING == pnode->flag) + && + (ip6_addr_match + (&pnode->data.ip6data.addr, &data->addr, data->masklen))) + { + dmm_spin_lock_with_pid(&handle->rd_lock); + pnode->flag = RD_NODE_DELETING; /*just set deleting state */ + pnode->agetime = 0; + handle->icnt--; + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF + ("nstack rd delete:%s, addr:%s, masklen:%u index:%d was delete", + pnode->data.stack_name, ipv6_ntop(data->addr), + data->masklen, iindex); + return 0; + } + } + NSSOC_LOGINF("nstack rd delete, addr:%s, masklen:%u index was not found", + ipv6_ntop(data->addr), data->masklen); + return 0; +} + +NSTACK_STATIC nsfw_rcc_stat rd_recyle_lock(u32 pid, void *pdata, u16 rec_type) +{ + int i; + + for (i = 0; i < NSTACK_MAX_MODULE_NUM; i++) + { + if (g_rd_table_handle[i] && pid == g_rd_table_handle[i]->rd_lock.lock) + { + (void) + __sync_bool_compare_and_swap(&g_rd_table_handle[i]->rd_lock. + lock, pid, 0); + NSFW_LOGWAR("rd locked]pid=%u", pid); + } + } + + return NSFW_RCC_CONTINUE; +} + +REGIST_RECYCLE_LOCK_REL(rd_recyle_lock, NULL, NSFW_PROC_NULL) + int nstack_rd_type_node_insert(const char *name, rd_type_data * data, + void *table) +{ + rd_route_table *handle = (rd_route_table *) table; + if (!handle || !data) + { + NSSOC_LOGERR("invalid parameters!"); + return -1; + } + int iindex = 0; + rd_route_node *pnode = NULL; + int agetime = 0; + int ageindex = -1; + int freeindex = -1; + int repeatflag = 0; + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + /*record the index of first free element */ + if (RD_NODE_USELESS == pnode->flag) + { + if (-1 == freeindex) + { + freeindex = iindex; + NSSOC_LOGINF("free element index:%d was found", iindex); + } + continue; + } + + /*if is using, and repeat just set flag */ + if (RD_NODE_USING == pnode->flag) + { + if (pnode->data.type_data.value == data->value + && pnode->data.type_data.attr == data->attr) + { + NSSOC_LOGWAR("find duplicate node, type:%u", data->value); + repeatflag = 1; + } + continue; + } + + /*if flag is deleting, just update the age time, if agetime is on, just set flag to free */ + if (RD_NODE_DELETING == pnode->flag) + { + pnode->agetime++; + if (pnode->agetime >= RD_AGE_MAX_TIME) + { + pnode->flag = RD_NODE_USELESS; + NSSOC_LOGINF("goint to free node at index:%d", iindex); + } + /*record delete time */ + if (agetime < pnode->agetime) + { + agetime = pnode->agetime; + ageindex = iindex; + } + continue; + } + } + + /*if repeat, just return */ + if (1 == repeatflag) + { + return 0; + } + if (-1 == freeindex) + { + if (-1 != ageindex) + { + freeindex = ageindex; + } + else + { + NSSOC_LOGERR("the rd route table:%p is full", handle); + return -1; + } + } + pnode = &(handle->node[freeindex]); + /*if no free found, just reuse the big agetime */ + dmm_spin_lock_with_pid(&handle->rd_lock); + if (EOK != strcpy_s(pnode->data.stack_name, RD_PLANE_NAMELEN, name)) + { + NSSOC_LOGERR("strcpy_s failed]copy_name=%s", name); + } + pnode->data.type = RD_DATA_TYPE_TYPE; + pnode->data.type_data.value = data->value; + pnode->data.type_data.attr = data->attr; + pnode->data.type_data.reserved[0] = data->reserved[0]; + pnode->data.type_data.reserved[1] = data->reserved[1]; + pnode->data.type_data.reserved[2] = data->reserved[2]; + pnode->data.type_data.reserved[3] = data->reserved[3]; + pnode->flag = RD_NODE_USING; /*last set */ + handle->icnt++; + __sync_fetch_and_add(&handle->rdtbl_ver, 1); /*[MISRA 2004 Rule 14.2] */ + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF("nstack=%s, type:%u attr:%u was inserted", name, + data->value, data->attr); + return 0; +} + +int nstack_rd_type_node_delete(rd_type_data * data, void *table) +{ + int iindex = 0; + rd_route_table *handle = (rd_route_table *) table; + rd_route_node *pnode = NULL; + + if (!handle || !data) + { + NSSOC_LOGERR("invalid parameters"); + return -1; + } + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + if ((RD_NODE_USING == pnode->flag) + && pnode->data.type_data.value == data->value + && pnode->data.type_data.attr == data->attr) + { + dmm_spin_lock_with_pid(&handle->rd_lock); + pnode->flag = RD_NODE_DELETING; /*just set deleting state */ + pnode->agetime = 0; + handle->icnt--; + NSSOC_LOGINF + ("nstack rd:%s, type:%u, attr:%u at index:%d will be deleted", + pnode->data.stack_name, data->value, data->attr, iindex); + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF + ("nstack rd:%s, type:%u, attr:%u at index:%d was deleted", + pnode->data.stack_name, data->value, data->attr, iindex); + return 0; + } + } + NSSOC_LOGINF("nstack rd delete, type:%u attr:%u was not found", + data->value, data->attr); + return 0; +} + +int nstack_rd_proto_node_insert(const char *name, rd_proto_data * data, + void *table) +{ + rd_route_table *handle = (rd_route_table *) table; + if (!handle || !data) + { + NSSOC_LOGERR("invalid parameters!"); + return -1; + } + int iindex = 0; + rd_route_node *pnode = NULL; + int agetime = 0; + int ageindex = -1; + int freeindex = -1; + int repeatflag = 0; + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + /*record the index of first free element */ + if (RD_NODE_USELESS == pnode->flag) + { + if (-1 == freeindex) + { + freeindex = iindex; + NSSOC_LOGINF("free element index:%d was found", iindex); + } + continue; + } + + /*if is using, and repeat just set flag */ + if (RD_NODE_USING == pnode->flag) + { + if (pnode->data.proto_data.value == data->value + && pnode->data.proto_data.attr == data->attr) + { + NSSOC_LOGWAR("find duplicate node, proto:%u", data->value); + repeatflag = 1; + } + continue; + } + + /*if flag is deleting, just update the age time, if agetime is on, just set flag to free */ + if (RD_NODE_DELETING == pnode->flag) + { + pnode->agetime++; + if (pnode->agetime >= RD_AGE_MAX_TIME) + { + pnode->flag = RD_NODE_USELESS; + NSSOC_LOGINF("goint to free node at index:%d", iindex); + } + /*record delete time */ + if (agetime < pnode->agetime) + { + agetime = pnode->agetime; + ageindex = iindex; + } + continue; + } + } + + /*if repeat, just return */ + if (1 == repeatflag) + { + return 0; + } + if (-1 == freeindex) + { + if (-1 != ageindex) + { + freeindex = ageindex; + } + else + { + NSSOC_LOGERR("the rd route table:%p is full", handle); + return -1; + } + } + pnode = &(handle->node[freeindex]); + /*if no free found, just reuse the big agetime */ + dmm_spin_lock_with_pid(&handle->rd_lock); + if (EOK != strcpy_s(pnode->data.stack_name, RD_PLANE_NAMELEN, name)) + { + NSSOC_LOGERR("strcpy_s failed]copy_name=%s", name); + } + pnode->data.type = RD_DATA_TYPE_PROTO; + pnode->data.proto_data.value = data->value; + pnode->data.proto_data.attr = data->attr; + pnode->flag = RD_NODE_USING; /*last set */ + handle->icnt++; + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF("nstack=%s, proto:%u attr:%u was inserted", name, + data->value, data->attr); + return 0; +} + +int nstack_rd_proto_node_delete(rd_proto_data * data, void *table) +{ + int iindex = 0; + rd_route_table *handle = (rd_route_table *) table; + rd_route_node *pnode = NULL; + + if (!handle || !data) + { + NSSOC_LOGERR("invalid parameters"); + return -1; + } + + for (iindex = 0; iindex < NSTACK_RD_DATA_MAX; iindex++) + { + pnode = &(handle->node[iindex]); + if ((RD_NODE_USING == pnode->flag) + && pnode->data.proto_data.value == data->value + && pnode->data.proto_data.attr == data->attr) + { + dmm_spin_lock_with_pid(&handle->rd_lock); + pnode->flag = RD_NODE_DELETING; /*just set deleting state */ + pnode->agetime = 0; + handle->icnt--; + NSSOC_LOGINF + ("nstack rd:%s, proto:%u, attr:%u at index:%d will be deleted", + pnode->data.stack_name, data->value, data->attr, iindex); + __sync_fetch_and_add(&handle->rdtbl_ver, 1); + dmm_spin_unlock(&handle->rd_lock); + NSSOC_LOGINF + ("nstack rd:%s, proto:%u, attr:%u at index:%d was deleted", + pnode->data.stack_name, data->value, data->attr, iindex); + return 0; + } + } + NSSOC_LOGINF("nstack rd delete, proto:%u attr:%u was not found", + data->value, data->attr); + return 0; +} diff --git a/src/framework/res/nstack_share_res.c b/src/framework/res/nstack_share_res.c new file mode 100644 index 0000000..d6024cf --- /dev/null +++ b/src/framework/res/nstack_share_res.c @@ -0,0 +1,270 @@ +/* +* +* 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_share_res.h" +#include "nsfw_mem_api.h" +#include "types.h" +#include "nstack_securec.h" +#include "nstack_log.h" +#include "nsfw_maintain_api.h" + +#include "nsfw_ps_api.h" + +#define NSTACK_SHARE_RES "nstack_share_res" + +#define MAX_DELAY_RECYCLE_SEC 15 + +typedef struct +{ + volatile u16 forking; + u8 delay_recycle; + u8 delay_tick; + volatile u16 child_hbt; + u16 old_child_hbt; +} nstack_fork_recycle; + +typedef struct +{ + nstack_fork_recycle fork_recycle[NSFW_MAX_PID]; +} nstack_share_res; + +NSTACK_STATIC nstack_share_res *g_nstack_share_res; +NSTACK_STATIC volatile int g_enable_child_hbt = 0; + +/* Add dfx timer tick */ +/** global timer tick */ +u64 g_nstack_timer_init_value = 0; +nstack_tick_info_t g_nstack_timer_tick = {.tick_ptr = + &g_nstack_timer_init_value, +}; + +int nstack_init_share_res() +{ + mzone_handle zone; + nsfw_mem_zone param; + int ret; + + param.isocket_id = -1; + param.lenth = sizeof(nstack_share_res); + param.stname.entype = NSFW_SHMEM; + + ret = strcpy_s(param.stname.aname, NSFW_MEM_NAME_LENTH, NSTACK_SHARE_RES); + if (EOK != ret) + { + NSSOC_LOGERR("strcpy_s failed]name=%s,ret=%d", NSTACK_SHARE_RES, ret); + return -1; + } + + zone = nsfw_mem_zone_create(¶m); + if (!zone) + { + NSSOC_LOGERR("nsfw_mem_zone_create failed]name=%s", NSTACK_SHARE_RES); + return -1; + } + + g_nstack_share_res = (nstack_share_res *) zone; + if (EOK != + memset_s(g_nstack_share_res, sizeof(nstack_share_res), 0, + sizeof(nstack_share_res))) + { + NSSOC_LOGERR("memset failed"); + return -1; + } + + NSSOC_LOGDBG("ok"); + return 0; +} + +NSTACK_STATIC int nstack_lookup_share_res() +{ + mzone_handle zone; + nsfw_mem_name param; + + param.entype = NSFW_SHMEM; + param.enowner = NSFW_PROC_MAIN; + if (strcpy_s(param.aname, NSFW_MEM_NAME_LENTH, NSTACK_SHARE_RES) != 0) + { + NSSOC_LOGERR("strcpy_s failed]name=%s", NSTACK_SHARE_RES); + return -1; + } + + zone = nsfw_mem_zone_lookup(¶m); + if (!zone) + { + NSSOC_LOGERR("nsfw_mem_zone_lookup failed]name=%s", NSTACK_SHARE_RES); + return -1; + } + + g_nstack_share_res = (nstack_share_res *) zone; + NSSOC_LOGDBG("ok"); + return 0; +} + +/* Add dfx timer tick */ +NSTACK_STATIC int nstack_lookup_share_global_tick() +{ + int ret; + nsfw_mem_name name = {.entype = NSFW_SHMEM,.enowner = NSFW_PROC_MAIN }; + + ret = strcpy_s(name.aname, NSFW_MEM_NAME_LENTH, NSTACK_GLOBAL_TICK_SHM); + if (EOK != ret) + { + NSSOC_LOGERR("strcpy_s failed]name=%s,ret=%d", + NSTACK_GLOBAL_TICK_SHM, ret); + return -1; + } + + g_nstack_timer_tick.tick_ptr = (u64 *) nsfw_mem_zone_lookup(&name); + if (NULL == g_nstack_timer_tick.tick_ptr) + { + NSSOC_LOGERR("Failed to lookup global timer tick memory"); + return -1; + } + + NSSOC_LOGDBG("ok"); + return 0; +} + +int nstack_attach_share_res() +{ + if (nstack_lookup_share_res() != 0) + { + return -1; + } + + /* Add dfx timer tick */ + if (nstack_lookup_share_global_tick() != 0) + { + return -1; + } + + return 0; +} + +void fork_parent_start(i32 ppid) +{ + g_nstack_share_res->fork_recycle[ppid].forking = 1; +} + +/* + * if child die, child_hbt will stop changing, parent wait FORK_WAIT_SEC seconds. + * otherwise, parent wait until child fork done. + */ +void fork_wait_child_done(u32 ppid) +{ +#define FORK_WAIT_SEC 5 +#define FORK_SLEEP_MS 10 +#define FORK_WAIT_CNT (FORK_WAIT_SEC * 1000 / FORK_SLEEP_MS) + u32 wait_cnt = FORK_WAIT_CNT; + nstack_fork_recycle *recycle = &g_nstack_share_res->fork_recycle[ppid]; + while (recycle->forking && wait_cnt) + { + --wait_cnt; + sys_sleep_ns(0, 1000000 * FORK_SLEEP_MS); + + if (recycle->old_child_hbt != recycle->child_hbt) + { + recycle->old_child_hbt = recycle->child_hbt; + wait_cnt = FORK_WAIT_CNT; + } + } + + if ((0 == wait_cnt) && recycle->forking) + { + NSSOC_LOGWAR("timeout] waited time=%u,ppid=%u", FORK_WAIT_SEC, ppid); + recycle->forking = 0; + } +} + +void fork_parent_failed(u32 ppid) +{ + g_nstack_share_res->fork_recycle[ppid].forking = 0; +} + +NSTACK_STATIC void *fork_start_child_hbt(void *arg) +{ + u32 ppid = (u32) (u64) arg; + nstack_fork_recycle *recycle = &g_nstack_share_res->fork_recycle[ppid]; + + while (g_enable_child_hbt) + { + ++recycle->child_hbt; + sys_sleep_ns(0, 10); + } + + return NULL; +} + +void fork_child_start(u32 ppid) +{ + g_enable_child_hbt = 1; + pthread_t t; + if (pthread_create(&t, NULL, fork_start_child_hbt, (void *) (u64) ppid)) + { + NSPOL_LOGERR("pthread_create failed]ppid=%u", ppid); + } +} + +void fork_child_done(u32 ppid) +{ + g_enable_child_hbt = 0; + g_nstack_share_res->fork_recycle[ppid].forking = 0; +} + +int fork_recycle_check(u32 pid) +{ + if (g_nstack_share_res->fork_recycle[pid].forking) + { + g_nstack_share_res->fork_recycle[pid].delay_recycle = 1; + return -1; + } + + return 0; +} + +/* + * if child die, child_hbt will stop changing, daemon-stack delay MAX_DELAY_RECYCLE_SEC seconds to recycle. + * otherwise, daemon-stack delay recycle until child fork done. + */ +void fork_delay_recycle(u8 sec, nsfw_recycle_fun fun) +{ + u32 i; + + for (i = 0; i < NSFW_MAX_PID; ++i) + { + nstack_fork_recycle *recycle = &g_nstack_share_res->fork_recycle[i]; + if (recycle->delay_recycle) + { + if (recycle->old_child_hbt != recycle->child_hbt) + { + recycle->old_child_hbt = recycle->child_hbt; + recycle->delay_tick = 0; + } + else + { + recycle->delay_tick += sec; + if (!recycle->forking + || (recycle->delay_tick > MAX_DELAY_RECYCLE_SEC)) + { + recycle->delay_recycle = 0; + recycle->delay_tick = 0; + recycle->forking = 0; + (void) fun(i, NULL, 0); + } + } + } + } +} diff --git a/src/framework/ring/dmm_ring.c b/src/framework/ring/dmm_ring.c new file mode 100644 index 0000000..24bcf33 --- /dev/null +++ b/src/framework/ring/dmm_ring.c @@ -0,0 +1,214 @@ +/* +* +* 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 <string.h> + +#include "nstack_log.h" + +#include "dmm_ring.h" +#include "dmm_ring_base.h" +#include "nsfw_mem_api.h" +#include "nstack_securec.h" +/* enqueue several objects in a ring. + ring: point to the ring + p: object pointer list array + num: number of object + fixed: enqueue fixed number +single_cons: is single producer + <return>: number of enqueued object, 0: queue is full +*/ +inline static int +dmm_ring_enqueue(struct dmm_ring *ring, void **p, int num, + int fixed, int is_sp) +{ + int n, pos, new_pos; + + n = dmm_enqueue_prep(ring, num, &pos, fixed, is_sp); + + if (n == 0) + return 0; + + new_pos = dmm_enqueue_copy(ring, pos, p, n); + + dmm_enqueue_done(ring, pos, new_pos, is_sp); + + return n; +} + +inline static int dmm_fix_enqueue(struct dmm_ring *ring, void **p, int num) +{ + return dmm_ring_enqueue(ring, p, num, 1, ring->is_sp); +} + +inline static int dmm_var_enqueue(struct dmm_ring *ring, void **p, int num) +{ + return dmm_ring_enqueue(ring, p, num, 0, ring->is_sp); +} + +inline static int dmm_enqueue(struct dmm_ring *ring, void *p) +{ + return dmm_var_enqueue(ring, &p, 1); +} + +inline static int +dmm_array_enqueue(struct dmm_ring *ring, void *array, + int num, size_t elt_size) +{ + int n, pos, new_pos; + + n = dmm_enqueue_prep(ring, num, &pos, 0, ring->is_sp); + + if (n == 0) + return 0; + + new_pos = dmm_enqueue_copy_array(ring, pos, array, n, elt_size); + + dmm_enqueue_done(ring, pos, new_pos, ring->is_sp); + + return n; +} + +void dmm_ring_dump(struct dmm_ring *ring, int list) +{ + if (!ring) + return; + + NSFW_LOGINF("ring:%p size:%d flag:0x%x prod:%d-%d/%d cons:%d-%d/%d", + ring, ring->size, ring->flag, + ring->prod_head, ring->prod_tail, ring->is_sp, + ring->cons_head, ring->cons_tail, ring->is_sc); + if (list && dmm_ring_count(ring)) + { + int count = 0; + void **p = (void **) (ring + 1); + int i = ring->cons_head; + while (i != ring->prod_tail) + { + if ((count++ & 3) == 0) + NSFW_LOGINF("\n"); + NSFW_LOGINF(" %d:%p", i, p[i]); + if (++i >= ring->size) + i = 0; + } + } + NSFW_LOGINF("\n----------------\n"); +} + +int +dmm_ring_init(struct dmm_ring *ring, int num, size_t eltsize, int flag, + unsigned char mem_type) +{ + if (num > DMM_RING_MAX_NUM) + return -1; + + (void) memset_s(ring, sizeof(struct dmm_ring), 0, + sizeof(struct dmm_ring)); + + ring->memtype = mem_type; + ring->ringflag = NSFW_MRING_MPMC; + + ring->size = num + 1; + ring->eltsize = eltsize; + + ring->prod_head = 0; + ring->prod_tail = 0; + ring->is_sp = flag & DMM_RING_INIT_SP; + + ring->cons_head = 0; + ring->cons_tail = 0; + ring->is_sc = flag & DMM_RING_INIT_SC; + + return 0; +} + +/* dequeue several objects from a ring. + ring: point to the ring + p: save object array + num: number of p + fixed: dequeue fixed number +single_cons: is single consumer + <return>: number of dequeued object, 0: queue is empty +*/ +inline static int +dmm_ring_dequeue(struct dmm_ring *ring, void **p, int num, + int fixed, int single_cons) +{ + int n, pos, new_pos; + + n = dmm_dequeue_prep(ring, num, &pos, fixed, single_cons); + + if (n == 0) + return 0; + + new_pos = dmm_dequeue_copy(ring, pos, p, n); + + dmm_dequeue_done(ring, pos, new_pos, single_cons); + + return n; +} + +inline static int dmm_fix_dequeue(struct dmm_ring *ring, void **p, int num) +{ + return dmm_ring_dequeue(ring, p, num, 1, ring->is_sc); +} + +inline static int dmm_var_dequeue(struct dmm_ring *ring, void **p, int num) +{ + return dmm_ring_dequeue(ring, p, num, 0, ring->is_sc); +} + +inline static int dmm_dequeue(struct dmm_ring *ring, void **p) +{ + return dmm_var_dequeue(ring, p, 1); +} + +int +dmm_pool_init(struct dmm_ring *pool, size_t elt_size, int num, int flag, + unsigned char memtype) +{ + int ret; + void *array; + const size_t ring_size = dmm_ring_bufsize(num); + + if (0 != dmm_ring_init(pool, num, elt_size, flag, memtype)) + { + NSFW_LOGERR + ("init pool's ring failed, num:%d flag:0x%x ring_size:%lu", num, + flag, ring_size); + return -1; + } + + array = (char *) pool + ring_size; + ret = dmm_array_enqueue(pool, array, num, elt_size); + if (ret != num) + { + NSFW_LOGERR("enqueue failed, num:%d elt_size:%lu", num, elt_size); + return -1; + } + + return 0; +} + +int dmm_mem_enqueue(void *ring, void *p) +{ + return dmm_enqueue((struct dmm_ring *) ring, p); +} + +int dmm_mem_dequeue(void *ring, void **p) +{ + return dmm_dequeue((struct dmm_ring *) ring, p); +} diff --git a/src/framework/ring/dmm_ring_base.h b/src/framework/ring/dmm_ring_base.h new file mode 100644 index 0000000..1f2ce35 --- /dev/null +++ b/src/framework/ring/dmm_ring_base.h @@ -0,0 +1,190 @@ +/* +* +* 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 _DMM_RING_BASE_H_ +#define _DMM_RING_BASE_H_ + +#ifndef _DMM_RING_H_ +#error include dmm_ring.h please +#endif + +inline static int +__move_head(volatile int *head, int ring_size, + int old_head, int real_num, int is_single) +{ + int new_head = old_head + real_num; + + if (new_head >= ring_size) + { + new_head -= ring_size; + } + + if (is_single) + { + *head = new_head; + return 1; + } + + return dmm_atomic_swap((dmm_atomic_t *) head, old_head, new_head); +} + +inline static int +dmm_enqueue_prep(struct dmm_ring *ring, const int num, + int *pos, const int fixed, int is_sp) +{ + int succ, real, head; + const int ring_size = ring->size; + + do + { + head = ring->prod_head; + + dmm_barrier(); + + if ((real = ring->cons_tail - head - 1) < 0) + real += ring_size; + + if (real >= num) + real = num; + else if (fixed) + return 0; + + if (real <= 0) + return 0; + + succ = __move_head(&ring->prod_head, ring_size, head, real, is_sp); + } + while (!succ); + + *pos = head; + return real; +} + +inline static int +dmm_enqueue_copy(struct dmm_ring *ring, int pos, void **from, int num) +{ + const int ring_size = ring->size; + void **box = (void **) (ring + 1); + + while (num > 0) + { + box[pos++] = *from++; + if (pos >= ring_size) + pos = 0; + --num; + } + + return pos; +} + +inline static void +dmm_enqueue_done(struct dmm_ring *ring, int pos, int new_pos, int is_sp) +{ + dmm_barrier(); + + if (!is_sp) + { + while (ring->prod_tail != pos) + dmm_pause(); + } + + ring->prod_tail = new_pos; +} + +inline static int +dmm_enqueue_copy_array(struct dmm_ring *ring, int pos, + void *array, int num, size_t elt_size) +{ + const int ring_size = ring->size; + void **box = (void **) (ring + 1); + char *from = (char *) array; + + while (num > 0) + { + box[pos++] = from; + if (pos >= ring_size) + pos = 0; + from += elt_size; + --num; + } + + return pos; +} + +inline static int +dmm_dequeue_prep(struct dmm_ring *ring, const int num, int *pos, + const int fixed, int is_sc) +{ + int succ, real, head; + const int ring_size = ring->size; + + do + { + head = ring->cons_head; + + dmm_barrier(); + + if ((real = ring->prod_tail - head) < 0) + real += ring_size; + + if (real >= num) + real = num; + else if (fixed) + return 0; + + if (real <= 0) + return 0; + + succ = __move_head(&ring->cons_head, ring_size, head, real, is_sc); + } + while (!succ); + + *pos = head; + return real; +} + +inline static int +dmm_dequeue_copy(struct dmm_ring *ring, int pos, void **to, int num) +{ + const int ring_size = ring->size; + void **box = (void **) (ring + 1); + + while (num > 0) + { + *to++ = box[pos++]; + if (pos >= ring_size) + pos = 0; + --num; + } + + return pos; +} + +inline static void +dmm_dequeue_done(struct dmm_ring *ring, int pos, int new_pos, int is_sc) +{ + dmm_barrier(); + + if (!is_sc) + { + while (ring->cons_tail != pos) + dmm_pause(); + } + + ring->cons_tail = new_pos; +} + +#endif diff --git a/src/framework/snapshot/fw_snapshot.c b/src/framework/snapshot/fw_snapshot.c index c68d3e0..cb571e2 100644 --- a/src/framework/snapshot/fw_snapshot.c +++ b/src/framework/snapshot/fw_snapshot.c @@ -15,9 +15,9 @@ */ #include "nstack_securec.h" -#include "nsfw_snapshot.h" +#include "nsfw_snapshot_api.h" #include "nstack_log.h" -#include "fw_ss_tlv.h" +#include "fw_snapshot.h" #ifdef __cplusplus /* *INDENT-OFF* */ @@ -25,455 +25,504 @@ extern "C"{ /* *INDENT-ON* */ #endif /* __cplusplus */ -/* *INDENT-OFF* */ -nsfw_ss_objDescManager_t g_nsfw_ss_objDescManager = +nsfw_ss_obj_desc_manager_t g_nsfw_ss_obj_desc_manager = + {.g_nsfw_ss_obj_des_num = 0 }; + +void nsfw_ss_register_obj_desc(nsfw_ss_obj_desc_t * objDesc) { -.g_nsfw_ss_objDesNum = 0}; + if (objDesc == NULL) + return; -/* *INDENT-ON* */ + nsfw_ss_obj_desc_manager_t *manager = nsfw_ss_get_obj_desc_manager_inst(); -void -nsfw_ss_register_ObjDesc (nsfw_ss_objDesc_t * objDesc) -{ - if (objDesc == NULL) - return; - nsfw_ss_objDescManager_t *manager = nsfw_ss_getObjDescManagerInst (); - if (manager->g_nsfw_ss_objDesNum >= NSFW_SS_MAX_OBJDESC_NUM) - return; - manager->g_nsfw_ss_objDescs[manager->g_nsfw_ss_objDesNum++] = objDesc; + if (manager->g_nsfw_ss_obj_des_num >= NSFW_SS_MAX_OBJDESC_NUM) + return; + + manager->g_nsfw_ss_obj_descs[manager->g_nsfw_ss_obj_des_num++] = objDesc; } -static nsfw_ss_objDesc_t * -nsfw_ss_getObjDescFromType (u16 objType) +static nsfw_ss_obj_desc_t *nsfw_ss_get_obj_desc_from_type(u16 objType) { - nsfw_ss_objDescManager_t *manager = nsfw_ss_getObjDescManagerInst (); - int i; - for (i = 0; i < manager->g_nsfw_ss_objDesNum && i < NSFW_SS_MAX_OBJDESC_NUM; - i++) + nsfw_ss_obj_desc_manager_t *manager = nsfw_ss_get_obj_desc_manager_inst(); + int i; + for (i = 0; + i < manager->g_nsfw_ss_obj_des_num && i < NSFW_SS_MAX_OBJDESC_NUM; + i++) { - if (manager->g_nsfw_ss_objDescs[i]->objType == objType) - return manager->g_nsfw_ss_objDescs[i]; + if (manager->g_nsfw_ss_obj_descs[i]->objType == objType) + return manager->g_nsfw_ss_obj_descs[i]; } - return NULL; + return NULL; } -static nsfw_ss_objMemDesc_t * -nsfw_ss_getMemDescFromType (u16 objType, nsfw_ss_objDesc_t * objDesc) +static nsfw_ss_obj_mem_desc_t *nsfw_ss_get_mem_desc_from_type(u16 objType, + nsfw_ss_obj_desc_t + * objDesc) { - int i; - for (i = 0; i < objDesc->memNum; i++) + int i; + for (i = 0; i < objDesc->memNum; i++) { - if (objDesc->memDesc[i].type == objType) + if (objDesc->memDesc[i].type == objType) { - return &objDesc->memDesc[i]; + return &objDesc->memDesc[i]; } } - return NULL; + return NULL; } /** * @Function nsfw_ss_store * @Description store object to memory * @param (in) objType - type of object with member description - * @param (in) obj - address of object memory + * @param (in) obj - adderss of object memory * @param (in) storeMem - address of memory to store object data * @param (in) storeMemLen - maximal length of storage memory * @return positive integer means length of memory cost on success. return -1 if error */ -int -nsfw_ss_storeObjMem (u16 objMemType, void *obj, void *storeMem, - u32 storeMemLen) +int nsfw_ss_store_obj_mem(u16 objMemType, void *obj, void *storeMem, + u32 storeMemLen) { - if (NULL == obj || NULL == storeMem) - return -1; - - // example of object - /* struct A{ */ - /* int a1; */ - /* struct A2 a2; --> struct A2 {int a2} */ - /* struct A3 a3[2]; --> struct A3 [{int a3}, {int a3}] */ - /* } */ - - /* -------------------------------------------- */ - /* | type(object) | length | */ - /* | -------------------------------------- | */// -- - /* | | type(item) | length | | */// member a1 - /* | | item value (object->member) | | */// -- - /* | -------------------------------------- | */// object a2 - /* | | type(object) | length | | */// -- - /* | | ------------------------------- | | */// member a2 - /* | | | type(item) | length | | | */// -- - /* | | | item value (object->member) | | | */// -- - /* | | ------------------------------- | | */// - /* | -------------------------------------- | */// - /* | | type(object array) | length | | */// array member a3 - /* | | ------------------------------- | | */// -- - /* | | | type(object) | length | | | */// object a3_1 - /* | | | ----------------------------| | | */// -- - /* | | | type(item) | length | | | */// member a3_1_1 - /* | | | item value (object->member) | | | */ - /* | | | ----------------------------| | | */ - /* | | ------------------------------- | | */ - /* | | | type(object) | length | | | */ - /* | | | ----------------------------| | | */ - /* | | | type(item) | length | | | */ - /* | | | item value (object->member) | | | */ - /* | | | ----------------------------| | | */ - /* | | ------------------------------- | | */ - /* | |------------------------------------| | */ - /* -------------------------------------------- */ - nsfw_ss_objDesc_t *objDesc = - nsfw_ss_getObjDescFromType (NSFW_SS_TYPE_GETOBJ (objMemType)); - if (NULL == objDesc) - return -1; - - /* Get object header tlv */ - if (storeMemLen < tlv_header_length ()) - return -1; - nsfw_ss_tlv_t *tlv = (nsfw_ss_tlv_t *) storeMem; - tlv->type = objMemType; - tlv->length = 0; - tlv_header (storeMem); - storeMemLen -= tlv_header_length (); - - /* Search every object member */ - - /* For base item(including array of base item), it should start with a tlv header */ - /* For object array, it should start with one tlv header including array information */ - /* For object, it should call nsfw_ss_store recursively */ - int i; - for (i = 0; i < objDesc->memNum; i++) + if (NULL == obj || NULL == storeMem) { - nsfw_ss_objMemDesc_t *memDesc = &objDesc->memDesc[i]; - if (NSFW_SS_TYPE_IS_MEMBER_OBJ (memDesc->type)) + return -1; + } + + // example of object + /* struct A{ */ + /* int a1; */ + /* struct A2 a2; --> struct A2 {int a2} */ + /* struct A3 a3[2]; --> struct A3 [{int a3}, {int a3}] */ + /* } */ + + /* -------------------------------------------- */ + /* | type(object) | length | */ + /* | -------------------------------------- | */// -- + /* | | type(item) | length | | */// member a1 + /* | | item value (object->member) | | */// -- + /* | -------------------------------------- | */// object a2 + /* | | type(object) | length | | */// -- + /* | | ------------------------------- | | */// member a2 + /* | | | type(item) | length | | | */// -- + /* | | | item value (object->member) | | | */// -- + /* | | ------------------------------- | | */ + /* | -------------------------------------- | */ + /* | | type(object array) | length | | */// array member a3 + /* | | ------------------------------- | | */// -- + /* | | | type(object) | length | | | */// object a3_1 + /* | | | ----------------------------| | | */// -- + /* | | | type(item) | length | | | */// member a3_1_1 + /* | | | item value (object->member) | | | */ + /* | | | ----------------------------| | | */ + /* | | ------------------------------- | | */ + /* | | | type(object) | length | | | */ + /* | | | ----------------------------| | | */ + /* | | | type(item) | length | | | */ + /* | | | item value (object->member) | | | */ + /* | | | ----------------------------| | | */ + /* | | ------------------------------- | | */ + /* | |------------------------------------| | */ + /* -------------------------------------------- */ + + nsfw_ss_obj_desc_t *objDesc = + nsfw_ss_get_obj_desc_from_type(NSFW_SS_TYPE_GETOBJ(objMemType)); + if (NULL == objDesc) + return -1; + + /* Get object header tlv */ + if (storeMemLen < tlv_header_length()) + return -1; + nsfw_ss_tlv_t *tlv = (nsfw_ss_tlv_t *) storeMem; + tlv->type = objMemType; + tlv->length = 0; + + tlv_header(storeMem); + storeMemLen -= tlv_header_length(); + + /* Search every object member */ + + /* For base item(including array of base item), it should start with a tlv header */ + /* For object array, it should start with one tlv header including array information */ + /* For object, it should call nsfw_ss_store recursively */ + + int i; + for (i = 0; i < objDesc->memNum; i++) + { + nsfw_ss_obj_mem_desc_t *memDesc = &objDesc->memDesc[i]; + + if (NSFW_SS_TYPE_IS_MEMBER_OBJ(memDesc->type)) { - if (NSFW_SS_TYPE_IS_MEMBER_ARRAY (memDesc->type)) + if (NSFW_SS_TYPE_IS_MEMBER_ARRAY(memDesc->type)) { - /* array object should includes one array tlv header, shows the array informations */ - if (storeMemLen < tlv_header_length ()) - return -1; - nsfw_ss_tlv_t *arrayTlv = (nsfw_ss_tlv_t *) storeMem; - arrayTlv->type = memDesc->type; - arrayTlv->length = 0; - tlv_header (storeMem); - storeMemLen -= tlv_header_length (); - nsfw_ss_objDesc_t *memObjDesc = - nsfw_ss_getObjDescFromType (NSFW_SS_TYPE_GETOBJ - (memDesc->type)); - if (NULL == memObjDesc) - return -1; - u32 arraySize = memDesc->length / memObjDesc->objSize; - u32 j; - for (j = 0; j < arraySize; j++) - { - int ret = - nsfw_ss_storeObjMem (NSFW_SS_TYPE_SET_MEMBER_OBJ - (NSFW_SS_TYPE_GETOBJ (memDesc->type), - 0), - (char *) obj + - (u64) (memDesc->offset) + - (u64) j * memObjDesc->objSize, - storeMem, storeMemLen); - if ((-1 == ret) || (storeMemLen < (u32) ret)) + /* array object should includes one array tlv header, shows the array informations */ + + if (storeMemLen < tlv_header_length()) return -1; - tlv_mem_forward (storeMem, ret); - storeMemLen -= (u32) ret; - arrayTlv->length += (u32) ret; + + nsfw_ss_tlv_t *arrayTlv = (nsfw_ss_tlv_t *) storeMem; + arrayTlv->type = memDesc->type; + arrayTlv->length = 0; + + tlv_header(storeMem); + storeMemLen -= tlv_header_length(); + + nsfw_ss_obj_desc_t *memObjDesc = + nsfw_ss_get_obj_desc_from_type(NSFW_SS_TYPE_GETOBJ + (memDesc->type)); + if (NULL == memObjDesc) + return -1; + + u32 arraySize = memDesc->length / memObjDesc->objSize; + u32 j; + for (j = 0; j < arraySize; j++) + { + int ret = + nsfw_ss_store_obj_mem(NSFW_SS_TYPE_SET_MEMBER_OBJ + (NSFW_SS_TYPE_GETOBJ + (memDesc->type), 0), + (char *) obj + + (u64) (memDesc->offset) + + (u64) j * memObjDesc->objSize, + storeMem, + storeMemLen); + + if ((-1 == ret) || (storeMemLen < (u32) ret)) + return -1; + + tlv_mem_forward(storeMem, ret); + storeMemLen -= (u32) ret; + arrayTlv->length += (u32) ret; } - tlv->length += (arrayTlv->length + (u32) tlv_header_length ()); + + tlv->length += (arrayTlv->length + (u32) tlv_header_length()); } - else + else { - int ret = nsfw_ss_storeObjMem (memDesc->type, - ((char *) obj + memDesc->offset), - storeMem, storeMemLen); - if (ret < 0 || (storeMemLen < (u32) ret)) - return -1; - storeMemLen -= (u32) ret; - tlv_mem_forward (storeMem, ret); - tlv->length += (u32) ret; + int ret = nsfw_ss_store_obj_mem(memDesc->type, + ((char *) obj + + memDesc->offset), + storeMem, storeMemLen); + if (ret < 0 || (storeMemLen < (u32) ret)) + return -1; + + storeMemLen -= (u32) ret; + tlv_mem_forward(storeMem, ret); + tlv->length += (u32) ret; } } - else + else { - // Base Item - if (storeMemLen < tlv_header_length ()) + // Base Item + if (storeMemLen < tlv_header_length()) { - return -1; + return -1; } - nsfw_ss_tlv_t *curtlv = (nsfw_ss_tlv_t *) storeMem; // curTlv means next tlv elem - curtlv->type = memDesc->type; - curtlv->length = memDesc->length; - tlv_header (storeMem); - storeMemLen -= tlv_header_length (); - if (storeMemLen < curtlv->length) - return -1; - if (EOK != - MEMCPY_S (storeMem, (size_t) storeMemLen, - ((char *) obj + memDesc->offset), - (size_t) memDesc->length)) + + nsfw_ss_tlv_t *curtlv = (nsfw_ss_tlv_t *) storeMem; // curTlv means next tlv elem + curtlv->type = memDesc->type; + curtlv->length = memDesc->length; + + tlv_header(storeMem); + storeMemLen -= tlv_header_length(); + + if (storeMemLen < curtlv->length) + return -1; + + if (EOK != + memcpy_s(storeMem, (size_t) storeMemLen, + ((char *) obj + memDesc->offset), + (size_t) memDesc->length)) { - return -1; + return -1; } - tlv_mem_forward (storeMem, memDesc->length); - storeMemLen -= memDesc->length; - tlv->length += (curtlv->length + (u32) tlv_header_length ()); + tlv_mem_forward(storeMem, memDesc->length); + storeMemLen -= memDesc->length; + tlv->length += (curtlv->length + (u32) tlv_header_length()); } } - return (int) (tlv->length + tlv_header_length ()); + + return (int) (tlv->length + tlv_header_length()); } /** * @Function nsfw_ss_store * @Description store object to memory * @param (in) objType - type of object - * @param (in) obj - address of object memory + * @param (in) obj - adderss of object memory * @param (in) storeMem - address of memory to store object data * @param (in) storeMemLen - maximal length of storage memory * @return positive integer means length of memory cost on success. return -1 if error */ -int -nsfw_ss_store (u16 objType, void *obj, void *storeMem, u32 storeMemLen) +int nsfw_ss_store(u16 objType, void *obj, void *storeMem, u32 storeMemLen) { - return nsfw_ss_storeObjMem (NSFW_SS_TYPE_SET_MEMBER_OBJ (objType, 0), - obj, storeMem, storeMemLen); + return nsfw_ss_store_obj_mem(NSFW_SS_TYPE_SET_MEMBER_OBJ(objType, 0), + obj, storeMem, storeMemLen); } /** - * @Function nsfw_ss_restoreObjArray + * @Function nsfw_ss_restore_obj_array * @Description restore array of objects * @param (in) objType - type of object - * @param (in) objMem - object memory to restore - * @param (in) mem - memory of storage - * @param (in) storeMemLength - maximal length of storage memory - * @return 0 on success , -1 on error + * @param (in) obj_update - memory of object/storage memory info + * @return 0 on succss , -1 on error */ -NSTACK_STATIC int -nsfw_ss_restoreObjArray (int objType, void *objMem, void *mem, - u32 storeMemLength) +NSTACK_STATIC int nsfw_ss_restore_obj_array(int objType, + nsfw_ss_obj_restore_t * + obj_update) { - if (storeMemLength < tlv_header_length ()) - return -1; - nsfw_ss_tlv_t *arrayTlv = (nsfw_ss_tlv_t *) mem; - storeMemLength -= tlv_header_length (); - tlv_header (mem); - if (0 == arrayTlv->length || storeMemLength < arrayTlv->length) - return -1; - storeMemLength = arrayTlv->length; // Only cares tlv->value - nsfw_ss_objDesc_t *objDesc = nsfw_ss_getObjDescFromType ((u16) objType); - if (NULL == objDesc) - return -1; - - /* Now we are going to iterate every object */ - u32 objCnt = 0; - while (storeMemLength) + if (obj_update->storeMemLen < tlv_header_length()) + return -1; + + nsfw_ss_obj_restore_t obj_res = { NULL, NULL, 0, 0 }; + nsfw_ss_tlv_t *arrayTlv = (nsfw_ss_tlv_t *) (obj_update->mem); + obj_update->storeMemLen -= tlv_header_length(); + tlv_header(obj_update->mem); + if (0 == arrayTlv->length || obj_update->storeMemLen < arrayTlv->length) + return -1; + obj_update->storeMemLen = arrayTlv->length; // Only cares tlv->value + + nsfw_ss_obj_desc_t *objDesc = + nsfw_ss_get_obj_desc_from_type((u16) objType); + if (NULL == objDesc) + return -1; + + /* Now we are going to iterate every object */ + u32 objCnt = 0; + while (obj_update->storeMemLen) { - if (storeMemLength < tlv_header_length ()) - return -1; // Format error - nsfw_ss_tlv_t *objTlv = (nsfw_ss_tlv_t *) mem; - if ((int) NSFW_SS_TYPE_GETOBJ (objTlv->type) != objType) + if (obj_update->storeMemLen < tlv_header_length()) + return -1; // Format error + + nsfw_ss_tlv_t *objTlv = (nsfw_ss_tlv_t *) (obj_update->mem); + if ((int) NSFW_SS_TYPE_GETOBJ(objTlv->type) != objType) { - return -1; + return -1; } - int ret = - nsfw_ss_restore ((char *) objMem + (u64) objDesc->objSize * objCnt, - mem, storeMemLength); - if (-1 == ret) - return -1; - objCnt++; - tlv_mem_forward (mem, (objTlv->length + tlv_header_length ())); - storeMemLength -= (objTlv->length + tlv_header_length ()); + + obj_res.objMem = + (void *) ((char *) (obj_update->objMem) + + (u64) objDesc->objSize * objCnt); + obj_res.mem = obj_update->mem; + obj_res.storeMemLen = obj_update->storeMemLen; + + int ret = nsfw_ss_restore(&obj_res); + if (-1 == ret) + return -1; + objCnt++; + tlv_mem_forward(obj_update->mem, + (objTlv->length + tlv_header_length())); + obj_update->storeMemLen -= (objTlv->length + tlv_header_length()); } - return 0; + + return 0; } /** * @Function nsfw_ss_restore * @Description restore object from memory - * @param (in) objMem - memory of object - * @param (in) mem - memory of storage - * @param (in) storeMemLen - maximal length of storage memory + * @param (in) obj_res - memory of object/storage memory info * @return positive integer stands on object type, -1 on error */ -int -nsfw_ss_restore (void *objMem, void *mem, u32 storeMemLen) +int nsfw_ss_restore(nsfw_ss_obj_restore_t * obj_res) { - if (NULL == objMem || NULL == mem || 0 == storeMemLen) - return -1; - - // example of object - /* struct A{ */ - /* int a1; */ - /* struct A2 a2; --> struct A2 {int a2} */ - /* struct A3 a3[2]; --> struct A3 [{int a3}, {int a3}] */ - /* } */ - - /* -------------------------------------------- */// -- - /* | type(object) | length | */// type length - /* | -------------------------------------- | */// -- - /* | | type(item) | length | | */// member a1 - /* | | item value (object->member) | | */// -- - /* | -------------------------------------- | */// object a2 - /* | | type(object) | length | | */// -- - /* | | ------------------------------- | | */// member a2 - /* | | | type(item) | length | | | */// -- - /* | | | item value (object->member) | | | */// -- - /* | | ------------------------------- | | */// - /* | -------------------------------------- | */// - /* | | type(object array) | length | | */// array member a3 - /* | | ------------------------------- | | */// -- - /* | | | type(object) | length | | | */// object a3_1 - /* | | | ----------------------------| | | */// -- - /* | | | type(item) | length | | | */// member a3_1_1 - /* | | | item value (object->member) | | | */ - /* | | | ----------------------------| | | */ - /* | | ------------------------------- | | */ - /* | | | type(object) | length | | | */ - /* | | | ----------------------------| | | */ - /* | | | type(item) | length | | | */ - /* | | | item value (object->member) | | | */ - /* | | | ----------------------------| | | */ - /* | | ------------------------------- | | */ - /* | |------------------------------------| | */ - /* -------------------------------------------- */ - if (storeMemLen < tlv_header_length ()) - return -1; - nsfw_ss_tlv_t *tlv = (nsfw_ss_tlv_t *) mem; - storeMemLen -= tlv_header_length (); - tlv_header (mem); - nsfw_ss_objDesc_t *objDesc = - nsfw_ss_getObjDescFromType (NSFW_SS_TYPE_GETOBJ (tlv->type)); - if (NULL == objDesc) + if (NULL == obj_res || NULL == obj_res->objMem || NULL == obj_res->mem + || 0 == obj_res->storeMemLen) + return -1; + + // example of object + /* struct A{ */ + /* int a1; */ + /* struct A2 a2; --> struct A2 {int a2} */ + /* struct A3 a3[2]; --> struct A3 [{int a3}, {int a3}] */ + /* } */ + + /* -------------------------------------------- */// -- + /* | type(object) | length | */// type length + /* | -------------------------------------- | */// -- + /* | | type(item) | length | | */// member a1 + /* | | item value (object->member) | | */// -- + /* | -------------------------------------- | */// object a2 + /* | | type(object) | length | | */// -- + /* | | ------------------------------- | | */// member a2 + /* | | | type(item) | length | | | */// -- + /* | | | item value (object->member) | | | */// -- + /* | | ------------------------------- | | */ + /* | -------------------------------------- | */ + /* | | type(object array) | length | | */// array member a3 + /* | | ------------------------------- | | */// -- + /* | | | type(object) | length | | | */// object a3_1 + /* | | | ----------------------------| | | */// -- + /* | | | type(item) | length | | | */// member a3_1_1 + /* | | | item value (object->member) | | | */ + /* | | | ----------------------------| | | */ + /* | | ------------------------------- | | */ + /* | | | type(object) | length | | | */ + /* | | | ----------------------------| | | */ + /* | | | type(item) | length | | | */ + /* | | | item value (object->member) | | | */ + /* | | | ----------------------------| | | */ + /* | | ------------------------------- | | */ + /* | |------------------------------------| | */ + /* -------------------------------------------- */ + + if (obj_res->storeMemLen < tlv_header_length()) + return -1; + + nsfw_ss_tlv_t *tlv = (nsfw_ss_tlv_t *) (obj_res->mem); + obj_res->storeMemLen -= tlv_header_length(); + tlv_header(obj_res->mem); + + nsfw_ss_obj_restore_t obj_update = { NULL, NULL, 0, 0 }; + nsfw_ss_obj_desc_t *objDesc = + nsfw_ss_get_obj_desc_from_type(NSFW_SS_TYPE_GETOBJ(tlv->type)); + if (NULL == objDesc) { - return -1; + return -1; } - if (!NSFW_SS_TYPE_IS_MEMBER_OBJ (tlv->type)) - return -1; - if (0 == tlv->length || storeMemLen < tlv->length) - return -1; - - /* Now we go to inner of object */ - storeMemLen = tlv->length; /* Only care about tlv values */ - while (storeMemLen) + + if (!NSFW_SS_TYPE_IS_MEMBER_OBJ(tlv->type)) + return -1; + + if (0 == tlv->length || obj_res->storeMemLen < tlv->length) + return -1; + + /* Now we go to inner of object */ + obj_res->storeMemLen = tlv->length; /* Only care about tlv values */ + while (obj_res->storeMemLen) { - if (storeMemLen < tlv_header_length ()) - return -1; // Format error - nsfw_ss_tlv_t *curtlv = (nsfw_ss_tlv_t *) mem; - nsfw_ss_objMemDesc_t *memDesc = - nsfw_ss_getMemDescFromType (curtlv->type, objDesc); - if (NULL == memDesc) + if (obj_res->storeMemLen < tlv_header_length()) + return -1; // Format error + + nsfw_ss_tlv_t *curtlv = (nsfw_ss_tlv_t *) (obj_res->mem); + + nsfw_ss_obj_mem_desc_t *memDesc = + nsfw_ss_get_mem_desc_from_type(curtlv->type, objDesc); + if (NULL == memDesc) { // This type not support - storeMemLen -= tlv_header_length (); - tlv_header (mem); - if (storeMemLen < curtlv->length) - return -1; - tlv_mem_forward (mem, curtlv->length); - storeMemLen -= curtlv->length; - continue; + obj_res->storeMemLen -= tlv_header_length(); + tlv_header(obj_res->mem); + if (obj_res->storeMemLen < curtlv->length) + return -1; + tlv_mem_forward(obj_res->mem, curtlv->length); + obj_res->storeMemLen -= curtlv->length; + continue; } - if (NSFW_SS_TYPE_IS_MEMBER_OBJ (curtlv->type)) + + obj_update.objMem = + (void *) ((char *) (obj_res->objMem) + memDesc->offset); + obj_update.mem = obj_res->mem; + obj_update.storeMemLen = obj_res->storeMemLen; + + if (NSFW_SS_TYPE_IS_MEMBER_OBJ(curtlv->type)) { - if (NSFW_SS_TYPE_IS_MEMBER_ARRAY (curtlv->type)) + if (NSFW_SS_TYPE_IS_MEMBER_ARRAY(curtlv->type)) { - int ret = - nsfw_ss_restoreObjArray ((int) - NSFW_SS_TYPE_GETOBJ (curtlv->type), - (void *) ((char *) objMem + - memDesc->offset), mem, - storeMemLen); - if (-1 == ret) - return -1; + int ret = + nsfw_ss_restore_obj_array((int) + NSFW_SS_TYPE_GETOBJ + (curtlv->type), + &obj_update); + if (-1 == ret) + return -1; } - else + else { - int ret = - nsfw_ss_restore ((void *) ((char *) objMem + - memDesc->offset), mem, - storeMemLen); - if (-1 == ret) - return -1; + int ret = nsfw_ss_restore(&obj_update); + if (-1 == ret) + return -1; } - tlv_mem_forward (mem, (curtlv->length + tlv_header_length ())); - storeMemLen -= (curtlv->length + tlv_header_length ()); + + tlv_mem_forward(obj_res->mem, + (curtlv->length + tlv_header_length())); + obj_res->storeMemLen -= (curtlv->length + tlv_header_length()); } - else + else { - tlv_header (mem); - storeMemLen -= tlv_header_length (); - NSFW_LOGDBG - ("curtlv->type(%u), curtlv->length(%u), memDesc->offset(%u), memDesc->length(%u), mem(%u)", - curtlv->type, curtlv->length, memDesc->offset, memDesc->length, - *(u32 *) mem); - if (storeMemLen < curtlv->length) - return -1; - if (EOK != - MEMCPY_S ((void *) ((char *) objMem + memDesc->offset), - (size_t) memDesc->length, mem, - (size_t) curtlv->length)) + tlv_header(obj_res->mem); + obj_res->storeMemLen -= tlv_header_length(); + + NSFW_LOGDBG + ("curtlv->type(%u), curtlv->length(%u), memDesc->offset(%u), memDesc->length(%u), mem(%u)", + curtlv->type, curtlv->length, memDesc->offset, + memDesc->length, *(u32 *) (obj_res->mem)); + + if (obj_res->storeMemLen < curtlv->length) + return -1; + if (EOK != + memcpy_s((void *) ((char *) (obj_res->objMem) + + memDesc->offset), + (size_t) memDesc->length, obj_res->mem, + (size_t) curtlv->length)) { - return -1; + return -1; } - tlv_mem_forward (mem, curtlv->length); - storeMemLen -= curtlv->length; + + tlv_mem_forward(obj_res->mem, curtlv->length); + obj_res->storeMemLen -= curtlv->length; } } - return (int) tlv->type; + + return (int) tlv->type; } /** - * @Function nsfw_ss_getObjStoreMemLen + * @Function nsfw_ss_get_obj_store_mem_len * @Description Get the maximal memory it needs * @param (in) objType - type of object * @return length of memory needs, -1 if error */ -int -nsfw_ss_getObjStoreMemLen (int objType) +int nsfw_ss_get_obj_store_mem_len(int objType) { - u32 maxlength = tlv_header_length (); - u32 i; - nsfw_ss_objDesc_t *objDesc = nsfw_ss_getObjDescFromType ((u16) objType); - if (!objDesc) - return -1; - for (i = 0; i < objDesc->memNum; i++) + u32 maxlength = tlv_header_length(); + u32 i; + + nsfw_ss_obj_desc_t *objDesc = + nsfw_ss_get_obj_desc_from_type((u16) objType); + if (!objDesc) + return -1; + for (i = 0; i < objDesc->memNum; i++) { - nsfw_ss_objMemDesc_t *memDesc = &objDesc->memDesc[i]; - int temp_len; - if (NSFW_SS_TYPE_IS_MEMBER_OBJ (memDesc->type)) + nsfw_ss_obj_mem_desc_t *memDesc = &objDesc->memDesc[i]; + int temp_len; + if (NSFW_SS_TYPE_IS_MEMBER_OBJ(memDesc->type)) { - nsfw_ss_objDesc_t *curObjDesc = - nsfw_ss_getObjDescFromType (NSFW_SS_TYPE_GETOBJ (memDesc->type)); - if (NULL == curObjDesc) - return -1; - if (NSFW_SS_TYPE_IS_MEMBER_ARRAY (memDesc->type)) + nsfw_ss_obj_desc_t *curObjDesc = + nsfw_ss_get_obj_desc_from_type(NSFW_SS_TYPE_GETOBJ + (memDesc->type)); + if (NULL == curObjDesc) + return -1; + + if (NSFW_SS_TYPE_IS_MEMBER_ARRAY(memDesc->type)) { - maxlength += tlv_header_length (); // array length - u32 arrSize = memDesc->length / curObjDesc->objSize; - u32 j; - for (j = 0; j < arrSize; j++) + maxlength += tlv_header_length(); // array length + + u32 arrSize = memDesc->length / curObjDesc->objSize; + u32 j; + for (j = 0; j < arrSize; j++) { - temp_len = - nsfw_ss_getObjStoreMemLen ((int) curObjDesc->objType); - if (temp_len < 0) - return -1; - maxlength += (u32) temp_len; + temp_len = + nsfw_ss_get_obj_store_mem_len((int) + curObjDesc->objType); + if (temp_len < 0) + return -1; + maxlength += (u32) temp_len; } } - else + else { - temp_len = - nsfw_ss_getObjStoreMemLen ((int) curObjDesc->objType); - if (temp_len < 0) - return -1; - maxlength += (u32) temp_len; + temp_len = + nsfw_ss_get_obj_store_mem_len((int) curObjDesc->objType); + if (temp_len < 0) + return -1; + maxlength += (u32) temp_len; } } - else + else { - maxlength += ((u32) tlv_header_length () + memDesc->length); + maxlength += ((u32) tlv_header_length() + memDesc->length); } } - return (int) maxlength; + return (int) maxlength; } #ifdef __cplusplus diff --git a/src/framework/snapshot/fw_ss_tlv.h b/src/framework/snapshot/fw_snapshot.h index 0bfbd91..810f289 100644 --- a/src/framework/snapshot/fw_ss_tlv.h +++ b/src/framework/snapshot/fw_snapshot.h @@ -28,9 +28,9 @@ extern "C"{ typedef struct _nsfw_ss_tlv { - u16 type; - u32 length; - void *value; + u16 type; + u32 length; + void *value; } nsfw_ss_tlv_t; #define tlv_header_length() ((size_t)(&((nsfw_ss_tlv_t*)0)->value)) |