diff --git a/.gitee/ISSUE_TEMPLATE.zh-CN.md b/.gitee/ISSUE_TEMPLATE.zh-CN.md new file mode 100755 index 00000000..f09d98dd --- /dev/null +++ b/.gitee/ISSUE_TEMPLATE.zh-CN.md @@ -0,0 +1,13 @@ +### 该问题是怎么引起的? + + + +### 重现步骤 + + + +### 报错信息 + + + + diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md new file mode 100755 index 00000000..33948fdc --- /dev/null +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -0,0 +1,15 @@ +### 相关的Issue + + +### 原因(目的、解决的问题等) + + +### 描述(做了什么,变更了什么) + + +### 测试用例(新增、改动、可能影响的功能) + + + + + diff --git a/ability/config/device_resource_if.c b/ability/config/device_resource_if.c new file mode 100755 index 00000000..16863d67 --- /dev/null +++ b/ability/config/device_resource_if.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "device_resource_if.h" +#include "hcs_tree_if.h" +#include "hdf_log.h" + +static void HcsIfaceConstruct(struct DeviceResourceIface *instance) +{ + instance->GetRootNode = HcsGetRootNode; + instance->GetBool = HcsGetBool; + instance->GetUint8 = HcsGetUint8; + instance->GetUint8ArrayElem = HcsGetUint8ArrayElem; + instance->GetUint8Array = HcsGetUint8Array; + instance->GetUint16 = HcsGetUint16; + instance->GetUint16ArrayElem = HcsGetUint16ArrayElem; + instance->GetUint16Array = HcsGetUint16Array; + instance->GetUint32 = HcsGetUint32; + instance->GetUint32ArrayElem = HcsGetUint32ArrayElem; + instance->GetUint32Array = HcsGetUint32Array; + instance->GetUint64 = HcsGetUint64; + instance->GetUint64ArrayElem = HcsGetUint64ArrayElem; + instance->GetUint64Array = HcsGetUint64Array; + instance->GetString = HcsGetString; + instance->GetStringArrayElem = HcsGetStringArrayElem; + instance->GetElemNum = HcsGetElemNum; + instance->GetNodeByMatchAttr = HcsGetNodeByMatchAttr; + instance->GetChildNode = HcsGetChildNode; + instance->GetNodeByRefAttr = HcsGetNodeByRefAttr; +} + +static bool DeviceResourceIfaceConstruct(struct DeviceResourceIface *instance, DeviceResourceType type) +{ + switch (type) { + case HDF_CONFIG_SOURCE: + HcsIfaceConstruct(instance); + break; + default: + HDF_LOGE("%s: Currently, this configuration type is not supported. the type is %d", __func__, type); + return false; + } + return true; +} + +struct DeviceResourceIface *DeviceResourceGetIfaceInstance(DeviceResourceType type) +{ + static struct DeviceResourceIface *instance = NULL; + if (instance == NULL) { + static struct DeviceResourceIface singletonInstance; + if (!DeviceResourceIfaceConstruct(&singletonInstance, type)) { + return NULL; + } + instance = &singletonInstance; + } + return instance; +} diff --git a/ability/config/hcs_parser/include/hcs_blob_if.h b/ability/config/hcs_parser/include/hcs_blob_if.h new file mode 100755 index 00000000..c1f8547b --- /dev/null +++ b/ability/config/hcs_parser/include/hcs_blob_if.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_BLOB_IF_H +#define HCS_BLOB_IF_H + +#include +#include "hdf_base.h" + +#define CONFIG_NODE 0x1 +#define CONFIG_ATTR 0x2 +#define CONFIG_REFERENCE 0x3 +#define CONFIG_ARRAY 0x4 +#define CONFIG_BYTE 0x10 +#define CONFIG_WORD 0x11 +#define CONFIG_DWORD 0x12 +#define CONFIG_QWORD 0x13 +#define CONFIG_STRING 0x14 + +struct HbcHeader { + uint32_t magicNumber; + uint32_t versionMajor; + uint32_t versionMinor; + uint32_t checkSum; + int32_t totalSize; +}; + +#define HBC_MAGIC_NUMBER 0xA00AA00A +#define HBC_HEADER_LENGTH sizeof(struct HbcHeader) +#define HBC_BLOB_MAX_LENGTH (1024 * 1024 * 10) // The maximum length is 10 MB. +#define HBC_ROOT_NAME "root" + +bool HcsIsByteAlign(void); +#define HCS_ALIGN_SIZE 4 +static inline size_t HcsAlignSize(size_t size) +{ + return (size + HCS_ALIGN_SIZE - 1) & (~(HCS_ALIGN_SIZE - 1)); +} + +static inline uint8_t HcsByteCodeToUint8(const char *start) +{ + return *(uint8_t *)(start); +} + +static inline uint16_t HcsByteCodeToUint16(const char *start) +{ + return *(uint16_t *)(start); +} + +static inline uint32_t HcsByteCodeToUint32(const char *start) +{ + return *(uint32_t *)(start); +} + +static inline uint64_t HcsByteCodeToUint64(const char *start) +{ + return *(uint64_t *)(start); +} + +static inline uint32_t HcsGetPrefix(const char *start) +{ + return HcsIsByteAlign() ? HcsByteCodeToUint32(start) : HcsByteCodeToUint8(start); +} + +#define HCS_DWORD_LENGTH 4 +#define HCS_QWORD_LENGTH 8 +#define HCS_PREFIX_LENGTH (HcsIsByteAlign() ? HCS_DWORD_LENGTH : 1) +#define HCS_BYTE_LENGTH (HcsIsByteAlign() ? HCS_DWORD_LENGTH : 1) +#define HCS_WORD_LENGTH (HcsIsByteAlign() ? HCS_DWORD_LENGTH : 2) +#define HCS_STRING_LENGTH(str) (HcsIsByteAlign() ? HcsAlignSize(strlen(str) + 1) : (strlen(str) + 1)) // add the '\0'. +int32_t HcsGetDataTypeOffset(const char *start); +int32_t HcsGetAttrLength(const char *start); +int32_t HcsGetNodeOrAttrLength(const char *start); +int32_t HcsGetNodeLength(const char *blob); +bool HcsCheckBlobFormat(const char *start, uint32_t length); +bool HcsSwapToUint8(uint8_t *value, const char *realValue, uint32_t type); +bool HcsSwapToUint16(uint16_t *value, const char *realValue, uint32_t type); +bool HcsSwapToUint32(uint32_t *value, const char *realValue, uint32_t type); +bool HcsSwapToUint64(uint64_t *value, const char *realValue, uint32_t type); + +#endif // HCS_BLOB_IF_H \ No newline at end of file diff --git a/ability/config/hcs_parser/include/hcs_generate_tree.h b/ability/config/hcs_parser/include/hcs_generate_tree.h new file mode 100755 index 00000000..59bfc3d8 --- /dev/null +++ b/ability/config/hcs_parser/include/hcs_generate_tree.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_GENERATE_TREE_H +#define HCS_GENERATE_TREE_H + +#include "device_resource_if.h" + +#define TREE_STACK_MAX 64 +struct TreeStack { + uint32_t offset; // the offset of node in blob + struct DeviceResourceNode *node; // the node is the head node of every layer tree +}; +int32_t GenerateCfgTree(const char *treeStart, int32_t length, char *treeMem, struct DeviceResourceNode **root); + +#endif // HCS_GENERATE_TREE_H \ No newline at end of file diff --git a/ability/config/hcs_parser/include/hcs_parser.h b/ability/config/hcs_parser/include/hcs_parser.h new file mode 100755 index 00000000..a58c60bc --- /dev/null +++ b/ability/config/hcs_parser/include/hcs_parser.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_PARSER_H +#define HCS_PARSER_H + +#include "device_resource_if.h" + +bool HcsDecompile(const char *hcsBlob, uint32_t offset, struct DeviceResourceNode **root); + +#endif // HCS_PARSER_H \ No newline at end of file diff --git a/ability/config/hcs_parser/include/hcs_tree_if.h b/ability/config/hcs_parser/include/hcs_tree_if.h new file mode 100755 index 00000000..f4d9e096 --- /dev/null +++ b/ability/config/hcs_parser/include/hcs_tree_if.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_TREE_IF_H +#define HCS_TREE_IF_H + +#include "device_resource_if.h" +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define HCS_MATCH_ATTR "match_attr" + +const struct DeviceResourceNode *HcsGetRootNode(void); +bool HcsGetBool(const struct DeviceResourceNode *node, const char *attrName); +int32_t HcsGetUint8(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint8_t def); +int32_t HcsGetUint8ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint8_t *value, uint8_t def); +int32_t HcsGetUint8Array(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint32_t len, + uint8_t def); +int32_t HcsGetUint16(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint16_t def); +int32_t HcsGetUint16ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint16_t *value, uint16_t def); +int32_t HcsGetUint16Array(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint32_t len, + uint16_t def); +int32_t HcsGetUint32(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, uint32_t def); +int32_t HcsGetUint32ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint32_t *value, uint32_t def); +int32_t HcsGetUint32Array(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, + uint32_t len, uint32_t def); +int32_t HcsGetUint64(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, uint64_t def); +int32_t HcsGetUint64ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint64_t *value, uint64_t def); +int32_t HcsGetUint64Array(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, + uint32_t len, uint64_t def); +int32_t HcsGetStringArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + const char **value, const char *def); +int32_t HcsGetString(const struct DeviceResourceNode *node, const char *attrName, const char **value, const char *def); +int32_t HcsGetElemNum(const struct DeviceResourceNode *node, const char *attrName); +const struct DeviceResourceNode *HcsGetNodeByMatchAttr(const struct DeviceResourceNode *node, const char *attrValue); +const struct DeviceResourceNode *HcsGetChildNode(const struct DeviceResourceNode *node, const char *nodeName); +const struct DeviceResourceNode *HcsGetNodeByRefAttr(const struct DeviceResourceNode *node, const char *attrName); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // HCS_TREE_IF_H \ No newline at end of file diff --git a/ability/config/hcs_parser/src/hcs_blob_if.c b/ability/config/hcs_parser/src/hcs_blob_if.c new file mode 100755 index 00000000..f4159e0f --- /dev/null +++ b/ability/config/hcs_parser/src/hcs_blob_if.c @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_blob_if.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hcs_blob_if + +static bool g_byteAlign = false; + +bool HcsIsByteAlign() +{ + return g_byteAlign; +} + +int32_t HcsGetDataTypeOffset(const char *start) +{ + int32_t len; + switch (HcsGetPrefix(start)) { + case CONFIG_BYTE: + len = HCS_BYTE_LENGTH + HCS_PREFIX_LENGTH; + break; + case CONFIG_WORD: + len = HCS_WORD_LENGTH + HCS_PREFIX_LENGTH; + break; + case CONFIG_DWORD: + case CONFIG_REFERENCE: + len = HCS_DWORD_LENGTH + HCS_PREFIX_LENGTH; + break; + case CONFIG_QWORD: + len = HCS_QWORD_LENGTH + HCS_PREFIX_LENGTH; + break; + case CONFIG_STRING: + len = HCS_STRING_LENGTH(start + HCS_PREFIX_LENGTH) + HCS_PREFIX_LENGTH; + break; + default: + len = HDF_FAILURE; + break; + } + return len; +} + +static int32_t HcsGetArrayLength(const char *start) +{ + int32_t arrayLen = HCS_PREFIX_LENGTH + HCS_WORD_LENGTH; + uint16_t count; + (void)HcsSwapToUint16(&count, start + HCS_PREFIX_LENGTH, CONFIG_WORD); + for (uint16_t i = 0; i < count; i++) { + int32_t lenData = HcsGetDataTypeOffset(start + arrayLen); + if (lenData < 0) { + return HDF_FAILURE; + } + arrayLen += lenData; + } + return arrayLen; +} + +int32_t HcsGetAttrLength(const char *start) +{ + int32_t length = HCS_PREFIX_LENGTH + HCS_STRING_LENGTH(start + HCS_PREFIX_LENGTH); + int32_t dataLen; + switch (HcsGetPrefix(start + length)) { + case CONFIG_BYTE: + case CONFIG_WORD: + case CONFIG_DWORD: + case CONFIG_QWORD: + case CONFIG_STRING: + case CONFIG_REFERENCE: + dataLen = HcsGetDataTypeOffset(start + length); + break; + case CONFIG_ARRAY: + dataLen = HcsGetArrayLength(start + length); + break; + default: + dataLen = HDF_FAILURE; + break; + } + return (dataLen < 0) ? HDF_FAILURE : (dataLen + length); +} + +int32_t HcsGetNodeOrAttrLength(const char *start) +{ + int32_t length; + switch (HcsGetPrefix(start)) { + case CONFIG_NODE: + length = HCS_STRING_LENGTH(start + HCS_PREFIX_LENGTH) + HCS_PREFIX_LENGTH + HCS_DWORD_LENGTH; + break; + case CONFIG_ATTR: + length = HcsGetAttrLength(start); + break; + default: + length = HDF_FAILURE; + break; + } + return length; +} + +int32_t HcsGetNodeLength(const char *blob) +{ + int32_t rootLen = HcsGetNodeOrAttrLength(blob); + if (rootLen < 0) { + HDF_LOGE("%s failed, the rootLen is %d", __func__, rootLen); + return HDF_FAILURE; + } + rootLen += HcsByteCodeToUint32(blob + HCS_PREFIX_LENGTH + HCS_STRING_LENGTH(blob + HCS_PREFIX_LENGTH)); + return rootLen; +} + +bool HcsSwapToUint8(uint8_t *value, const char *realValue, uint32_t type) +{ + if (type == CONFIG_BYTE) { + *value = g_byteAlign ? (uint8_t)HcsByteCodeToUint32(realValue) : HcsByteCodeToUint8(realValue); + return true; + } + HDF_LOGE("%s failed, type: %u", __func__, type); + return false; +} + +bool HcsSwapToUint16(uint16_t *value, const char *realValue, uint32_t type) +{ + uint8_t data; + if (type == CONFIG_WORD) { + *value = g_byteAlign ? (uint16_t)HcsByteCodeToUint32(realValue) : HcsByteCodeToUint16(realValue); + return true; + } + if (HcsSwapToUint8(&data, realValue, type)) { + *value = data; + return true; + } + HDF_LOGE("%s failed, type: %u", __func__, type); + return false; +} + +bool HcsSwapToUint32(uint32_t *value, const char *realValue, uint32_t type) +{ + uint16_t data; + if (type == CONFIG_DWORD) { + *value = HcsByteCodeToUint32(realValue); + return true; + } + if (HcsSwapToUint16(&data, realValue, type)) { + *value = data; + return true; + } + HDF_LOGE("%s failed, type: %u", __func__, type); + return false; +} + +bool HcsSwapToUint64(uint64_t *value, const char *realValue, uint32_t type) +{ + uint32_t data; + if (type == CONFIG_QWORD) { + *value = HcsByteCodeToUint64(realValue); + return true; + } + if (HcsSwapToUint32(&data, realValue, type)) { + *value = data; + return true; + } + HDF_LOGE("%s failed, type: %u", __func__, type); + return false; +} + +static bool CheckHcsBlobLength(const char *start, uint32_t length, struct HbcHeader *header) +{ + uint32_t rootNodeLen = HCS_STRING_LENGTH(HBC_ROOT_NAME) + HCS_PREFIX_LENGTH + HCS_DWORD_LENGTH; + uint32_t minLength = rootNodeLen + HBC_HEADER_LENGTH; + uint32_t blobLength; + if (header->totalSize >= 0) { + blobLength = HBC_HEADER_LENGTH + header->totalSize; + g_byteAlign = false; + HDF_LOGE("%s: the blobLength: %u, byteAlign: %d, totalSize: %d", __func__, blobLength, + g_byteAlign, header->totalSize); + } else { + blobLength = HBC_HEADER_LENGTH - header->totalSize; + g_byteAlign = true; + HDF_LOGE("%s: the blobLength: %u, byteAlign: %d, totalSize: %d", __func__, blobLength, + g_byteAlign, header->totalSize); + } + if ((length != blobLength) || (blobLength < minLength)) { + HDF_LOGE("%s failed, Hcsblob file length is %u, But the length of calculation is %u", + __func__, length, blobLength); + return false; + } + return true; +} + +bool HcsCheckBlobFormat(const char *start, uint32_t length) +{ + struct HbcHeader *header = NULL; + if ((start == NULL) || (length < HBC_HEADER_LENGTH) || (length > HBC_BLOB_MAX_LENGTH)) { + HDF_LOGE("%s failed, Hcsblob file length is %u", __func__, length); + return false; + } + header = (struct HbcHeader *)start; + if (header->magicNumber != HBC_MAGIC_NUMBER) { + HDF_LOGE("%s failed, the magic of HBC is %x", __func__, header->magicNumber); + return false; + } + if (!CheckHcsBlobLength(start, length, header)) { + return false; + } + return true; +} diff --git a/ability/config/hcs_parser/src/hcs_generate_tree.c b/ability/config/hcs_parser/src/hcs_generate_tree.c new file mode 100755 index 00000000..94083057 --- /dev/null +++ b/ability/config/hcs_parser/src/hcs_generate_tree.c @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_generate_tree.h" +#include "hcs_blob_if.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG hcs_generate_tree + +static struct DeviceResourceNode *GetParentNode(int32_t offset, const struct TreeStack *treeStack, + int32_t *treeLayer, int32_t configOffset) +{ + int32_t parentLayer = *treeLayer; + while ((parentLayer > 0) && (configOffset + offset > 0)) { + if (treeStack[parentLayer].offset >= (uint32_t)(configOffset + offset)) { + *treeLayer = parentLayer; + return treeStack[parentLayer].node; + } + parentLayer--; + } + return NULL; +} + +static struct DeviceResourceNode *CreateTreeNode(const char *start, int32_t offset, + struct DeviceResourceNode *parentNode, char **treeMem) +{ + struct DeviceResourceNode *newNode = (struct DeviceResourceNode *)(*treeMem); + *treeMem += sizeof(struct DeviceResourceNode); + newNode->name = start + offset + HCS_PREFIX_LENGTH; + newNode->hashValue = offset + sizeof(struct HbcHeader); + if (parentNode != NULL) { + newNode->parent = parentNode; + struct DeviceResourceNode *curNode = parentNode->child; + while ((curNode != NULL) && (curNode->sibling != NULL)) { + curNode = curNode->sibling; + } + if (curNode == NULL) { + parentNode->child = newNode; + } else { + curNode->sibling = newNode; + } + } + return newNode; +} + +static bool UpdateTreeStack(struct TreeStack **treeStack, int32_t *treeLayer, struct DeviceResourceNode *newNode, + uint32_t offset) +{ + if (*treeLayer >= (TREE_STACK_MAX - 1)) { + HDF_LOGE("%s failed, the treeLayer error. treeLayer: %d", __func__, *treeLayer); + return false; + } + (*treeLayer)++; + (*treeStack)[*treeLayer].node = newNode; + (*treeStack)[*treeLayer].offset = offset; + return true; +} + +static bool AddAttrInNode(const char *start, struct DeviceResourceNode *parentNode, char **treeMem) +{ + if (parentNode == NULL) { + HDF_LOGE("%s failed, the parentNode is NULL", __func__); + return false; + } + struct DeviceResourceAttr *newAttr = (struct DeviceResourceAttr *)(*treeMem); + *treeMem += sizeof(struct DeviceResourceAttr); + newAttr->name = start + HCS_PREFIX_LENGTH; + newAttr->value = start + HCS_PREFIX_LENGTH + HCS_STRING_LENGTH(newAttr->name); + struct DeviceResourceAttr *curAttr = parentNode->attrData; + parentNode->attrData = newAttr; + newAttr->next = curAttr; + return true; +} + +static int32_t ParseByteCode(const char *treeStart, int32_t offset, char **treeMem, + struct TreeStack **treeStack, int32_t *treeLayerOrMemLen) +{ + int32_t termOffset = HcsGetNodeOrAttrLength(treeStart + offset); + if (termOffset <= 0) { + HDF_LOGE("%s failed, HcsGetNodeOrAttrLength failed, errno: %d", __func__, termOffset); + return HDF_FAILURE; + } + + struct DeviceResourceNode *parentOrCurNode = NULL; + switch (HcsGetPrefix(treeStart + offset)) { + case CONFIG_NODE: + if (*treeMem == NULL) { + *treeLayerOrMemLen += sizeof(struct DeviceResourceNode); + break; + } + parentOrCurNode = GetParentNode(offset, *treeStack, treeLayerOrMemLen, termOffset); + struct DeviceResourceNode *newNode = CreateTreeNode(treeStart, offset, parentOrCurNode, treeMem); + uint32_t newNodeOffset; + (void)HcsSwapToUint32(&newNodeOffset, treeStart + offset + HCS_STRING_LENGTH(newNode->name) + + HCS_PREFIX_LENGTH, CONFIG_DWORD); + newNodeOffset += offset + termOffset; + if (!UpdateTreeStack(treeStack, treeLayerOrMemLen, newNode, newNodeOffset)) { + return HDF_FAILURE; + } + break; + case CONFIG_ATTR: + if (*treeMem == NULL) { + *treeLayerOrMemLen += sizeof(struct DeviceResourceAttr); + break; + } + parentOrCurNode = GetParentNode(offset, *treeStack, treeLayerOrMemLen, termOffset); + if (!AddAttrInNode(treeStart + offset, parentOrCurNode, treeMem)) { + HDF_LOGE("%s failed, the AddAttrInNode error", __func__); + return HDF_FAILURE; + } + break; + default: + termOffset = HDF_FAILURE; + break; + } + return termOffset; +} + +int32_t GenerateCfgTree(const char *treeStart, int32_t length, char *treeMem, struct DeviceResourceNode **root) +{ + int32_t offset = 0; + int32_t treeLayerOrMemLen = 0; + + struct TreeStack *treeStack = (struct TreeStack *)OsalMemCalloc(sizeof(struct TreeStack) * TREE_STACK_MAX); + if (treeStack == NULL) { + HDF_LOGE("%s failed, treeStack malloc error", __func__); + return HDF_FAILURE; + } + + while ((offset < length) && (offset >= 0)) { + int32_t eachOffset = ParseByteCode(treeStart, offset, &treeMem, &treeStack, &treeLayerOrMemLen); + if (eachOffset <= 0) { + HDF_LOGE("%s failed, the ParseByteCode error", __func__); + treeLayerOrMemLen = eachOffset; + break; + } + offset += eachOffset; + } + if ((treeMem != NULL) && (root != NULL) && (treeLayerOrMemLen > 0)) { + // the treeStack[1] is root + *root = treeStack[1].node; + } + OsalMemFree(treeStack); + return treeLayerOrMemLen; +} diff --git a/ability/config/hcs_parser/src/hcs_parser.c b/ability/config/hcs_parser/src/hcs_parser.c new file mode 100755 index 00000000..65cbe951 --- /dev/null +++ b/ability/config/hcs_parser/src/hcs_parser.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_parser.h" +#include "hcs_blob_if.h" +#include "hcs_generate_tree.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG hcs_parser + +static int32_t GetHcsTreeSize(const char *blob, int32_t nodeLength) +{ + return GenerateCfgTree(blob, nodeLength, NULL, NULL); +} + +bool HcsDecompile(const char *hcsBlob, uint32_t offset, struct DeviceResourceNode **root) +{ + int32_t nodeLength = HcsGetNodeLength(hcsBlob + offset); + if (nodeLength < 0) { + HDF_LOGE("%s failed, HcsGetNodeLength failed", __func__); + return false; + } + + int32_t treeMemLength = GetHcsTreeSize(hcsBlob + offset, nodeLength); + if (treeMemLength <= 0) { + HDF_LOGE("%s failed, GetHcsTreeSize failed", __func__); + return false; + } + + char *treeMem = (char *)OsalMemCalloc(treeMemLength); + if (treeMem == NULL) { + HDF_LOGE("%s failed, OsalMemCalloc Device tree memory failed", __func__); + return false; + } + int32_t treeLayer = GenerateCfgTree(hcsBlob + offset, nodeLength, treeMem, root); + if (treeLayer <= 0) { + HDF_LOGE("%s failed, the treeLayer is %d", __func__, treeLayer); + OsalMemFree(treeMem); + *root = NULL; + return false; + } + return true; +} \ No newline at end of file diff --git a/ability/config/hcs_parser/src/hcs_tree_if.c b/ability/config/hcs_parser/src/hcs_tree_if.c new file mode 100755 index 00000000..dd0079f8 --- /dev/null +++ b/ability/config/hcs_parser/src/hcs_tree_if.c @@ -0,0 +1,437 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_tree_if.h" +#include "hcs_blob_if.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hcs_tree_if + +static struct DeviceResourceAttr *GetAttrInNode(const struct DeviceResourceNode *node, const char *attrName) +{ + struct DeviceResourceAttr *attr = NULL; + if ((node == NULL) || (attrName == NULL)) { + return NULL; + } + for (attr = node->attrData; attr != NULL; attr = attr->next) { + if ((attr->name != NULL) && (strcmp(attr->name, attrName) == 0)) { + break; + } + } + return attr; +} + +bool HcsGetBool(const struct DeviceResourceNode *node, const char *attrName) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + if ((attr == NULL) || (attr->value == NULL)) { + HDF_LOGE("%s failed, the node or attrName is NULL", __func__); + return false; + } + + uint8_t value; + if (!HcsSwapToUint8(&value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return false; + } + return value ? true : false; +} + +#define RETURN_DEFAULT_VALUE(attr, attrName, value, def) do { \ + if (((attr) == NULL) || ((attr)->value == NULL) || ((value) == NULL)) { \ + HDF_LOGE("%s failed, the attr of %s is NULL, or the value is NULL, return the default value", \ + __func__, ((attrName) == NULL) ? "error attrName" : (attrName)); \ + if ((value) != NULL) { \ + *(value) = (def); \ + } \ + return HDF_FAILURE; \ + } \ +} while (0) + +int32_t HcsGetUint8(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint8_t def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + if (!HcsSwapToUint8(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint16(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint16_t def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + if (!HcsSwapToUint16(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint32(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, uint32_t def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + if (!HcsSwapToUint32(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint64(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, uint64_t def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + if (!HcsSwapToUint64(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static const char *GetArrayElem(const struct DeviceResourceAttr *attr, uint32_t index) +{ + int32_t offset = HCS_WORD_LENGTH + HCS_PREFIX_LENGTH; + uint16_t count; + if ((HcsGetPrefix(attr->value) != CONFIG_ARRAY) || + !HcsSwapToUint16(&count, attr->value + HCS_PREFIX_LENGTH, CONFIG_WORD)) { + HDF_LOGE("%s failed, the attr of %s is not array", __func__, attr->name); + return NULL; + } + if (index >= count) { + HDF_LOGE("%s failed, the index: %u >= count: %u", __func__, index, count); + return NULL; + } + for (uint32_t i = 0; i < index; i++) { + int32_t result = HcsGetDataTypeOffset(attr->value + offset); + if (result < 0) { + return NULL; + } + offset += result; + } + return attr->value + offset; +} + +int32_t HcsGetUint8ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint8_t *value, uint8_t def) +{ + const char *realValue = NULL; + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + realValue = GetArrayElem(attr, index); + if (realValue == NULL) { + *value = def; + HDF_LOGE("%s failed, the realValue is NULL", __func__); + return HDF_FAILURE; + } + if (!HcsSwapToUint8(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_ERR_INVALID_OBJECT; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint16ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint16_t *value, uint16_t def) +{ + const char *realValue = NULL; + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + realValue = GetArrayElem(attr, index); + if (realValue == NULL) { + *value = def; + HDF_LOGE("%s failed, the realValue is NULL", __func__); + return HDF_FAILURE; + } + if (!HcsSwapToUint16(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_ERR_INVALID_OBJECT; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint32ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint32_t *value, uint32_t def) +{ + const char *realValue = NULL; + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + realValue = GetArrayElem(attr, index); + if (realValue == NULL) { + *value = def; + HDF_LOGE("%s failed, the realValue is NULL", __func__); + return HDF_FAILURE; + } + if (!HcsSwapToUint32(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_ERR_INVALID_OBJECT; + } + return HDF_SUCCESS; +} + +int32_t HcsGetUint64ArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint64_t *value, uint64_t def) +{ + const char *realValue = NULL; + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + realValue = GetArrayElem(attr, index); + if ((realValue == NULL) || !HcsSwapToUint64(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { + *value = def; + HDF_LOGE("%s failed, the realValue is NULL or incorrect prefix code", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +#define CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result) do { \ + if ((result) == HDF_ERR_INVALID_OBJECT) { \ + (ret) = HDF_ERR_INVALID_OBJECT; \ + HDF_LOGE("%s failed, the ret is %d", __func__, (result)); \ + continue; \ + } \ + if ((result) != HDF_SUCCESS) { \ + HDF_LOGE("%s failed, the ret is %d", __func__, (result)); \ + return result; \ + } \ +} while (0) + +int32_t HcsGetUint8Array(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint32_t len, + uint8_t def) +{ + if ((value == NULL) || (len == 0)) { + HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); + return HDF_FAILURE; + } + + int32_t ret = HDF_SUCCESS; + for (uint32_t i = 0; i < len; i++) { + int32_t result = HcsGetUint8ArrayElem(node, attrName, i, value + i, def); + // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. + CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); + } + return ret; +} + +int32_t HcsGetUint16Array(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint32_t len, + uint16_t def) +{ + if ((value == NULL) || (len == 0)) { + HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); + return HDF_FAILURE; + } + + int32_t ret = HDF_SUCCESS; + for (uint32_t i = 0; i < len; i++) { + int32_t result = HcsGetUint16ArrayElem(node, attrName, i, value + i, def); + // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. + CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); + } + return ret; +} + +int32_t HcsGetUint32Array(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, uint32_t len, + uint32_t def) +{ + if ((value == NULL) || (len == 0)) { + HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); + return HDF_FAILURE; + } + + int32_t ret = HDF_SUCCESS; + for (uint32_t i = 0; i < len; i++) { + int32_t result = HcsGetUint32ArrayElem(node, attrName, i, value + i, def); + // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. + CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); + } + return ret; +} + +int32_t HcsGetUint64Array(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, uint32_t len, + uint64_t def) +{ + if ((value == NULL) || (len == 0)) { + HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); + return HDF_FAILURE; + } + + for (uint32_t i = 0; i < len; i++) { + int32_t result = HcsGetUint64ArrayElem(node, attrName, i, value + i, def); + if (result != HDF_SUCCESS) { + HDF_LOGE("%s failed, the ret is %d", __func__, result); + return result; + } + } + return HDF_SUCCESS; +} + +int32_t HcsGetStringArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + const char **value, const char *def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + + const char *realValue = GetArrayElem(attr, index); + if ((realValue == NULL) || (HcsGetPrefix(realValue) != CONFIG_STRING)) { + *value = def; + HDF_LOGE("%s failed, %s attr is default value", __func__, attrName); + return HDF_FAILURE; + } + *value = realValue + HCS_PREFIX_LENGTH; + return HDF_SUCCESS; +} + +int32_t HcsGetString(const struct DeviceResourceNode *node, const char *attrName, const char **value, const char *def) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + RETURN_DEFAULT_VALUE(attr, attrName, value, def); + if (HcsGetPrefix(attr->value) != CONFIG_STRING) { + *value = def; + HDF_LOGE("%s failed, Incorrect prefix code", __func__); + return HDF_FAILURE; + } + *value = attr->value + HCS_PREFIX_LENGTH; + return HDF_SUCCESS; +} + +int32_t HcsGetElemNum(const struct DeviceResourceNode *node, const char *attrName) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + if ((attr == NULL) || (attr->value == NULL) || (HcsGetPrefix(attr->value) != CONFIG_ARRAY)) { + HDF_LOGE("%s failed, %s attr error", __func__, (attrName == NULL) ? "error attrName" : attrName); + return HDF_FAILURE; + } + + uint16_t num; + (void)HcsSwapToUint16(&num, attr->value + HCS_PREFIX_LENGTH, CONFIG_WORD); + return num; +} + +static struct DeviceResourceAttr *GetAttrValueInNode(const struct DeviceResourceNode *node, const char *attrValue) +{ + struct DeviceResourceAttr *attr = NULL; + if ((node == NULL) || (attrValue == NULL)) { + return NULL; + } + for (attr = node->attrData; attr != NULL; attr = attr->next) { + if ((attr->value != NULL) && (strcmp(attr->value + HCS_PREFIX_LENGTH, attrValue) == 0) && + (attr->name != NULL) && (strcmp(attr->name, HCS_MATCH_ATTR) == 0)) { + break; + } + } + return attr; +} + +static const struct DeviceResourceNode *TraverseTreeNode(const struct DeviceResourceNode *curNode) +{ + const struct DeviceResourceNode *nextNode = curNode; + while (nextNode->parent && !nextNode->sibling) { + nextNode = nextNode->parent; + } + nextNode = nextNode->sibling; + return nextNode; +} + +const struct DeviceResourceNode *HcsGetNodeByMatchAttr(const struct DeviceResourceNode *node, const char *attrValue) +{ + struct DeviceResourceIface *instance = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if ((attrValue == NULL) || (instance == NULL) || (instance->GetRootNode == NULL)) { + HDF_LOGE("%s failed, attrValue is NULL or DeviceResourceGetIfaceInstance error", __func__); + return NULL; + } + const struct DeviceResourceNode *curNode = (node != NULL) ? node : instance->GetRootNode(); + while (curNode != NULL) { + if (GetAttrValueInNode(curNode, attrValue) != NULL) { + break; + } + curNode = (curNode->child != NULL) ? curNode->child : TraverseTreeNode(curNode); + } + return curNode; +} + +const struct DeviceResourceNode *HcsGetChildNode(const struct DeviceResourceNode *node, const char *nodeName) +{ + if ((node == NULL) || (nodeName == NULL)) { + HDF_LOGE("%s failed, the node or nodeName is NULL", __func__); + return NULL; + } + + struct DeviceResourceNode *child = NULL; + for (child = node->child; child != NULL; child = child->sibling) { + if ((child->name != NULL) && (strcmp(nodeName, child->name) == 0)) { + break; + } + } + return child; +} + +const struct DeviceResourceNode *HcsGetNodeByRefAttr(const struct DeviceResourceNode *node, const char *attrName) +{ + struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); + if ((attr == NULL) || (attr->value == NULL) || (HcsGetPrefix(attr->value) != CONFIG_REFERENCE)) { + HDF_LOGE("%s failed, %s attr error", __func__, (attrName == NULL) ? "error attrName" : attrName); + return NULL; + } + + uint32_t attrValue; + (void)HcsSwapToUint32(&attrValue, attr->value + HCS_PREFIX_LENGTH, CONFIG_DWORD); + struct DeviceResourceIface *instance = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if ((instance == NULL) || (instance->GetRootNode == NULL)) { + HDF_LOGE("%s failed, DeviceResourceGetIfaceInstance error", __func__); + return NULL; + } + const struct DeviceResourceNode *curNode = instance->GetRootNode(); + while (curNode != NULL) { + if (curNode->hashValue == attrValue) { + break; + } + curNode = (curNode->child != NULL) ? curNode->child : TraverseTreeNode(curNode); + } + return curNode; +} diff --git a/ability/sbuf/include/hdf_sbuf.h b/ability/sbuf/include/hdf_sbuf.h new file mode 100755 index 00000000..80a56909 --- /dev/null +++ b/ability/sbuf/include/hdf_sbuf.h @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/** + * @addtogroup Core + * @{ + * + * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * + * The HDF implements driver framework capabilities such as driver loading, service management, + * and driver message model. You can develop drivers based on the HDF. + * + * @since 1.0 + */ + +/** + * @file hdf_sbuf.h + * + * @brief Defines functions related to a HdfSBuf. The HDF provides data serialization and deserialization + * capabilities for data transmission between user-mode applications and kernel-mode drivers. + * + * @since 1.0 + */ + +#ifndef HDF_SBUF_H +#define HDF_SBUF_H + +#include +#include +#include "hdf_cstring.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Defines a HdfSBuf. + * + * @since 1.0 + */ +struct HdfSBuf { + size_t writePos; /**< Current write position */ + size_t readPos; /**< Current read position */ + size_t capacity; /**< Storage capacity, at most 512 KB. */ + uint8_t *data; /**< Pointer to data storage */ + bool isBind; /**< Whether to bind the externally transferred pointer for data storage */ +}; + +/** + * @brief Writes a data segment to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param data Indicates the pointer to the data segment to write. + * @param writeSize Indicates the size of the data segment to write. The maximum value is 512 KB. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteBuffer(struct HdfSBuf *sbuf, const void *data, uint32_t writeSize); + +/** + * @brief Writes a 64-bit unsigned integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 64-bit unsigned integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteUint64(struct HdfSBuf *sbuf, uint64_t value); + +/** + * @brief Writes a 32-bit unsigned integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 32-bit unsigned integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteUint32(struct HdfSBuf *sbuf, uint32_t value); + +/** + * @brief Writes a 16-bit unsigned integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 16-bit unsigned integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteUint16(struct HdfSBuf *sbuf, uint16_t value); + +/** + * @brief Writes an 8-bit unsigned integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 8-bit unsigned integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteUint8(struct HdfSBuf *sbuf, uint8_t value); + +/** + * @brief Writes a 64-bit signed integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 64-bit signed integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteInt64(struct HdfSBuf *sbuf, int64_t value); + +/** + * @brief Writes a 32-bit signed integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 32-bit signed integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteInt32(struct HdfSBuf *sbuf, int32_t value); + +/** + * @brief Writes a 16-bit signed integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 16-bit signed integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteInt16(struct HdfSBuf *sbuf, int16_t value); + +/** + * @brief Writes an 8-bit signed integer to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the 8-bit signed integer to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteInt8(struct HdfSBuf *sbuf, int8_t value); + +/** + * @brief Writes a string to a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the string to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteString(struct HdfSBuf *sbuf, const char *value); + +/** + * @brief Reads a data segment from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param data Indicates the double pointer to the data read. The data read is stored in *data, + * which is requested by the caller. The memory pointed to by *data is managed by the SBuf + * and they share the same lifecycle. + * @param readSize Indicates the pointer to the size of the data read. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadBuffer(struct HdfSBuf *sbuf, const void **data, uint32_t *readSize); + +/** + * @brief Reads a 64-bit unsigned integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 64-bit unsigned integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadUint64(struct HdfSBuf *sbuf, uint64_t *value); + +/** + * @brief Reads a 32-bit unsigned integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 32-bit unsigned integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadUint32(struct HdfSBuf *sbuf, uint32_t *value); + +/** + * @brief Reads a 16-bit unsigned integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 16-bit unsigned integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadUint16(struct HdfSBuf *sbuf, uint16_t *value); + +/** + * @brief Reads an 8-bit unsigned integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 8-bit unsigned integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadUint8(struct HdfSBuf *sbuf, uint8_t *value); + +/** + * @brief Reads a 64-bit signed integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 64-bit signed integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadInt64(struct HdfSBuf *sbuf, int64_t *value); + +/** + * @brief Reads a 32-bit signed integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 32-bit signed integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadInt32(struct HdfSBuf *sbuf, int32_t *value); + +/** + * @brief Reads a 16-bit signed integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 16-bit signed integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadInt16(struct HdfSBuf *sbuf, int16_t *value); + +/** + * @brief Reads an 8-bit signed integer from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the 8-bit signed integer read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadInt8(struct HdfSBuf *sbuf, int8_t *value); + +/** + * @brief Reads a string from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the pointer to the string read if the operation is successful; returns NULL otherwise. + * The memory pointed to by this pointer is managed by the SBuf and they share the same lifecycle. + * + * @since 1.0 + */ +const char *HdfSbufReadString(struct HdfSBuf *sbuf); + +/** + * @brief Obtains the pointer to the data stored in aSBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the pointer to the data stored in the target SBuf. + * + * @since 1.0 + */ +uint8_t *HdfSbufGetData(const struct HdfSBuf *sbuf); + +/** + * @brief Clears the data stored in a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * + * @since 1.0 + */ +void HdfSbufFlush(struct HdfSBuf *sbuf); + +/** + * @brief Obtains the capacity of a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the SBuf capacity. + * @since 1.0 + */ +size_t HdfSbufGetCapacity(const struct HdfSBuf *sbuf); + +/** + * @brief Obtains the size of the data stored in a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the data size. + * + * @since 1.0 + */ +size_t HdfSbufGetDataSize(const struct HdfSBuf *sbuf); + +/** + * @brief Obtains a SBuf instance. + * + * @param capacity Indicates the initial capacity of theSBuf. + * @return Returns the SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufObtain(size_t capacity); + +/** + * @brief Obtains a SBuf instance of the default capacity (256 bytes). + * + * @return Returns the SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufObtainDefaultSize(void); + +/** + * @brief Creates a SBuf instance with the specified data and size. + * The pointer to the data stored in the SBuf is released by the caller, + * and the written data size should not exceed the specified value of size. + * + * @param base Indicates the base of the data to use. + * @param size Indicates the size of the data to use. + * @return Returns the SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufBind(uintptr_t base, size_t size); + +/** + * @brief Releases a SBuf . + * + * @param sbuf Indicates the pointer to the SBuf to release. + * + * @since 1.0 + */ +void HdfSBufRecycle(struct HdfSBuf *sbuf); + +/** + * @brief Creates a SBuf instance with an original SBuf. + * This function moves the data stored in the original SBuf to the new one without memory copy. + * + * @param sbuf Indicates the pointer to the original SBuf. + * @return Returns the new SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufMove(struct HdfSBuf *sbuf); + +/** + * @brief Creates a SBuf instance with an original SBuf. + * This function copies the data stored in the original SBuf to the new one. + * + * @param sbuf Indicates the pointer to the original SBuf. + * @return Returns the new SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufCopy(const struct HdfSBuf *sbuf); + +/** + * @brief Transfers the data ownership to a SBuf. Once the SBuf is released, + * the bound data memory is also released. This function is used together with {@link HdfSBufBind}. + * + * @param sbuf Indicates the pointer to the target SBuf. + * + * @since 1.0 + */ +void HdfSbufTransDataOwnership(struct HdfSBuf *sbuf); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_SBUF_H */ +/** @} */ diff --git a/ability/sbuf/src/hdf_sbuf.c b/ability/sbuf/src/hdf_sbuf.c new file mode 100755 index 00000000..0c2e1c50 --- /dev/null +++ b/ability/sbuf/src/hdf_sbuf.c @@ -0,0 +1,474 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "osal_mem.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" + +#define HDF_SBUF_GROW_SIZE_DEFAULT 256 +#define HDF_SBUF_MAX_SIZE (512 * 1024) // 512kB +#define HDF_SBUF_ALIGN 4 + +static inline size_t HdfSbufGetAlignSize(size_t size) +{ + return (size + HDF_SBUF_ALIGN - 1) & (~(HDF_SBUF_ALIGN - 1)); +} + +static size_t HdfSbufGetLeftWriteSize(struct HdfSBuf *sbuf) +{ + return (sbuf->capacity < sbuf->writePos) ? 0 : (sbuf->capacity - sbuf->writePos); +} + +static size_t HdfSbufGetLeftReadSize(struct HdfSBuf *sbuf) +{ + return (sbuf->writePos < sbuf->readPos) ? 0 : (sbuf->writePos - sbuf->readPos); +} + +static bool HdfSbufWriteRollback(struct HdfSBuf *sbuf, uint32_t size) +{ + size_t alignSize = HdfSbufGetAlignSize(size); + if (sbuf->writePos < alignSize) { + return false; + } + + sbuf->writePos -= alignSize; + return true; +} + +static bool HdfSbufReadRollback(struct HdfSBuf *sbuf, uint32_t size) +{ + size_t alignSize = HdfSbufGetAlignSize(size); + if (sbuf->readPos < alignSize) { + return false; + } + + sbuf->readPos -= alignSize; + return true; +} + +uint8_t *HdfSbufGetData(const struct HdfSBuf *sbuf) +{ + if (sbuf == NULL) { + HDF_LOGE("Get data is null, input sbuf is null"); + return NULL; + } + return (uint8_t *)sbuf->data; +} + +void HdfSbufFlush(struct HdfSBuf *sbuf) +{ + if (sbuf != NULL) { + sbuf->readPos = 0; + sbuf->writePos = 0; + } +} + +size_t HdfSbufGetCapacity(const struct HdfSBuf *sbuf) +{ + return (sbuf != NULL) ? sbuf->capacity : 0; +} + +size_t HdfSbufGetDataSize(const struct HdfSBuf *sbuf) +{ + return (sbuf != NULL) ? sbuf->writePos : 0; +} + +static bool HdfSbufGrow(struct HdfSBuf *sbuf, uint32_t growSize) +{ + if (sbuf->isBind) { + HDF_LOGE("%s: binded sbuf oom", __func__); + return false; + } + + uint32_t newSize = HdfSbufGetAlignSize(sbuf->capacity + growSize); + if (newSize < sbuf->capacity) { + HDF_LOGE("%s: grow size overflow", __func__); + return false; + } + if (newSize > HDF_SBUF_MAX_SIZE) { + HDF_LOGE("%s: buf size over limit", __func__); + return false; + } + + uint8_t *newData = OsalMemCalloc(newSize); + if (newData == NULL) { + HDF_LOGE("%s: oom", __func__); + return false; + } + + if (memcpy_s(newData, newSize, sbuf->data, sbuf->writePos) != EOK) { + OsalMemFree(newData); + return false; + } + + OsalMemFree(sbuf->data); + sbuf->data = newData; + sbuf->capacity = newSize; + + return true; +} + +static bool HdfSbufWrite(struct HdfSBuf *sbuf, const uint8_t *data, uint32_t size) +{ + if (sbuf == NULL || data == NULL) { + return false; + } + + if (size == 0) { + return true; + } + + size_t alignSize = HdfSbufGetAlignSize(size); + // in case of desireCapacity overflow + if (alignSize < size) { + HDF_LOGE("desireCapacity is overflow"); + return false; + } + size_t writeableSize = HdfSbufGetLeftWriteSize(sbuf); + if (alignSize > writeableSize) { + size_t growSize = (alignSize > HDF_SBUF_GROW_SIZE_DEFAULT) ? (alignSize + HDF_SBUF_GROW_SIZE_DEFAULT) : + HDF_SBUF_GROW_SIZE_DEFAULT; + if (!HdfSbufGrow(sbuf, growSize)) { + return false; + } + writeableSize = HdfSbufGetLeftWriteSize(sbuf); + } + + uint8_t *dest = sbuf->data + sbuf->writePos; + if (memcpy_s(dest, writeableSize, data, size) != EOK) { + return false; /* never hits */ + } + + sbuf->writePos += alignSize; + return true; +} + +static bool HdfSbufRead(struct HdfSBuf *sbuf, uint8_t *data, uint32_t readSize) +{ + if (sbuf == NULL || data == NULL) { + return false; + } + + if (readSize == 0) { + return true; + } + + size_t alignSize = HdfSbufGetAlignSize(readSize); + if (alignSize > HdfSbufGetLeftReadSize(sbuf)) { + HDF_LOGE("Read out of buffer range"); + return false; + } + + if (memcpy_s(data, readSize, sbuf->data + sbuf->readPos, readSize) != EOK) { + return false; // never hits + } + sbuf->readPos += alignSize; + return true; +} + +bool HdfSbufWriteBuffer(struct HdfSBuf *sbuf, const void *data, uint32_t writeSize) +{ + if (sbuf == NULL) { + HDF_LOGE("Write buffer failed, input param is invalid"); + return false; + } + if (data == NULL) { + return HdfSbufWriteInt32(sbuf, 0); + } + + if (!HdfSbufWriteInt32(sbuf, writeSize)) { + return false; + } + if (!HdfSbufWrite(sbuf, data, writeSize)) { + (void)HdfSbufWriteRollback(sbuf, sizeof(int32_t)); + return false; + } + + return true; +} + +/* return actual read size */ +bool HdfSbufReadBuffer(struct HdfSBuf *sbuf, const void **data, uint32_t *readSize) +{ + if (sbuf == NULL || data == NULL || readSize == NULL) { + HDF_LOGE("%s:input invalid", __func__); + return false; + } + + int buffSize = 0; + if (!HdfSbufReadInt32(sbuf, &buffSize)) { + return false; + } + + if (buffSize == 0) { + *data = NULL; + *readSize = 0; + return true; + } + size_t alignSize = HdfSbufGetAlignSize(buffSize); + if (alignSize > HdfSbufGetLeftReadSize(sbuf)) { + HDF_LOGE("%s:readBuff out of range", __func__); + (void)HdfSbufReadRollback(sbuf, sizeof(int32_t)); + return false; + } + + *data = sbuf->data + sbuf->readPos; + *readSize = buffSize; + sbuf->readPos += alignSize; + return true; +} + +bool HdfSbufWriteUint64(struct HdfSBuf *sbuf, uint64_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteUint32(struct HdfSBuf *sbuf, uint32_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteUint16(struct HdfSBuf *sbuf, uint16_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteUint8(struct HdfSBuf *sbuf, uint8_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteInt64(struct HdfSBuf *sbuf, int64_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteInt32(struct HdfSBuf *sbuf, int32_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteInt16(struct HdfSBuf *sbuf, int16_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteInt8(struct HdfSBuf *sbuf, int8_t value) +{ + return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); +} + +bool HdfSbufWriteString(struct HdfSBuf *sbuf, const char *value) +{ + if (sbuf == NULL) { + HDF_LOGE("%s:input null", __func__); + return false; + } + + return HdfSbufWriteBuffer(sbuf, value, value ? (strlen(value) + 1) : 0); +} + +bool HdfSbufReadUint64(struct HdfSBuf *sbuf, uint64_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadUint32(struct HdfSBuf *sbuf, uint32_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadUint16(struct HdfSBuf *sbuf, uint16_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadUint8(struct HdfSBuf *sbuf, uint8_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadInt64(struct HdfSBuf *sbuf, int64_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadInt32(struct HdfSBuf *sbuf, int32_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadInt16(struct HdfSBuf *sbuf, int16_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +bool HdfSbufReadInt8(struct HdfSBuf *sbuf, int8_t *value) +{ + return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); +} + +const char *HdfSbufReadString(struct HdfSBuf *sbuf) +{ + if (sbuf == NULL) { + HDF_LOGE("%s:input null", __func__); + return NULL; + } + /* this length contains '\0' at the end. */ + int32_t strLen = 0; + if (!HdfSbufReadInt32(sbuf, &strLen) || strLen <= 0) { + return NULL; + } + size_t alignSize = HdfSbufGetAlignSize(strLen); + if (strLen > INT16_MAX || alignSize > HdfSbufGetLeftReadSize(sbuf)) { + (void)HdfSbufReadRollback(sbuf, sizeof(int32_t)); + return NULL; + } + + char *str = (char *)(sbuf->data + sbuf->readPos); + sbuf->readPos += alignSize; + /* force set '\0' at end of the string */ + str[strLen - 1] = '\0'; + return str; +} + +struct HdfSBuf *HdfSBufObtainDefaultSize() +{ + return HdfSBufObtain(HDF_SBUF_GROW_SIZE_DEFAULT); +} + +struct HdfSBuf *HdfSBufObtain(size_t capacity) +{ + if (capacity > HDF_SBUF_MAX_SIZE) { + HDF_LOGE("%s: buf size over limit", __func__); + return NULL; + } + struct HdfSBuf *sbuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (sbuf == NULL) { + HDF_LOGE("instance usbuf failure"); + return NULL; + } + + sbuf->data = (uint8_t *)OsalMemCalloc(capacity); + if (sbuf->data == NULL) { + OsalMemFree(sbuf); + HDF_LOGE("sbuf obtain oom, size=%u", (uint32_t)capacity); + return NULL; + } + sbuf->capacity = capacity; + sbuf->writePos = 0; + sbuf->readPos = 0; + sbuf->isBind = false; + return sbuf; +} + +struct HdfSBuf *HdfSBufBind(uintptr_t base, size_t size) +{ + /* require 4 byte alignment for base */ + if ((base & 0x3) != 0) { + HDF_LOGE("Base is not align for 4-byte"); + return NULL; + } + struct HdfSBuf *sbuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (sbuf == NULL) { + HDF_LOGE("%s: oom", __func__); + return NULL; + } + + sbuf->data = (uint8_t *)base; + sbuf->capacity = size; + sbuf->writePos = size; + sbuf->readPos = 0; + sbuf->isBind = true; + return sbuf; +} + +struct HdfSBuf *HdfSBufCopy(const struct HdfSBuf *sbuf) +{ + if (sbuf == NULL || sbuf->data == NULL) { + return NULL; + } + + struct HdfSBuf *new = HdfSBufObtain(sbuf->capacity); + if (new == NULL) { + return NULL; + } + new->capacity = sbuf->capacity; + new->readPos = 0; + new->writePos = sbuf->writePos; + if (memcpy_s(new->data, new->capacity, sbuf->data, sbuf->capacity) != EOK) { + HdfSBufRecycle(new); + return NULL; + } + + return new; +} + +struct HdfSBuf *HdfSBufMove(struct HdfSBuf *sbuf) +{ + if (sbuf == NULL) { + return NULL; + } + + struct HdfSBuf *new = OsalMemCalloc(sizeof(struct HdfSBuf)); + if (new == NULL) { + return NULL; + } + new->capacity = sbuf->capacity; + new->readPos = 0; + new->writePos = sbuf->writePos; + new->data = sbuf->data; + + sbuf->data = NULL; + sbuf->capacity = 0; + HdfSbufFlush(sbuf); + + return new; +} + +void HdfSbufTransDataOwnership(struct HdfSBuf *sbuf) +{ + if (sbuf == NULL) { + return; + } + + sbuf->isBind = false; +} +void HdfSBufRecycle(struct HdfSBuf *sbuf) +{ + if (sbuf != NULL) { + if (sbuf->data != NULL && !sbuf->isBind) { + OsalMemFree(sbuf->data); + } + OsalMemFree(sbuf); + } +} diff --git a/core/host/include/devhost_service.h b/core/host/include/devhost_service.h new file mode 100755 index 00000000..402e67ce --- /dev/null +++ b/core/host/include/devhost_service.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVICE_HOST_SERVICE_H +#define DEVICE_HOST_SERVICE_H + +#include "devhost_service_if.h" +#include "hdf_service_observer.h" +#include "hdf_slist.h" +#include "osal_mutex.h" + +struct DevHostService { + struct IDevHostService super; + uint16_t hostId; + const char *hostName; + struct HdfSList devices; + struct HdfServiceObserver observer; +}; + +struct IDevHostService *DevHostServiceNewInstance(uint16_t hostId, const char *hostName); +void DevHostServiceFreeInstance(struct IDevHostService *service); +struct HdfObject *DevHostServiceCreate(void); +void DevHostServiceRelease(struct HdfObject *object); + +#endif /* DEVICE_HOST_SERVICE_H */ diff --git a/core/host/include/devmgr_service_clnt.h b/core/host/include/devmgr_service_clnt.h new file mode 100755 index 00000000..962cf208 --- /dev/null +++ b/core/host/include/devmgr_service_clnt.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVMGR_SERVICE_CLIENT_H +#define DEVMGR_SERVICE_CLIENT_H + +#include "devhost_service_if.h" +#include "devmgr_service_if.h" +#include "hdf_device_token.h" + +struct DevmgrServiceClnt { + struct IDevmgrService *devMgrSvcIf; +}; + +struct DevmgrServiceClnt *DevmgrServiceClntGetInstance(void); +void DevmgrServiceClntFreeInstance(struct DevmgrServiceClnt *inst); +int DevmgrServiceClntAttachDevice(const struct HdfDeviceInfo *deviceInfo, struct IHdfDeviceToken *deviceToken); +int DevmgrServiceClntAttachDeviceHost(uint16_t hostId, struct IDevHostService *hostService); + +#endif /* DEVMGR_SERVICE_CLIENT_H */ diff --git a/core/host/include/devsvc_manager_clnt.h b/core/host/include/devsvc_manager_clnt.h new file mode 100755 index 00000000..03be6eca --- /dev/null +++ b/core/host/include/devsvc_manager_clnt.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVSVC_MANAGER_CLNT_H +#define DEVSVC_MANAGER_CLNT_H + +#include "devsvc_manager_if.h" +#include "devsvc_manager_stub.h" + +struct DevSvcManagerClnt { + struct IDevSvcManager *devSvcMgrIf; +}; + +struct DevSvcManagerClnt *DevSvcManagerClntGetInstance(void); +struct HdfDeviceObject *DevSvcManagerClntGetDeviceObject(const char *svcName); +int DevSvcManagerClntAddService(const char *svcName, struct HdfDeviceObject *service); +void DevSvcManagerClntRemoveService(const char *svcName); + +#endif /* DEVSVC_MANAGER_CLNT_H */ diff --git a/core/host/include/hdf_device.h b/core/host/include/hdf_device.h new file mode 100755 index 00000000..26b2189f --- /dev/null +++ b/core/host/include/hdf_device.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DEVICE_H +#define HDF_DEVICE_H + +#include "devhost_service.h" +#include "device_token_if.h" +#include "hdf_device_desc.h" +#include "hdf_object.h" +#include "hdf_service_observer.h" +#include "hdf_slist.h" +#include "osal_mutex.h" + +struct HdfDeviceNode; + +struct IHdfDevice { + struct HdfObject object; + int (*Attach)(struct IHdfDevice *, struct HdfDeviceNode *); +}; + +struct HdfDevice { + struct IHdfDevice super; + struct HdfSListNode node; + struct HdfSList services; + uint16_t deviceId; + uint16_t hostId; +}; + +struct HdfObject *HdfDeviceCreate(void); +void HdfDeviceRelease(struct HdfObject *object); +struct HdfDevice *HdfDeviceNewInstance(void); +void HdfDeviceFreeInstance(struct HdfDevice *device); +void HdfDeviceDelete(struct HdfSListNode *deviceEntry); + +#endif /* HDF_DEVICE_H */ diff --git a/core/host/include/hdf_device_node.h b/core/host/include/hdf_device_node.h new file mode 100755 index 00000000..1af1982b --- /dev/null +++ b/core/host/include/hdf_device_node.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DEVICE_NODE_H +#define HDF_DEVICE_NODE_H + +#include "hdf_device.h" +#include "hdf_device_info.h" +#include "hdf_device_desc.h" + +struct HdfDeviceNode; +struct DevHostService; + +struct IDeviceNode { + struct HdfObject object; + int (*PublishService)(struct HdfDeviceNode *, const char *); + int (*LaunchNode)(struct HdfDeviceNode *, struct IHdfDevice *); +}; + +struct HdfDeviceNode { + struct IDeviceNode super; + struct HdfSListNode entry; + struct PowerStateToken *powerToken; + struct DevHostService *hostService; + struct HdfDeviceObject deviceObject; + struct IHdfDeviceToken *token; + struct HdfDriverEntry *driverEntry; + const struct HdfDeviceInfo *deviceInfo; +}; + +int HdfDeviceNodeAddPowerStateListener( + struct HdfDeviceNode *devNode, struct IPowerEventListener *listener); +void HdfDeviceNodeConstruct(struct HdfDeviceNode *service); +void HdfDeviceNodeDestruct(struct HdfDeviceNode *service); +struct HdfDeviceNode *HdfDeviceNodeNewInstance(void); +void HdfDeviceNodeFreeInstance(struct HdfDeviceNode *service); +void HdfDeviceNodeDelete(struct HdfSListNode *deviceEntry); +int HdfDeviceNodePublishPublicService(struct HdfDeviceNode *service, const char *svcName); +void HdfDeviceNodeReclaimService(const char *svcName); + +#endif /* HDF_DEVICE_NODE_H */ diff --git a/core/host/include/hdf_device_object.h b/core/host/include/hdf_device_object.h new file mode 100755 index 00000000..62732f9c --- /dev/null +++ b/core/host/include/hdf_device_object.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DEVICE_OBJECT_H +#define HDF_DEVICE_OBJECT_H + +#include "hdf_device_desc.h" + +void HdfDeviceObjectConstruct(struct HdfDeviceObject *deviceObject); + +#endif /* HDF_DEVICE_OBJECT_H */ diff --git a/core/host/include/hdf_device_token.h b/core/host/include/hdf_device_token.h new file mode 100755 index 00000000..851766e5 --- /dev/null +++ b/core/host/include/hdf_device_token.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DEVICE_TOKEN_H +#define HDF_DEVICE_TOKEN_H + +#include "device_token_if.h" +#include "hdf_slist.h" + +struct HdfDeviceToken { + struct HdfSListNode node; + struct IHdfDeviceToken super; +}; + +struct HdfObject *HdfDeviceTokenCreate(void); +void HdfDeviceTokenRelease(struct HdfObject *object); +struct IHdfDeviceToken *HdfDeviceTokenNewInstance(void); +void HdfDeviceTokenFreeInstance(struct IHdfDeviceToken *token); + +#endif /* HDF_DEVICE_TOKEN_H */ diff --git a/core/host/include/hdf_driver_loader.h b/core/host/include/hdf_driver_loader.h new file mode 100755 index 00000000..3551fed1 --- /dev/null +++ b/core/host/include/hdf_driver_loader.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DRIVER_LOADER_H +#define HDF_DRIVER_LOADER_H + +#include "hdf_device_info.h" +#include "hdf_device_node.h" +#include "hdf_object.h" + +struct IDriverLoader { + struct HdfObject object; + struct HdfDriverEntry *(*GetDriverEntry)(const struct HdfDeviceInfo *deviceInfo); + struct HdfDeviceNode *(*LoadNode)(struct IDriverLoader *, const struct HdfDeviceInfo *deviceInfo); + void (*UnLoadNode)(struct IDriverLoader *, const struct HdfDeviceInfo *deviceInfo); +}; + +struct HdfDriverLoader { + struct IDriverLoader super; +}; + +struct HdfObject *HdfDriverLoaderCreate(void); +void HdfDriverLoaderRelease(struct HdfObject *object); +struct IDriverLoader *HdfDriverLoaderGetInstance(void); +struct HdfDriverEntry *HdfDriverLoaderGetDriverEntry(const struct HdfDeviceInfo *deviceInfo); + +#endif /* HDF_DRIVER_LOADER_H */ diff --git a/core/host/include/hdf_observer_record.h b/core/host/include/hdf_observer_record.h new file mode 100755 index 00000000..4dd7370d --- /dev/null +++ b/core/host/include/hdf_observer_record.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_OBSERVER_RECORD_H +#define HDF_OBSERVER_RECORD_H + +#include "hdf_object.h" +#include "hdf_slist.h" +#include "osal_mutex.h" + +struct HdfServiceObserverRecord { + struct HdfSListNode entry; + uint32_t serviceKey; + uint16_t policy; + uint32_t matchId; + struct OsalMutex obsRecMutex; + struct HdfSList subscribers; + struct HdfObject *publisher; +}; + +uint32_t HdfMakeHardwareId(uint16_t hostId, uint16_t deviceId); +struct HdfServiceObserverRecord *HdfServiceObserverRecordObtain(uint32_t serviceKey); +void HdfServiceObserverRecordRecycle(struct HdfServiceObserverRecord *record); +bool HdfServiceObserverRecordCompare(struct HdfSListNode *listEntry, uint32_t serviceKey); +void HdfServiceObserverRecordNotifySubscribers( + struct HdfServiceObserverRecord *record, uint32_t matchId, uint16_t policy); +void HdfServiceObserverRecordDelete(struct HdfSListNode *listEntry); + +#endif /* HDF_OBSERVER_RECORD_H */ diff --git a/core/host/include/hdf_service_observer.h b/core/host/include/hdf_service_observer.h new file mode 100755 index 00000000..530a09c3 --- /dev/null +++ b/core/host/include/hdf_service_observer.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_SERVICE_OBSERVER_H +#define HDF_SERVICE_OBSERVER_H + +#include "hdf_service_subscriber.h" +#include "osal_mutex.h" + +struct HdfServiceObserver { + struct HdfSList services; + struct OsalMutex observerMutex; +}; + +bool HdfServiceObserverConstruct(struct HdfServiceObserver *observer); +void HdfServiceObserverDestruct(struct HdfServiceObserver *observer); +int HdfServiceObserverPublishService(struct HdfServiceObserver *observer, + const char *svcName, uint32_t pubHardwareId, uint16_t policy, struct HdfObject *service); +int HdfServiceObserverSubscribeService(struct HdfServiceObserver *observer, + const char *svcName, uint32_t subHardwareId, struct SubscriberCallback callback); +void HdfServiceObserverRemoveRecord(struct HdfServiceObserver *observer, const char *svcName); + +#endif /* HDF_SERVICE_OBSERVER_H */ diff --git a/core/host/include/hdf_service_subscriber.h b/core/host/include/hdf_service_subscriber.h new file mode 100755 index 00000000..3ec9106b --- /dev/null +++ b/core/host/include/hdf_service_subscriber.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_SERVICE_SUBSCRIBER_H +#define HDF_SERVICE_SUBSCRIBER_H + +#include "hdf_device_desc.h" +#include "hdf_slist.h" + +struct HdfServiceSubscriber { + struct HdfSListNode entry; + uint32_t state; + uint32_t matchId; + struct SubscriberCallback callback; +}; + +enum { + HDF_SUBSCRIBER_STATE_PENDING, + HDF_SUBSCRIBER_STATE_READY +}; + +struct HdfServiceSubscriber *HdfServiceSubscriberObtain(struct SubscriberCallback callback, uint32_t matchId); +void HdfServiceSubscriberRecycle(struct HdfServiceSubscriber *subscriber); +void HdfServiceSubscriberDelete(struct HdfSListNode *listEntry); + +#endif /* HDF_SERVICE_SUBSCRIBER_H */ diff --git a/core/host/include/power_state_token.h b/core/host/include/power_state_token.h new file mode 100755 index 00000000..c75cdb19 --- /dev/null +++ b/core/host/include/power_state_token.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef POWER_STATE_TOKEN_H +#define POWER_STATE_TOKEN_H + +#include "hdf_sref.h" +#include "power_state_token_if.h" + +struct PowerStateToken { + struct IPowerStateToken super; + struct IPowerEventListener *listener; + struct HdfDeviceObject *deviceObject; + struct HdfSRef wakeRef; + HdfPowerState state; +}; + +struct PowerStateToken *PowerStateTokenNewInstance( + struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener); +void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken); + +#endif /* POWER_STATE_TOKEN_H */ \ No newline at end of file diff --git a/core/host/src/devhost_service.c b/core/host/src/devhost_service.c new file mode 100755 index 00000000..d5f91073 --- /dev/null +++ b/core/host/src/devhost_service.c @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devhost_service.h" +#include "devmgr_service_clnt.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_driver_loader.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG devhost_service + +static struct HdfDevice *DevHostServiceFindDevice(struct DevHostService *inst, uint16_t deviceId) +{ + struct HdfSListIterator it; + struct HdfDevice *deviceNode = NULL; + if (inst == NULL) { + HDF_LOGE("Find driver failed, inst is null"); + return NULL; + } + + HdfSListIteratorInit(&it, &inst->devices); + while (HdfSListIteratorHasNext(&it)) { + deviceNode = (struct HdfDevice *)HDF_SLIST_CONTAINER_OF( + struct HdfSListNode, HdfSListIteratorNext(&it), struct HdfDevice, node); + if (deviceNode->deviceId == deviceId) { + return deviceNode; + } + } + return NULL; +} + +static void DevHostServiceFreeDevice(struct DevHostService *inst, uint16_t deviceId) +{ + struct HdfDevice *deviceNode = DevHostServiceFindDevice(inst, deviceId); + if (deviceNode != NULL) { + HdfSListRemove(&inst->devices, &deviceNode->node); + HdfDeviceFreeInstance(deviceNode); + } +} + +static struct HdfDevice *DevHostServiceGetDevice(struct DevHostService *inst, uint16_t deviceId) +{ + struct HdfDevice *device = DevHostServiceFindDevice(inst, deviceId); + if (device == NULL) { + device = HdfDeviceNewInstance(); + if (device == NULL) { + HDF_LOGE("Dev host service create driver instance failed"); + return NULL; + } + device->hostId = inst->hostId; + HdfSListAdd(&inst->devices, &device->node); + } + return device; +} + +static int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo) +{ + int ret = HDF_FAILURE; + struct HdfDevice *device = NULL; + struct HdfDeviceNode *devNode = NULL; + struct DevHostService *hostService = (struct DevHostService *)inst; + struct IDriverLoader *driverLoader = HdfDriverLoaderGetInstance(); + + if ((deviceInfo == NULL) || (driverLoader == NULL) || (driverLoader->LoadNode == NULL)) { + HDF_LOGE("Add device failed, input param is null"); + return ret; + } + + device = DevHostServiceGetDevice(hostService, deviceInfo->deviceId); + if (device == NULL || device->super.Attach == NULL) { + ret = HDF_DEV_ERR_NO_MEMORY; + goto error; + } + + devNode = driverLoader->LoadNode(driverLoader, deviceInfo); + if (devNode == NULL) { + ret = HDF_DEV_ERR_NO_DEVICE_SERVICE; + goto error; + } + devNode->hostService = hostService; + ret = device->super.Attach(&device->super, devNode); + if (ret != HDF_SUCCESS) { + goto error; + } + return HDF_SUCCESS; + +error: + if (HdfSListIsEmpty(&hostService->devices)) { + DevHostServiceFreeDevice(hostService, hostService->hostId); + } + return ret; +} + +static int DevHostServiceDelDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo) +{ + struct HdfDevice *device = NULL; + struct DevHostService *hostService = (struct DevHostService *)inst; + struct IDriverLoader *driverLoader = HdfDriverLoaderGetInstance(); + + if ((deviceInfo == NULL) || (driverLoader == NULL) || (driverLoader->UnLoadNode == NULL)) { + HDF_LOGE("Add device failed, input param is null"); + return HDF_FAILURE; + } + + device = DevHostServiceGetDevice(hostService, deviceInfo->deviceId); + if (device == NULL) { + HDF_LOGW("Del device failed, device is not exist"); + return HDF_SUCCESS; + } + + driverLoader->UnLoadNode(driverLoader, deviceInfo); + if (HdfSListIsEmpty(&hostService->devices)) { + DevHostServiceFreeDevice(hostService, device->deviceId); + } + DevSvcManagerClntRemoveService(deviceInfo->svcName); + return HDF_SUCCESS; +} + +static int DevHostServiceStartService(struct IDevHostService *service) +{ + struct DevHostService *hostService = (struct DevHostService*)service; + if (hostService == NULL) { + HDF_LOGE("Start device service failed, hostService is null"); + return HDF_FAILURE; + } + return DevmgrServiceClntAttachDeviceHost(hostService->hostId, service); +} + +static void DevHostServiceConstruct(struct DevHostService *service) +{ + struct IDevHostService *hostServiceIf = &service->super; + if (hostServiceIf != NULL) { + hostServiceIf->AddDevice = DevHostServiceAddDevice; + hostServiceIf->DelDevice = DevHostServiceDelDevice; + hostServiceIf->StartService = DevHostServiceStartService; + HdfSListInit(&service->devices); + HdfServiceObserverConstruct(&service->observer); + } +} + +static void DevHostServiceDestruct(struct DevHostService *service) +{ + HdfSListFlush(&service->devices, HdfDeviceDelete); + HdfServiceObserverDestruct(&service->observer); +} + +struct HdfObject *DevHostServiceCreate() +{ + struct DevHostService *devHostService = (struct DevHostService *)OsalMemCalloc(sizeof(struct DevHostService)); + if (devHostService != NULL) { + DevHostServiceConstruct(devHostService); + } + return (struct HdfObject *)devHostService; +} + +void DevHostServiceRelease(struct HdfObject *object) +{ + struct DevHostService *devHostService = (struct DevHostService *)object; + if (devHostService != NULL) { + DevHostServiceDestruct(devHostService); + OsalMemFree(devHostService); + } +} + +struct IDevHostService *DevHostServiceNewInstance(uint16_t hostId, const char *hostName) +{ + struct DevHostService *hostService = + (struct DevHostService *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVHOST_SERVICE); + if (hostService != NULL) { + hostService->hostId = hostId; + hostService->hostName = hostName; + } + return (struct IDevHostService *)hostService; +} + +void DevHostServiceFreeInstance(struct IDevHostService *service) +{ + if (service != NULL) { + HdfObjectManagerFreeObject(&service->object); + } +} + diff --git a/core/host/src/devmgr_service_clnt.c b/core/host/src/devmgr_service_clnt.c new file mode 100755 index 00000000..4991e631 --- /dev/null +++ b/core/host/src/devmgr_service_clnt.c @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devmgr_service_clnt.h" +#include "hdf_base.h" +#include "hdf_device.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" + +#define HDF_LOG_TAG devmgr_service_clnt + +int DevmgrServiceClntAttachDeviceHost(uint16_t hostId, struct IDevHostService *hostService) +{ + struct IDevmgrService *devMgrSvcIf = NULL; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if ((inst == NULL) || (inst->devMgrSvcIf == NULL)) { + HDF_LOGE("Attach device host failed, get device manager service client is null"); + return HDF_FAILURE; + } + + devMgrSvcIf = inst->devMgrSvcIf; + if (devMgrSvcIf->AttachDeviceHost == NULL) { + HDF_LOGE("Attach device host failed, attach device host function is null"); + return HDF_FAILURE; + } + return devMgrSvcIf->AttachDeviceHost(devMgrSvcIf, hostId, hostService); +} + +int DevmgrServiceClntAttachDevice(const struct HdfDeviceInfo *deviceInfo, struct IHdfDeviceToken *deviceToken) +{ + struct IDevmgrService *devMgrSvcIf = NULL; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if ((inst == NULL) || (inst->devMgrSvcIf == NULL)) { + HDF_LOGE("Device manager service client attach device failed, inst is null"); + return HDF_FAILURE; + } + + devMgrSvcIf = inst->devMgrSvcIf; + if (devMgrSvcIf->AttachDevice == NULL) { + HDF_LOGE("Device manager service client attach device failed, dmsOps->AttachDevice is nul"); + return HDF_FAILURE; + } + return devMgrSvcIf->AttachDevice(devMgrSvcIf, deviceInfo, deviceToken); +} + +struct DevmgrServiceClnt *DevmgrServiceClntGetInstance() +{ + static struct DevmgrServiceClnt instance = {0}; + if (instance.devMgrSvcIf == NULL) { + instance.devMgrSvcIf = (struct IDevmgrService *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVMGR_SERVICE); + } + return &instance; +} + +void DevmgrServiceClntFreeInstance(struct DevmgrServiceClnt *inst) +{ + if ((inst != NULL) && (inst->devMgrSvcIf != NULL)) { + HdfObjectManagerFreeObject((struct HdfObject *)inst->devMgrSvcIf); + inst->devMgrSvcIf = NULL; + } +} + diff --git a/core/host/src/devsvc_manager_clnt.c b/core/host/src/devsvc_manager_clnt.c new file mode 100755 index 00000000..8d5a61fd --- /dev/null +++ b/core/host/src/devsvc_manager_clnt.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devsvc_manager_clnt.h" +#include "devsvc_manager.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" + +#define HDF_LOG_TAG devsvc_manager_clnt + +int DevSvcManagerClntAddService(const char *svcName, struct HdfDeviceObject *service) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return HDF_FAILURE; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->AddService == NULL) { + HDF_LOGE("AddService function is not assigned"); + return HDF_FAILURE; + } + return serviceManager->AddService(serviceManager, svcName, service); +} + +const struct HdfObject *DevSvcManagerClntGetService(const char *svcName) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return NULL; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->GetService == NULL) { + HDF_LOGE("GetService function is not assigned"); + return NULL; + } + return serviceManager->GetService(serviceManager, svcName); +} + +struct HdfDeviceObject *DevSvcManagerClntGetDeviceObject(const char *svcName) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return NULL; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->GetObject == NULL) { + HDF_LOGE("GetObject function is not assigned"); + return NULL; + } + return serviceManager->GetObject(serviceManager, svcName); +} + +int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return HDF_FAILURE; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->SubscribeService == NULL) { + HDF_LOGE("SubscribeService function is not assigned"); + return HDF_FAILURE; + } + return serviceManager->SubscribeService(serviceManager, svcName, callback); +} + +int DevSvcManagerClntUnsubscribeService(const char *svcName) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return HDF_FAILURE; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->UnsubscribeService == NULL) { + HDF_LOGE("UnsubService function is not assigned"); + return HDF_FAILURE; + } + return serviceManager->UnsubscribeService(serviceManager, svcName); +} + +void DevSvcManagerClntRemoveService(const char *svcName) +{ + struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); + if (devSvcMgrClnt == NULL) { + HDF_LOGE("Get device manager client is null"); + return; + } + + struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; + if (serviceManager->RemoveService == NULL) { + HDF_LOGE("Remove service function is not assigned"); + return; + } + serviceManager->RemoveService(serviceManager, svcName); +} + +static void DevSvcManagerClntConstruct(struct DevSvcManagerClnt *inst) +{ + inst->devSvcMgrIf = (struct IDevSvcManager *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVSVC_MANAGER); +} + +struct DevSvcManagerClnt *DevSvcManagerClntGetInstance() +{ + static struct DevSvcManagerClnt *instance = NULL; + if (instance == NULL) { + static struct DevSvcManagerClnt singletonInstance; + DevSvcManagerClntConstruct(&singletonInstance); + instance = &singletonInstance; + } + return instance; +} + +void DevSvcManagerClntFreeInstance(struct DevSvcManagerClnt *instance) +{ + if (instance != NULL) { + if (instance->devSvcMgrIf != NULL) { + HdfObjectManagerFreeObject((struct HdfObject *)instance->devSvcMgrIf); + } + } +} + diff --git a/core/host/src/hdf_device.c b/core/host/src/hdf_device.c new file mode 100755 index 00000000..15660ddb --- /dev/null +++ b/core/host/src/hdf_device.c @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_device.h" +#include "hdf_base.h" +#include "hdf_cstring.h" +#include "hdf_device_node.h" +#include "hdf_device_token.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" +#include "hdf_service_observer.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG hdf_device + +static int HdfDeviceAttach(struct IHdfDevice *devInst, struct HdfDeviceNode *devNode) +{ + struct HdfDevice *device = (struct HdfDevice *)devInst; + struct IDeviceNode *nodeIf = (struct IDeviceNode *)devNode; + if (device == NULL || nodeIf == NULL || nodeIf->LaunchNode == NULL) { + HDF_LOGE("Device attach failed, input params is wrong"); + return HDF_ERR_INVALID_PARAM; + } + HdfSListAdd(&device->services, &devNode->entry); + return nodeIf->LaunchNode(devNode, devInst); +} + +static void HdfDeviceConstruct(struct HdfDevice *device) +{ + device->super.Attach = HdfDeviceAttach; + HdfSListInit(&device->services); +} + +static void HdfDeviceDestruct(struct HdfDevice *device) +{ + HdfSListFlush(&device->services, HdfDeviceNodeDelete); +} + +struct HdfObject *HdfDeviceCreate() +{ + struct HdfDevice *device = + (struct HdfDevice *)OsalMemCalloc(sizeof(struct HdfDevice)); + if (device != NULL) { + HdfDeviceConstruct(device); + } + return (struct HdfObject *)device; +} + +void HdfDeviceRelease(struct HdfObject *object) +{ + struct HdfDevice *device = (struct HdfDevice *)object; + if (device != NULL) { + HdfDeviceDestruct(device); + OsalMemFree(device); + } +} + +struct HdfDevice *HdfDeviceNewInstance() +{ + return (struct HdfDevice *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVICE); +} + +void HdfDeviceFreeInstance(struct HdfDevice *device) +{ + if (device != NULL) { + HdfObjectManagerFreeObject((struct HdfObject *)device); + } +} + +void HdfDeviceDelete(struct HdfSListNode *listEntry) +{ + if (listEntry != NULL) { + struct HdfDevice *device = (struct HdfDevice *)HDF_SLIST_CONTAINER_OF( + struct HdfSListNode, listEntry, struct HdfDevice, node); + HdfDeviceFreeInstance(device); + } +} + diff --git a/core/host/src/hdf_device_node.c b/core/host/src/hdf_device_node.c new file mode 100755 index 00000000..a518cc91 --- /dev/null +++ b/core/host/src/hdf_device_node.c @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_device_node.h" +#include "devhost_service.h" +#include "devmgr_service_clnt.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_device_object.h" +#include "hdf_device_token.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" +#include "hdf_observer_record.h" +#include "osal_mem.h" +#include "power_state_token.h" + +#define HDF_LOG_TAG device_node + +static int HdfDeviceNodePublishLocalService( + struct HdfDeviceNode *devNode, const struct HdfDeviceInfo *deviceInfo) +{ + uint32_t matchId; + if ((devNode == NULL) || (deviceInfo == NULL)) { + HDF_LOGE("Publish local service failed, device is null"); + return HDF_FAILURE; + } + struct DevHostService *hostService = devNode->hostService; + if (hostService == NULL) { + HDF_LOGE("Publish local service failed, host service is null"); + return HDF_FAILURE; + } + matchId = HdfMakeHardwareId(deviceInfo->hostId, deviceInfo->deviceId); + return HdfServiceObserverPublishService(&hostService->observer, deviceInfo->svcName, + matchId, deviceInfo->policy, (struct HdfObject *)devNode->deviceObject.service); +} + +static int HdfDeviceNodePublishService( + struct HdfDeviceNode *devNode, const struct HdfDeviceInfo *deviceInfo, struct IHdfDevice *device) +{ + int status = HDF_SUCCESS; + if (deviceInfo->policy == SERVICE_POLICY_NONE) { + HDF_LOGI("policy is %d", SERVICE_POLICY_NONE); + return status; + } + + struct IDeviceNode *nodeIf = &devNode->super; + if ((deviceInfo->policy == SERVICE_POLICY_PUBLIC) || + (deviceInfo->policy == SERVICE_POLICY_CAPACITY)) { + if (nodeIf->PublishService != NULL) { + status = nodeIf->PublishService(devNode, deviceInfo->svcName); + } + } + if (status == HDF_SUCCESS) { + status = HdfDeviceNodePublishLocalService(devNode, deviceInfo); + } + return status; +} + +int HdfDeviceLaunchNode(struct HdfDeviceNode *devNode, struct IHdfDevice *devInst) +{ + struct HdfDevice *device = (struct HdfDevice *)devInst; + if (device == NULL || devNode == NULL) { + HDF_LOGE("Launch service failed, device or service is null"); + return HDF_ERR_INVALID_PARAM; + } + + struct HdfDriverEntry *driverEntry = devNode->driverEntry; + const struct HdfDeviceInfo *deviceInfo = devNode->deviceInfo; + struct IHdfDeviceToken *deviceToken = NULL; + + if (deviceInfo == NULL) { + HDF_LOGE("Launch service failed, deviceInfo is null"); + return HDF_ERR_INVALID_PARAM; + } + + if ((driverEntry == NULL) || (driverEntry->Init == NULL)) { + HDF_LOGE("deviceEntry or deviceEntry->Init is null"); + return HDF_ERR_INVALID_PARAM; + } + int ret = driverEntry->Init(&devNode->deviceObject); + if (ret != HDF_SUCCESS) { + if (driverEntry->Release != NULL) { + driverEntry->Release(&devNode->deviceObject); + } + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + ret = HdfDeviceNodePublishService(devNode, deviceInfo, devInst); + if (ret != HDF_SUCCESS) { + if (driverEntry->Release != NULL) { + driverEntry->Release(&devNode->deviceObject); + } + return HDF_DEV_ERR_PUBLISH_FAIL; + } + deviceToken = devNode->token; + ret = DevmgrServiceClntAttachDevice(deviceInfo, deviceToken); + if (ret != HDF_SUCCESS) { + if (driverEntry->Release != NULL) { + driverEntry->Release(&devNode->deviceObject); + } + return HDF_DEV_ERR_ATTACHDEV_FAIL; + } + return ret; +} + +int HdfDeviceNodeAddPowerStateListener( + struct HdfDeviceNode *devNode, struct IPowerEventListener *listener) +{ + if (devNode->powerToken != NULL) { + return HDF_FAILURE; + } + if (devNode->powerToken == NULL) { + devNode->powerToken = PowerStateTokenNewInstance(&devNode->deviceObject, listener); + } + return (devNode->powerToken == NULL) ? HDF_SUCCESS : HDF_FAILURE; +} + +int HdfDeviceNodePublishPublicService(struct HdfDeviceNode *devNode, const char *svcName) +{ + if ((devNode == NULL) || (devNode->deviceObject.service == NULL)) { + HDF_LOGE("device method is null"); + return HDF_FAILURE; + } + return DevSvcManagerClntAddService(svcName, &devNode->deviceObject); +} + +void HdfDeviceNodeReclaimService(const char *svcName) +{ + DevSvcManagerClntRemoveService(svcName); +} + +void HdfDeviceNodeConstruct(struct HdfDeviceNode *devNode) +{ + if (devNode != NULL) { + struct IDeviceNode *nodeIf = &devNode->super; + HdfDeviceObjectConstruct(&devNode->deviceObject); + devNode->token = HdfDeviceTokenNewInstance(); + nodeIf->LaunchNode = HdfDeviceLaunchNode; + nodeIf->PublishService = HdfDeviceNodePublishPublicService; + } +} + +void HdfDeviceNodeDestruct(struct HdfDeviceNode *devNode) +{ + if (devNode == NULL) { + return; + } + HdfDeviceTokenFreeInstance(devNode->token); + devNode->token = NULL; + PowerStateTokenFreeInstance(devNode->powerToken); + devNode->powerToken = NULL; +} + +struct HdfDeviceNode *HdfDeviceNodeNewInstance() +{ + return (struct HdfDeviceNode *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVICE_SERVICE); +} + +void HdfDeviceNodeFreeInstance(struct HdfDeviceNode *devNode) +{ + HdfObjectManagerFreeObject((struct HdfObject *) devNode); +} + +void HdfDeviceNodeDelete(struct HdfSListNode *deviceEntry) +{ + if (deviceEntry == NULL) { + return; + } + struct HdfDeviceNode *devNode = + HDF_SLIST_CONTAINER_OF(struct HdfSListNode, deviceEntry, struct HdfDeviceNode, entry); + HdfDeviceNodeFreeInstance(devNode); +} + diff --git a/core/host/src/hdf_device_object.c b/core/host/src/hdf_device_object.c new file mode 100755 index 00000000..397f448f --- /dev/null +++ b/core/host/src/hdf_device_object.c @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_device_object.h" +#include "hdf_base.h" +#include "hdf_device_node.h" +#include "hdf_log.h" +#include "hdf_observer_record.h" +#include "hdf_service_observer.h" +#include "power_state_token.h" + +#define HDF_LOG_TAG device_object + +int32_t HdfDeviceSubscribeService( + struct HdfDeviceObject *deviceObject, const char *serviceName, struct SubscriberCallback callback) +{ + uint32_t matchId; + struct DevHostService *hostService = NULL; + const struct HdfDeviceInfo *deviceInfo = NULL; + if (deviceObject == NULL || serviceName == NULL) { + HDF_LOGE("%s input param is invalid", __func__); + return HDF_FAILURE; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + hostService = devNode->hostService; + if (hostService == NULL) { + HDF_LOGE("Get host service is null"); + return HDF_FAILURE; + } + deviceInfo = devNode->deviceInfo; + if (deviceInfo == NULL) { + HDF_LOGE("Get device deviceInfo is null"); + return HDF_FAILURE; + } + matchId = HdfMakeHardwareId(deviceInfo->hostId, deviceInfo->deviceId); + return HdfServiceObserverSubscribeService(&hostService->observer, serviceName, matchId, callback); +} + +const char *HdfDeviceGetServiceName(const struct HdfDeviceObject *deviceObject) +{ + if (deviceObject == NULL) { + HDF_LOGE("%s input param is invalid", __func__); + return NULL; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + const struct HdfDeviceInfo *deviceInfo = devNode->deviceInfo; + if (deviceInfo == NULL) { + HDF_LOGE("Get device deviceInfo is null"); + return NULL; + } + return deviceInfo->svcName; +} + +void HdfDeviceRegisterPowerListener(struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) +{ + if (deviceObject == NULL) { + HDF_LOGE("%s input param is invalid", __func__); + return; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + HdfDeviceNodeAddPowerStateListener(devNode, listener); +} + +void HdfDeviceAcquireWakeLock(struct HdfDeviceObject *deviceObject) +{ + if (deviceObject == NULL) { + HDF_LOGE("%s input param is invalid", __func__); + return; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + struct IPowerStateToken *tokenIf = (struct IPowerStateToken *)devNode->powerToken; + if ((tokenIf != NULL) && (tokenIf->AcquireWakeLock != NULL)) { + tokenIf->AcquireWakeLock(tokenIf); + } +} + +void HdfDeviceReleaseWakeLock(struct HdfDeviceObject *deviceObject) +{ + if (deviceObject == NULL) { + HDF_LOGE("%s input param is invalid", __func__); + return; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + struct IPowerStateToken *tokenIf = (struct IPowerStateToken *)devNode->powerToken; + if ((tokenIf != NULL) && (tokenIf->ReleaseWakeLock != NULL)) { + tokenIf->ReleaseWakeLock(tokenIf); + } +} + +void HdfDeviceObjectConstruct(struct HdfDeviceObject *deviceObject) +{ + if (deviceObject != NULL) { + deviceObject->property = NULL; + deviceObject->service = NULL; + } +} diff --git a/core/host/src/hdf_device_token.c b/core/host/src/hdf_device_token.c new file mode 100755 index 00000000..fd8098dd --- /dev/null +++ b/core/host/src/hdf_device_token.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_device_token.h" +#include "hdf_object_manager.h" +#include "osal_mem.h" + +static void HdfDeviceTokenConstruct(struct HdfDeviceToken *inst) +{ + inst->super.object.objectId = HDF_OBJECT_ID_DEVICE_TOKEN; +} + +struct HdfObject *HdfDeviceTokenCreate() +{ + struct HdfDeviceToken *token = + (struct HdfDeviceToken *)OsalMemCalloc(sizeof(struct HdfDeviceToken)); + if (token != NULL) { + HdfDeviceTokenConstruct(token); + } + return (struct HdfObject *)token; +} + +void HdfDeviceTokenRelease(struct HdfObject *object) +{ + struct HdfDeviceToken *deviceToken = (struct HdfDeviceToken *)object; + if (deviceToken != NULL) { + OsalMemFree(deviceToken); + } +} + +struct IHdfDeviceToken *HdfDeviceTokenNewInstance() +{ + return (struct IHdfDeviceToken *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVICE_TOKEN); +} + +void HdfDeviceTokenFreeInstance(struct IHdfDeviceToken *token) +{ + if (token != NULL) { + HdfObjectManagerFreeObject(&token->object); + } +} + diff --git a/core/host/src/hdf_driver_loader.c b/core/host/src/hdf_driver_loader.c new file mode 100755 index 00000000..f779c3ad --- /dev/null +++ b/core/host/src/hdf_driver_loader.c @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_driver_loader.h" +#include "devsvc_manager_clnt.h" +#include "hcs_tree_if.h" +#include "hdf_device_desc.h" +#include "hdf_device_node.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" + +#define HDF_LOG_TAG driver_loader + +static struct HdfDeviceNode *HdfDriverLoaderLoadNode( + struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo) +{ + struct HdfDriverEntry *driverEntry = NULL; + struct HdfDeviceNode *devNode = NULL; + if ((loader == NULL) || (loader->GetDriverEntry == NULL)) { + HDF_LOGE("loader or loader->GetDriverEntry is null"); + return NULL; + } + + driverEntry = loader->GetDriverEntry(deviceInfo); + if (driverEntry == NULL) { + HDF_LOGE("Load service failed, deviceEntry is null"); + return NULL; + } + + devNode = HdfDeviceNodeNewInstance(); + if (devNode == NULL) { + HDF_LOGE("Load service failed, device node is null"); + return NULL; + } + + devNode->driverEntry = driverEntry; + devNode->deviceInfo = deviceInfo; + devNode->deviceObject.property = HcsGetNodeByMatchAttr(HcsGetRootNode(), deviceInfo->deviceMatchAttr); + if (devNode->deviceObject.property == NULL) { + HDF_LOGW("Get property is null, match attr is: %s", deviceInfo->deviceMatchAttr); + } + + if ((deviceInfo->policy == SERVICE_POLICY_PUBLIC) || (deviceInfo->policy == SERVICE_POLICY_CAPACITY)) { + if (driverEntry->Bind == NULL) { + HDF_LOGE("driver bind method is null"); + HdfDeviceNodeFreeInstance(devNode); + return NULL; + } + if (driverEntry->Bind(&devNode->deviceObject) != 0) { + HDF_LOGE("bind driver failed"); + HdfDeviceNodeFreeInstance(devNode); + return NULL; + } + } + return devNode; +} + +static void HdfDriverLoaderUnLoadNode(struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo) +{ + struct HdfDriverEntry *driverEntry = NULL; + struct HdfDeviceObject *deviceObject = NULL; + if ((loader == NULL) || (loader->GetDriverEntry == NULL)) { + HDF_LOGE("loader or loader->GetDriverEntry is null"); + return; + } + + driverEntry = loader->GetDriverEntry(deviceInfo); + if (driverEntry == NULL) { + HDF_LOGE("Load service failed, driverEntry is null"); + return; + } + if (driverEntry->Release == NULL) { + HDF_LOGI("Device Release func is null"); + return; + } + deviceObject = DevSvcManagerClntGetDeviceObject(deviceInfo->svcName); + driverEntry->Release(deviceObject); +} + +static void HdfDriverLoaderConstruct(struct HdfDriverLoader *inst) +{ + struct IDriverLoader *driverLoaderIf = (struct IDriverLoader *)inst; + driverLoaderIf->LoadNode = HdfDriverLoaderLoadNode; + driverLoaderIf->UnLoadNode = HdfDriverLoaderUnLoadNode; + driverLoaderIf->GetDriverEntry = HdfDriverLoaderGetDriverEntry; +} + +struct HdfObject *HdfDriverLoaderCreate() +{ + static bool isDriverLoaderInit = false; + static struct HdfDriverLoader driverLoader; + if (!isDriverLoaderInit) { + HdfDriverLoaderConstruct(&driverLoader); + isDriverLoaderInit = true; + } + return (struct HdfObject *)&driverLoader; +} + +struct IDriverLoader *HdfDriverLoaderGetInstance() +{ + static struct IDriverLoader *instance = NULL; + if (instance == NULL) { + instance = (struct IDriverLoader *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DRIVER_LOADER); + } + return instance; +} + diff --git a/core/host/src/hdf_observer_record.c b/core/host/src/hdf_observer_record.c new file mode 100755 index 00000000..b0dc8847 --- /dev/null +++ b/core/host/src/hdf_observer_record.c @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_observer_record.h" +#include "hdf_log.h" +#include "hdf_service_subscriber.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG observer_record +#define HALF_INT_LEN 16 + +uint32_t HdfMakeHardwareId(uint16_t hostId, uint16_t deviceId) +{ + uint32_t hardwareId = hostId; + hardwareId = (hardwareId << HALF_INT_LEN) | deviceId; + return hardwareId; +} + +struct HdfServiceObserverRecord *HdfServiceObserverRecordObtain(uint32_t serviceKey) +{ + struct HdfServiceObserverRecord *observerRecord = + (struct HdfServiceObserverRecord *)OsalMemCalloc(sizeof(struct HdfServiceObserverRecord)); + if (observerRecord != NULL) { + observerRecord->serviceKey = serviceKey; + observerRecord->publisher = NULL; + if (OsalMutexInit(&observerRecord->obsRecMutex) != HDF_SUCCESS) { + OsalMemFree(observerRecord); + return NULL; + } + HdfSListInit(&observerRecord->subscribers); + } + return observerRecord; +} + +void HdfServiceObserverRecordRecycle(struct HdfServiceObserverRecord *observerRecord) +{ + if (observerRecord != NULL) { + HdfSListFlush(&observerRecord->subscribers, HdfServiceSubscriberDelete); + OsalMutexDestroy(&observerRecord->obsRecMutex); + observerRecord->obsRecMutex.realMutex = NULL; + OsalMemFree(observerRecord); + } +} + +bool HdfServiceObserverRecordCompare(struct HdfSListNode *listEntry, uint32_t serviceKey) +{ + if (listEntry == NULL) { + return false; + } + struct HdfServiceObserverRecord *record = (struct HdfServiceObserverRecord *)listEntry; + if (record->serviceKey == serviceKey) { + return true; + } + return false; +} + +void HdfServiceObserverRecordNotifySubscribers( + struct HdfServiceObserverRecord *record, uint32_t matchId, uint16_t policy) +{ + struct HdfSListIterator it; + if (record == NULL) { + HDF_LOGE("%s: record is null", __func__); + return; + } + + OsalMutexLock(&record->obsRecMutex); + HdfSListIteratorInit(&it, &record->subscribers); + while (HdfSListIteratorHasNext(&it)) { + struct HdfServiceSubscriber *subscriber = + (struct HdfServiceSubscriber *)HdfSListIteratorNext(&it); + if ((matchId == subscriber->matchId) || (policy != SERVICE_POLICY_PRIVATE)) { + subscriber->state = HDF_SUBSCRIBER_STATE_READY; + if (subscriber->callback.OnServiceConnected != NULL) { + subscriber->callback.OnServiceConnected(subscriber->callback.deviceObject, record->publisher); + } + } + } + OsalMutexUnlock(&record->obsRecMutex); +} + +void HdfServiceObserverRecordDelete(struct HdfSListNode *listEntry) +{ + struct HdfServiceObserverRecord *observerRecord = (struct HdfServiceObserverRecord *)listEntry; + if (observerRecord != NULL) { + HdfServiceObserverRecordRecycle(observerRecord); + } +} + diff --git a/core/host/src/hdf_service_observer.c b/core/host/src/hdf_service_observer.c new file mode 100755 index 00000000..c68089a1 --- /dev/null +++ b/core/host/src/hdf_service_observer.c @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_service_observer.h" +#include "hdf_base.h" +#include "hdf_cstring.h" +#include "hdf_log.h" +#include "hdf_observer_record.h" + +#define HDF_LOG_TAG service_observer + +bool HdfServiceObserverConstruct(struct HdfServiceObserver *observer) +{ + if (observer == NULL) { + HDF_LOGE("observer is null"); + return false; + } + if (OsalMutexInit(&observer->observerMutex) != HDF_SUCCESS) { + return false; + } + HdfSListInit(&observer->services); + return true; +} + +void HdfServiceObserverDestruct(struct HdfServiceObserver *observer) +{ + if (observer != NULL) { + HdfSListFlush(&observer->services, HdfServiceObserverRecordDelete); + OsalMutexDestroy(&observer->observerMutex); + observer->observerMutex.realMutex = NULL; + } +} + +int HdfServiceObserverSubscribeService(struct HdfServiceObserver *observer, + const char *svcName, uint32_t matchId, struct SubscriberCallback callback) +{ + struct HdfServiceObserverRecord *serviceRecord = NULL; + struct HdfServiceSubscriber *subscriber = NULL; + uint32_t serviceKey = HdfStringMakeHashKey(svcName, 0); + if ((observer == NULL) || (svcName == NULL)) { + HDF_LOGE("observer or svcName or callback.OnServiceConnected is null"); + return HDF_FAILURE; + } + serviceRecord = (struct HdfServiceObserverRecord *)HdfSListSearch( + &observer->services, serviceKey, HdfServiceObserverRecordCompare); + if (serviceRecord == NULL) { + serviceRecord = HdfServiceObserverRecordObtain(serviceKey); + if (serviceRecord == NULL) { + HDF_LOGE("SubscribeService failed, serviceRecord is null"); + return HDF_FAILURE; + } + subscriber = HdfServiceSubscriberObtain(callback, matchId); + if (subscriber == NULL) { + HDF_LOGE("SubscribeService failed, subscriber is null"); + HdfServiceObserverRecordRecycle(serviceRecord); + return HDF_FAILURE; + } + HdfSListAdd(&observer->services, &serviceRecord->entry); + } else { + subscriber = HdfServiceSubscriberObtain(callback, matchId); + if (subscriber == NULL) { + HDF_LOGE("SubscribeService failed, hdf search list is null, subscriber is null"); + return HDF_FAILURE; + } + } + if ((serviceRecord->publisher != NULL) && + (subscriber->callback.OnServiceConnected != NULL) && + ((serviceRecord->policy != SERVICE_POLICY_PRIVATE) || + (serviceRecord->matchId == matchId))) { + subscriber->state = HDF_SUBSCRIBER_STATE_READY; + subscriber->callback.OnServiceConnected(subscriber->callback.deviceObject, serviceRecord->publisher); + } + OsalMutexLock(&serviceRecord->obsRecMutex); + HdfSListAdd(&serviceRecord->subscribers, &subscriber->entry); + OsalMutexUnlock(&serviceRecord->obsRecMutex); + return HDF_SUCCESS; +} + +int HdfServiceObserverPublishService(struct HdfServiceObserver *observer, + const char *svcName, uint32_t matchId, uint16_t policy, struct HdfObject *service) +{ + struct HdfServiceObserverRecord *serviceRecord = NULL; + uint32_t serviceKey = HdfStringMakeHashKey(svcName, 0); + if ((observer == NULL) || (svcName == NULL)) { + HDF_LOGE("observer or svcName is null"); + return HDF_FAILURE; + } + serviceRecord = (struct HdfServiceObserverRecord *)HdfSListSearch( + &observer->services, serviceKey, HdfServiceObserverRecordCompare); + if (serviceRecord == NULL) { + serviceRecord = HdfServiceObserverRecordObtain(serviceKey); + if (serviceRecord == NULL) { + HDF_LOGE("PublishService failed, serviceRecord is null"); + return HDF_FAILURE; + } + serviceRecord->publisher = service; + serviceRecord->matchId = matchId; + serviceRecord->policy = policy; + HdfSListAdd(&observer->services, &serviceRecord->entry); + } else { + serviceRecord->publisher = service; + HdfServiceObserverRecordNotifySubscribers(serviceRecord, matchId, policy); + } + return HDF_SUCCESS; +} + +void HdfServiceObserverRemoveRecord(struct HdfServiceObserver *observer, const char *svcName) +{ + struct HdfServiceObserverRecord *serviceRecord = NULL; + uint32_t serviceKey = HdfStringMakeHashKey(svcName, 0); + if ((observer == NULL) || (svcName == NULL)) { + HDF_LOGW("observer or svcName is null"); + return; + } + serviceRecord = (struct HdfServiceObserverRecord *)HdfSListSearch( + &observer->services, serviceKey, HdfServiceObserverRecordCompare); + if (serviceRecord != NULL) { + OsalMutexLock(&observer->observerMutex); + HdfSListRemove(&observer->services, &serviceRecord->entry); + OsalMutexUnlock(&observer->observerMutex); + HdfServiceObserverRecordRecycle(serviceRecord); + } +} + diff --git a/core/host/src/hdf_service_subscriber.c b/core/host/src/hdf_service_subscriber.c new file mode 100755 index 00000000..14b31c86 --- /dev/null +++ b/core/host/src/hdf_service_subscriber.c @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "osal_mem.h" +#include "hdf_service_subscriber.h" + +struct HdfServiceSubscriber *HdfServiceSubscriberObtain(struct SubscriberCallback callback, uint32_t matchId) +{ + struct HdfServiceSubscriber *serviceSubscriber = + (struct HdfServiceSubscriber *)OsalMemCalloc(sizeof(struct HdfServiceSubscriber)); + if (serviceSubscriber != NULL) { + serviceSubscriber->state = HDF_SUBSCRIBER_STATE_PENDING; + serviceSubscriber->matchId = matchId; + serviceSubscriber->callback = callback; + } + return serviceSubscriber; +} + +void HdfServiceSubscriberRecycle(struct HdfServiceSubscriber *subscriber) +{ + if (subscriber != NULL) { + OsalMemFree(subscriber); + } +} + +void HdfServiceSubscriberDelete(struct HdfSListNode *listEntry) +{ + struct HdfServiceSubscriber *serviceSubscriber = (struct HdfServiceSubscriber *)listEntry; + if (serviceSubscriber != NULL) { + HdfServiceSubscriberRecycle(serviceSubscriber); + } +} diff --git a/core/host/src/power_state_token.c b/core/host/src/power_state_token.c new file mode 100755 index 00000000..441b42a4 --- /dev/null +++ b/core/host/src/power_state_token.c @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "power_state_token.h" +#include "devmgr_service_clnt.h" +#include "hdf_device_desc.h" +#include "hdf_slist.h" +#include "osal_mem.h" + +static void PowerStateTokenAcqureWakeLock(struct IPowerStateToken *token) +{ + struct HdfSRef *sref = NULL; + struct PowerStateToken *stateToken = (struct PowerStateToken *)token; + if (stateToken == NULL) { + return; + } + sref = (struct HdfSRef *)&stateToken->wakeRef; + if ((sref != NULL) && (sref->Acquire != NULL)) { + sref->Acquire(sref); + } +} + +static void PowerStateTokenReleaseWakeLock(struct IPowerStateToken *token) +{ + struct HdfSRef *sref = NULL; + struct PowerStateToken *stateToken = (struct PowerStateToken *)token; + if (stateToken == NULL) { + return; + } + sref = (struct HdfSRef *)&stateToken->wakeRef; + if ((sref != NULL) && (sref->Release != NULL)) { + sref->Release(sref); + } +} + +static void PowerStateTokenOnFirstAcquire(struct HdfSRef *sref) +{ + if (sref == NULL) { + return; + } + struct PowerStateToken *stateToken = (struct PowerStateToken *)HDF_SLIST_CONTAINER_OF( + struct HdfSRef, sref, struct PowerStateToken, wakeRef); + if (stateToken->state != POWER_STATE_ACTIVE) { + struct IDevmgrService *devMgrSvcIf = NULL; + struct IPowerEventListener* listener = stateToken->listener; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if (inst == NULL) { + return; + } + devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; + if (devMgrSvcIf->AcquireWakeLock == NULL) { + return; + } + devMgrSvcIf->AcquireWakeLock(devMgrSvcIf, &stateToken->super); + if (stateToken->state == POWER_STATE_INACTIVE) { + if ((listener != NULL) && (listener->Resume != NULL)) { + listener->Resume(stateToken->deviceObject); + } + } + stateToken->state = POWER_STATE_ACTIVE; + } +} + +static void PowerStateTokenOnLastRelease(struct HdfSRef *sref) +{ + if (sref == NULL) { + return; + } + struct PowerStateToken *stateToken = (struct PowerStateToken *)HDF_SLIST_CONTAINER_OF( + struct HdfSRef, sref, struct PowerStateToken, wakeRef); + if (stateToken->state == POWER_STATE_ACTIVE) { + struct IDevmgrService *devMgrSvcIf = NULL; + struct IPowerEventListener *listener = stateToken->listener; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if (inst == NULL) { + return; + } + devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; + if ((devMgrSvcIf == NULL) || (devMgrSvcIf->AcquireWakeLock == NULL)) { + return; + } + devMgrSvcIf->ReleaseWakeLock(devMgrSvcIf, &stateToken->super); + if ((listener != NULL) && (listener->Suspend != NULL)) { + listener->Suspend(stateToken->deviceObject); + } + stateToken->state = POWER_STATE_INACTIVE; + } +} + +static void PowerStateTokenConstruct( + struct PowerStateToken *powerStateToken, struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) +{ + struct IPowerStateToken *tokenIf = (struct IPowerStateToken *)powerStateToken; + struct IHdfSRefListener *srefListener = (struct IHdfSRefListener *)OsalMemCalloc(sizeof(struct IHdfSRefListener)); + if (srefListener == NULL) { + return; + } + + tokenIf->AcquireWakeLock = PowerStateTokenAcqureWakeLock; + tokenIf->ReleaseWakeLock = PowerStateTokenReleaseWakeLock; + + srefListener->OnFirstAcquire = PowerStateTokenOnFirstAcquire; + srefListener->OnLastRelease = PowerStateTokenOnLastRelease; + + powerStateToken->state = POWER_STATE_IDLE; + powerStateToken->listener = listener; + powerStateToken->deviceObject = deviceObject; + HdfSRefConstruct(&powerStateToken->wakeRef, srefListener); +} + +struct PowerStateToken *PowerStateTokenNewInstance( + struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) +{ + struct PowerStateToken *stateToken = + (struct PowerStateToken *)OsalMemCalloc(sizeof(struct PowerStateToken)); + if (stateToken != NULL) { + PowerStateTokenConstruct(stateToken, deviceObject, listener); + } + return stateToken; +} + +void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken) +{ + if (stateToken != NULL) { + if (stateToken->wakeRef.listener != NULL) { + OsalMemFree(stateToken->wakeRef.listener); + stateToken->wakeRef.listener = NULL; + } + OsalMemFree(stateToken); + } +} diff --git a/core/manager/include/devhost_service_clnt.h b/core/manager/include/devhost_service_clnt.h new file mode 100755 index 00000000..d38c98b3 --- /dev/null +++ b/core/manager/include/devhost_service_clnt.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVHOST_SERVICE_CLNT_H +#define DEVHOST_SERVICE_CLNT_H + +#include "devhost_service_if.h" +#include "hdf_slist.h" + +struct DevHostServiceClnt { + struct HdfSListNode node; + struct HdfSList devices; + struct HdfSList *deviceInfos; + struct IDevHostService *hostService; + uint16_t hostId; + int hostPid; + const char *hostName; +}; + +int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt); +struct DevHostServiceClnt *DevHostServiceClntNewInstance(uint16_t hostId, const char *hostName); +void DevHostServiceClntFreeInstance(struct DevHostServiceClnt* hostClnt); +void DevHostServiceClntDelete(struct HdfSListNode *listEntry); + +#endif /* DEVHOST_SERVICE_CLNT_H */ diff --git a/core/manager/include/device_token_clnt.h b/core/manager/include/device_token_clnt.h new file mode 100755 index 00000000..047ed729 --- /dev/null +++ b/core/manager/include/device_token_clnt.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVICE_TOKEN_CLNT_H +#define DEVICE_TOKEN_CLNT_H + +#include "device_token_if.h" +#include "hdf_device_info.h" +#include "hdf_slist.h" + +struct DeviceTokenClnt { + struct HdfSListNode node; + struct IHdfDeviceToken *tokenIf; + const struct HdfDeviceInfo *deviceInfo; +}; + +struct DeviceTokenClnt *DeviceTokenClntNewInstance(struct IHdfDeviceToken *token); +void DeviceTokenClntFreeInstance(struct DeviceTokenClnt *token); +void DeviceTokenClntDelete(struct HdfSListNode *listEntry); + +#endif /* DEVICE_TOKEN_CLNT_H */ diff --git a/core/manager/include/devmgr_service.h b/core/manager/include/devmgr_service.h new file mode 100755 index 00000000..2fd02601 --- /dev/null +++ b/core/manager/include/devmgr_service.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVICE_MANAGER_SERVICE_H +#define DEVICE_MANAGER_SERVICE_H + +#include "devmgr_service_if.h" +#include "hdf_slist.h" +#include "osal_mutex.h" + +struct DevmgrService { + struct IDevmgrService super; + struct HdfSList hosts; + struct OsalMutex devMgrMutex; +}; + +int DevmgrServiceStartService(struct IDevmgrService *inst); +struct HdfObject *DevmgrServiceCreate(void); +void DevmgrServiceRelease(struct HdfObject *object); +struct IDevmgrService *DevmgrServiceGetInstance(void); +int DevmgrServiceLoadDevice(const char *svcName); +int DevmgrServiceUnLoadDevice(const char *svcName); +void DevmgrServiceAcquireWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf); +void DevmgrServiceReleaseWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf); + +#endif /* DEVICE_MANAGER_SERVICE_H */ diff --git a/core/manager/include/devsvc_manager.h b/core/manager/include/devsvc_manager.h new file mode 100755 index 00000000..65829a59 --- /dev/null +++ b/core/manager/include/devsvc_manager.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVICE_SERVICE_MANAGER_H +#define DEVICE_SERVICE_MANAGER_H + +#include "devsvc_manager_if.h" +#include "hdf_service_observer.h" +#include "hdf_slist.h" +#include "osal_mutex.h" + +struct DevSvcManager { + struct IDevSvcManager super; + struct HdfSList services; + struct HdfServiceObserver observer; + struct OsalMutex mutex; +}; + +struct HdfObject *DevSvcManagerCreate(void); +void DevSvcManagerRelease(struct HdfObject *object); +struct IDevSvcManager *DevSvcManagerGetInstance(void); +int DevSvcManagerAddService(struct IDevSvcManager *manager, const char *svcName, struct HdfDeviceObject *service); +struct HdfObject *DevSvcManagerGetService(struct IDevSvcManager *manager, const char *svcName); +void DevSvcManagerRemoveService(struct IDevSvcManager *manager, const char *svcName); + +#endif /* DEVICE_SERVICE_MANAGER_H */ diff --git a/core/manager/include/devsvc_manager_stub.h b/core/manager/include/devsvc_manager_stub.h new file mode 100755 index 00000000..ef8b7856 --- /dev/null +++ b/core/manager/include/devsvc_manager_stub.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVSVC_MANAGER_STUB_H +#define DEVSVC_MANAGER_STUB_H + +#include "hdf_device_desc.h" + +int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback); +int DevSvcManagerClntUnsubscribeService(const char *svcName); + +#endif /* DEVSVC_MANAGER_STUB_H */ + diff --git a/core/manager/include/hdf_driver_installer.h b/core/manager/include/hdf_driver_installer.h new file mode 100755 index 00000000..fed4dfb9 --- /dev/null +++ b/core/manager/include/hdf_driver_installer.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DRIVER_INSTALLER_H +#define HDF_DRIVER_INSTALLER_H + +#include "hdf_object.h" +#include "hdf_slist.h" + +struct IDriverInstaller { + struct HdfObject object; + int (*StartDeviceHost)(uint32_t, const char *); +}; + +struct DriverInstaller { + struct IDriverInstaller super; +}; + +struct HdfObject *DriverInstallerCreate(void); +struct IDriverInstaller *DriverInstallerGetInstance(void); + +#endif /* HDF_DRIVER_INSTALLER_H */ diff --git a/core/manager/include/hdf_host_info.h b/core/manager/include/hdf_host_info.h new file mode 100755 index 00000000..6fe5e57d --- /dev/null +++ b/core/manager/include/hdf_host_info.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_HOST_INFO_H +#define HDF_HOST_INFO_H + +#include "hdf_slist.h" + +struct HdfHostInfo { + struct HdfSListNode node; + uint16_t hostId; + uint16_t priority; + const char *hostName; +}; + +struct HdfHostInfo *HdfHostInfoNewInstance(void); +void HdfHostInfoFreeInstance(struct HdfHostInfo *hostInfo); +void HdfHostInfoDelete(struct HdfSListNode *listEntry); + +#endif /* HDF_HOST_INFO_H */ diff --git a/core/manager/include/power_state_manager.h b/core/manager/include/power_state_manager.h new file mode 100755 index 00000000..186db047 --- /dev/null +++ b/core/manager/include/power_state_manager.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef POWER_STATE_MANAGER_H +#define POWER_STATE_MANAGER_H + +#include "hdf_sref.h" +#include "hdf_slist.h" +#include "power_state_token_if.h" + +struct PowerStateManager { + struct HdfSRef wakeRef; + struct HdfSList tokens; + void (*AcquireWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); + void (*ReleaseWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); +}; + +struct PowerStateManager *PowerStateManagerGetInstance(void); + +#endif /* POWER_STATE_MANAGER_H */ \ No newline at end of file diff --git a/core/manager/include/power_state_token_clnt.h b/core/manager/include/power_state_token_clnt.h new file mode 100755 index 00000000..cd963cbb --- /dev/null +++ b/core/manager/include/power_state_token_clnt.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +#ifndef POWER_STATE_TOKEN_CLNT_H +#define POWER_STATE_TOKEN_CLNT_H + +#include "hdf_slist.h" +#include "power_state_token_if.h" + +struct PowerStateTokenClnt { + struct HdfSListNode entry; + HdfPowerState powerState; + struct IPowerStateToken* tokenIf; +}; + +struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf); +void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt); + +#endif /* POWER_STATE_TOKEN_CLNT_H */ \ No newline at end of file diff --git a/core/manager/src/devhost_service_clnt.c b/core/manager/src/devhost_service_clnt.c new file mode 100755 index 00000000..03c5136d --- /dev/null +++ b/core/manager/src/devhost_service_clnt.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "device_token_clnt.h" +#include "devhost_service_clnt.h" +#include "hdf_base.h" +#include "hdf_driver_installer.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG devhost_service_clnt + +int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt) +{ + int ret; + struct HdfSListIterator it; + struct HdfDeviceInfo *deviceInfo = NULL; + struct IDevHostService *devHostSvcIf = NULL; + if (hostClnt == NULL) { + HDF_LOGE("Install driver failed, hostClnt is null"); + return HDF_FAILURE; + } + + devHostSvcIf = (struct IDevHostService *)hostClnt->hostService; + if (devHostSvcIf == NULL || devHostSvcIf->AddDevice == NULL) { + HDF_LOGE("devHostSvcIf or devHostSvcIf->AddDevice is null"); + return HDF_FAILURE; + } + HdfSListIteratorInit(&it, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&it)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&it); + if ((deviceInfo == NULL) || (deviceInfo->preload != DEVICE_PRELOAD_ENABLE)) { + continue; + } + ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); + if (ret != HDF_SUCCESS) { + deviceInfo->preload = DEVICE_PRELOAD_DISABLE; + HDF_LOGE("Install %s driver failed, ret = %d", deviceInfo->svcName, ret); + } + } + return HDF_SUCCESS; +} + +static void DevHostServiceClntConstruct(struct DevHostServiceClnt *hostClnt) +{ + HdfSListInit(&hostClnt->devices); +} + +struct DevHostServiceClnt *DevHostServiceClntNewInstance(uint16_t hostId, const char *hostName) +{ + struct DevHostServiceClnt *hostClnt = + (struct DevHostServiceClnt *)OsalMemCalloc(sizeof(struct DevHostServiceClnt)); + if (hostClnt != NULL) { + hostClnt->hostId = hostId; + hostClnt->hostName = hostName; + DevHostServiceClntConstruct(hostClnt); + } + return hostClnt; +} + +void DevHostServiceClntFreeInstance(struct DevHostServiceClnt *hostClnt) +{ + if (hostClnt != NULL) { + HdfSListFlush(&hostClnt->devices, DeviceTokenClntDelete); + HdfSListFlush(hostClnt->deviceInfos, HdfDeviceInfoDelete); + OsalMemFree(hostClnt); + } +} + +void DevHostServiceClntDelete(struct HdfSListNode *listEntry) +{ + struct DevHostServiceClnt *hostClnt = (struct DevHostServiceClnt *)listEntry; + if (hostClnt != NULL) { + DevHostServiceClntFreeInstance(hostClnt); + } +} + diff --git a/core/manager/src/device_token_clnt.c b/core/manager/src/device_token_clnt.c new file mode 100755 index 00000000..f90d7f5a --- /dev/null +++ b/core/manager/src/device_token_clnt.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "device_token_clnt.h" +#include "hdf_device_token.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG device_token_clnt + +static void DeviceTokenClntConstruct(struct DeviceTokenClnt *tokenClnt, struct IHdfDeviceToken *tokenIf) +{ + tokenClnt->tokenIf = tokenIf; + tokenClnt->deviceInfo = NULL; +} + +struct DeviceTokenClnt *DeviceTokenClntNewInstance(struct IHdfDeviceToken *tokenIf) +{ + struct DeviceTokenClnt *tokenClnt = NULL; + if (tokenIf == NULL) { + HDF_LOGE("New token client failed, tokenIf is null"); + return NULL; + } + tokenClnt = (struct DeviceTokenClnt *)OsalMemCalloc(sizeof(struct DeviceTokenClnt)); + if (tokenClnt != NULL) { + DeviceTokenClntConstruct(tokenClnt, tokenIf); + } + return tokenClnt; +} + +void DeviceTokenClntFreeInstance(struct DeviceTokenClnt *tokenClnt) +{ + if (tokenClnt != NULL) { + OsalMemFree(tokenClnt); + } +} + +void DeviceTokenClntDelete(struct HdfSListNode *listEntry) +{ + struct DeviceTokenClnt *tokenClnt = (struct DeviceTokenClnt *)listEntry; + if (tokenClnt != NULL) { + DeviceTokenClntFreeInstance(tokenClnt); + } +} diff --git a/core/manager/src/devmgr_service.c b/core/manager/src/devmgr_service.c new file mode 100755 index 00000000..2513d4fe --- /dev/null +++ b/core/manager/src/devmgr_service.c @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devmgr_service.h" +#include +#include "devhost_service_clnt.h" +#include "device_token_clnt.h" +#include "hdf_attribute_manager.h" +#include "hdf_base.h" +#include "hdf_driver_installer.h" +#include "hdf_host_info.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" +#include "power_state_manager.h" + + +#define HDF_LOG_TAG devmgr_service + +static int DevmgrServiceActiveDevice(struct DevHostServiceClnt *hostClnt, struct HdfDeviceInfo *deviceInfo, bool isLoad) +{ + struct IDevHostService *devHostSvcIf = (struct IDevHostService *)hostClnt->hostService; + if (isLoad) { + int ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); + if (ret == HDF_SUCCESS) { + deviceInfo->preload = DEVICE_PRELOAD_ENABLE; + } + return ret; + } else { + devHostSvcIf->DelDevice(devHostSvcIf, deviceInfo); + deviceInfo->preload = DEVICE_PRELOAD_DISABLE; + return HDF_SUCCESS; + } +} + +static int DevmgrServiceFindAndActiveDevice(const char *svcName, bool isLoad) +{ + struct HdfSListIterator itHost; + struct HdfSListIterator itDeviceInfo; + struct HdfDeviceInfo *deviceInfo = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); + if (devMgrSvc == NULL || svcName == NULL) { + return HDF_FAILURE; + } + + HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); + while (HdfSListIteratorHasNext(&itHost)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); + HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&itDeviceInfo)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); + if (strcmp(deviceInfo->svcName, svcName) == 0) { + return DevmgrServiceActiveDevice(hostClnt, deviceInfo, isLoad); + } + } + } + HDF_LOGE("Find %s deviceInfo failed, active is: %u", svcName, isLoad); + return HDF_FAILURE; +} + +int DevmgrServiceLoadDevice(const char *svcName) +{ + return DevmgrServiceFindAndActiveDevice(svcName, true); +} + +int DevmgrServiceUnLoadDevice(const char *svcName) +{ + return DevmgrServiceFindAndActiveDevice(svcName, false); +} + +static struct DevHostServiceClnt *DevmgrServiceFindDeviceHost(struct IDevmgrService *inst, uint16_t hostId) +{ + struct HdfSListIterator it; + struct DevHostServiceClnt *hostClnt = NULL; + struct DevmgrService *dmService = (struct DevmgrService *)inst; + if (dmService == NULL) { + HDF_LOGE("Find device host failed, dmService is null"); + return NULL; + } + HdfSListIteratorInit(&it, &dmService->hosts); + while (HdfSListIteratorHasNext(&it)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&it); + if (hostClnt->hostId == hostId) { + return hostClnt; + } + } + HDF_LOGE("Find host failed, host id is %u", hostId); + return NULL; +} + +static int DevmgrServiceAttachDevice( + struct IDevmgrService *inst, const struct HdfDeviceInfo *deviceInfo, struct IHdfDeviceToken *token) +{ + if (deviceInfo == NULL) { + HDF_LOGE("deviceInfo is null"); + return HDF_FAILURE; + } + struct DevHostServiceClnt *hostClnt = DevmgrServiceFindDeviceHost(inst, deviceInfo->hostId); + if (hostClnt == NULL) { + HDF_LOGE("hostClnt is null"); + return HDF_FAILURE; + } + struct IDevHostService *hostService = hostClnt->hostService; + if ((hostService == NULL) || (hostClnt->deviceInfos == NULL)) { + HDF_LOGE("hostService or hostClnt->deviceInfos is null"); + return HDF_FAILURE; + } + struct DeviceTokenClnt *tokenClnt = DeviceTokenClntNewInstance(token); + if (tokenClnt == NULL) { + HDF_LOGE("tokenClnt is null"); + return HDF_FAILURE; + } + + tokenClnt->deviceInfo = deviceInfo; + HdfSListAdd(&hostClnt->devices, &tokenClnt->node); + return HDF_SUCCESS; +} + +static int DevmgrServiceAttachDeviceHost( + struct IDevmgrService *inst, uint16_t hostId, struct IDevHostService *hostService) +{ + struct DevHostServiceClnt *hostClnt = DevmgrServiceFindDeviceHost(inst, hostId); + if (hostClnt == NULL) { + HDF_LOGE("Attach device host failed, hostClnt is null"); + return HDF_FAILURE; + } + if (hostService == NULL) { + HDF_LOGE("Attach device host failed, hostService is null"); + return HDF_FAILURE; + } + hostClnt->deviceInfos = HdfAttributeManagerGetDeviceList(hostClnt->hostId, hostClnt->hostName); + if (hostClnt->deviceInfos == NULL) { + HDF_LOGE("Get device list failed"); + return HDF_FAILURE; + } + hostClnt->hostService = hostService; + return DevHostServiceClntInstallDriver(hostClnt); +} + +static int DevmgrServiceStartDeviceHosts(struct DevmgrService *inst) +{ + struct HdfSList hostList; + struct HdfSListIterator it; + struct HdfHostInfo *hostAttr = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + struct IDriverInstaller *installer = NULL; + installer = DriverInstallerGetInstance(); + if ((installer == NULL) || (installer->StartDeviceHost == NULL)) { + HDF_LOGE("installer or installer->StartDeviceHost is null"); + return HDF_FAILURE; + } + HdfSListInit(&hostList); + if (!HdfAttributeManagerGetHostList(&hostList)) { + HDF_LOGW("Get device host list failed"); + return HDF_FAILURE; + } + HdfSListIteratorInit(&it, &hostList); + while (HdfSListIteratorHasNext(&it)) { + hostAttr = (struct HdfHostInfo *)HdfSListIteratorNext(&it); + hostClnt = DevHostServiceClntNewInstance(hostAttr->hostId, hostAttr->hostName); + if (hostClnt == NULL) { + HDF_LOGW("Create new device host client failed"); + continue; + } + HdfSListAdd(&inst->hosts, &hostClnt->node); + hostClnt->hostPid = installer->StartDeviceHost(hostAttr->hostId, hostAttr->hostName); + if (hostClnt->hostPid == HDF_FAILURE) { + HDF_LOGW("Start device host failed, host id is %u", hostAttr->hostId); + HdfSListRemove(&inst->hosts, &hostClnt->node); + DevHostServiceClntFreeInstance(hostClnt); + } + } + HdfSListFlush(&hostList, HdfHostInfoDelete); + return HDF_SUCCESS; +} + +int DevmgrServiceStartService(struct IDevmgrService *inst) +{ + struct DevmgrService *dmService = (struct DevmgrService *)inst; + if (dmService == NULL) { + HDF_LOGE("Start device manager service failed, dmService is null"); + return HDF_FAILURE; + } + return DevmgrServiceStartDeviceHosts(dmService); +} + +static bool DevmgrServiceConstruct(struct DevmgrService *inst) +{ + if (OsalMutexInit(&inst->devMgrMutex) != HDF_SUCCESS) { + HDF_LOGE("%s mutex init failed", __func__); + return false; + } + struct IDevmgrService *devMgrSvcIf = (struct IDevmgrService *)inst; + if (devMgrSvcIf != NULL) { + devMgrSvcIf->AttachDevice = DevmgrServiceAttachDevice; + devMgrSvcIf->AttachDeviceHost = DevmgrServiceAttachDeviceHost; + devMgrSvcIf->StartService = DevmgrServiceStartService; + devMgrSvcIf->AcquireWakeLock = DevmgrServiceAcquireWakeLock; + devMgrSvcIf->ReleaseWakeLock = DevmgrServiceReleaseWakeLock; + HdfSListInit(&inst->hosts); + } + return true; +} + + +struct HdfObject *DevmgrServiceCreate() +{ + static bool isDevMgrServiceInit = false; + static struct DevmgrService devmgrServiceInstance; + if (!isDevMgrServiceInit) { + if (!DevmgrServiceConstruct(&devmgrServiceInstance)) { + return NULL; + } + isDevMgrServiceInit = true; + } + return (struct HdfObject *)&devmgrServiceInstance; +} + +struct IDevmgrService *DevmgrServiceGetInstance() +{ + static struct IDevmgrService *instance = NULL; + if (instance == NULL) { + instance = (struct IDevmgrService *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVMGR_SERVICE); + } + return instance; +} + +void DevmgrServiceRelease(struct HdfObject *object) +{ + struct DevmgrService *devmgrService = (struct DevmgrService *)object; + if (devmgrService == NULL) { + return; + } + HdfSListFlush(&devmgrService->hosts, DevHostServiceClntDelete); + OsalMutexDestroy(&devmgrService->devMgrMutex); +} + +void DevmgrServiceAcquireWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf) +{ + struct PowerStateManager *stateManager = PowerStateManagerGetInstance(); + if ((stateManager != NULL) && (stateManager->AcquireWakeLock != NULL)) { + stateManager->AcquireWakeLock(stateManager, tokenIf); + } +} + +void DevmgrServiceReleaseWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf) +{ + struct PowerStateManager *stateManager = PowerStateManagerGetInstance(); + if ((stateManager != NULL) && (stateManager->ReleaseWakeLock != NULL)) { + stateManager->ReleaseWakeLock(stateManager, tokenIf); + } +} diff --git a/core/manager/src/devsvc_manager.c b/core/manager/src/devsvc_manager.c new file mode 100755 index 00000000..4cdb93f4 --- /dev/null +++ b/core/manager/src/devsvc_manager.c @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devsvc_manager.h" +#include "devmgr_service.h" +#include "hdf_base.h" +#include "hdf_cstring.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" +#include "hdf_service_record.h" + +#define HDF_LOG_TAG devsvc_manager + +struct DevSvcRecord *DevSvcManagerSearchService(struct IDevSvcManager *inst, uint32_t serviceKey) +{ + struct HdfSListIterator it; + struct DevSvcRecord *record = NULL; + struct DevSvcRecord *searchResult = NULL; + struct DevSvcManager *devSvcManager = (struct DevSvcManager *)inst; + if (devSvcManager == NULL) { + HDF_LOGE("Search service failed, devSvcManager is null"); + return NULL; + } + + OsalMutexLock(&devSvcManager->mutex); + HdfSListIteratorInit(&it, &devSvcManager->services); + while (HdfSListIteratorHasNext(&it)) { + record = (struct DevSvcRecord *)HdfSListIteratorNext(&it); + if ((record != NULL) && (record->key == serviceKey)) { + searchResult = record; + break; + } + } + OsalMutexUnlock(&devSvcManager->mutex); + return searchResult; +} + +int DevSvcManagerAddService(struct IDevSvcManager *inst, const char *svcName, struct HdfDeviceObject *service) +{ + struct DevSvcManager *devSvcManager = (struct DevSvcManager *)inst; + if ((devSvcManager == NULL) || (service == NULL) || (svcName == NULL)) { + HDF_LOGE("Add service failed, input param is null"); + return HDF_FAILURE; + } + + struct DevSvcRecord *record = DevSvcRecordNewInstance(); + if (record == NULL) { + HDF_LOGE("Add service failed, record is null"); + return HDF_FAILURE; + } + + record->key = HdfStringMakeHashKey(svcName, 0); + record->value = service; + OsalMutexLock(&devSvcManager->mutex); + HdfSListAdd(&devSvcManager->services, &record->entry); + OsalMutexUnlock(&devSvcManager->mutex); + return HdfServiceObserverPublishService( + &devSvcManager->observer, svcName, 0, SERVICE_POLICY_PUBLIC, (struct HdfObject *)service->service); +} + +int DevSvcManagerSubscribeService(struct IDevSvcManager *inst, const char *svcName, struct SubscriberCallback callBack) +{ + int ret = HDF_FAILURE; + struct DevSvcManager *devSvcMgr = (struct DevSvcManager *)inst; + if (svcName == NULL || devSvcMgr == NULL) { + return ret; + } + + ret = HdfServiceObserverSubscribeService(&devSvcMgr->observer, svcName, 0, callBack); + if (ret != HDF_SUCCESS) { + return ret; + } + + struct HdfObject *deviceService = DevSvcManagerGetService(inst, svcName); + if (deviceService != NULL) { + if (callBack.OnServiceConnected != NULL) { + callBack.OnServiceConnected(callBack.deviceObject, deviceService); + } + return HDF_SUCCESS; + } + + return DevmgrServiceLoadDevice(svcName); +} + +int DevSvcManagerUnsubscribeService(struct IDevSvcManager *inst, const char *svcName) +{ + struct DevSvcManager *devSvcMgr = (struct DevSvcManager *)inst; + if (devSvcMgr == NULL) { + return HDF_FAILURE; + } + HdfServiceObserverRemoveRecord(&devSvcMgr->observer, svcName); + return HDF_SUCCESS; +} + + +void DevSvcManagerRemoveService(struct IDevSvcManager *inst, const char *svcName) +{ + struct DevSvcManager *devSvcManager = (struct DevSvcManager *)inst; + uint32_t serviceKey = HdfStringMakeHashKey(svcName, 0); + if (svcName == NULL || devSvcManager == NULL) { + return; + } + struct DevSvcRecord *serviceRecord = DevSvcManagerSearchService(inst, serviceKey); + if (serviceRecord != NULL) { + OsalMutexLock(&devSvcManager->mutex); + HdfSListRemove(&devSvcManager->services, &serviceRecord->entry); + OsalMutexUnlock(&devSvcManager->mutex); + } +} + +struct HdfDeviceObject *DevSvcManagerGetObject(struct IDevSvcManager *inst, const char *svcName) +{ + uint32_t serviceKey = HdfStringMakeHashKey(svcName, 0); + if (svcName == NULL) { + HDF_LOGE("Get service failed, svcName is null"); + return NULL; + } + struct DevSvcRecord *serviceRecord = DevSvcManagerSearchService(inst, serviceKey); + if (serviceRecord != NULL) { + return serviceRecord->value; + } + HDF_LOGE("Get object failed, serviceRecord is null, svcName is %s", svcName); + return NULL; +} + +struct HdfObject *DevSvcManagerGetService(struct IDevSvcManager *inst, const char *svcName) +{ + struct HdfDeviceObject *deviceObject = DevSvcManagerGetObject(inst, svcName); + if (deviceObject == NULL) { + HDF_LOGE("Get service failed"); + return NULL; + } + return (struct HdfObject *)deviceObject->service; +} + +static bool DevSvcManagerConstruct(struct DevSvcManager *inst) +{ + struct IDevSvcManager *devSvcMgrIf = &inst->super; + devSvcMgrIf->AddService = DevSvcManagerAddService; + devSvcMgrIf->SubscribeService = DevSvcManagerSubscribeService; + devSvcMgrIf->UnsubscribeService = DevSvcManagerUnsubscribeService; + devSvcMgrIf->RemoveService = DevSvcManagerRemoveService; + devSvcMgrIf->GetService = DevSvcManagerGetService; + devSvcMgrIf->GetObject = DevSvcManagerGetObject; + HdfSListInit(&inst->services); + if (OsalMutexInit(&inst->mutex) != HDF_SUCCESS) { + HDF_LOGE("Device service manager create mutex failed!"); + return false; + } + return true; +} + +struct HdfObject *DevSvcManagerCreate() +{ + static bool isDevSvcManagerInit = false; + static struct DevSvcManager devSvcManagerInstance; + if (!isDevSvcManagerInit) { + if (!DevSvcManagerConstruct(&devSvcManagerInstance)) { + return NULL; + } + isDevSvcManagerInit = true; + } + return (struct HdfObject *)&devSvcManagerInstance; +} + +void DevSvcManagerRelease(struct HdfObject *object) +{ + struct DevSvcManager *devSvcManager = (struct DevSvcManager *)object; + if (object == NULL) { + return; + } + HdfSListFlush(&devSvcManager->services, DevSvcRecordDelete); + OsalMutexDestroy(&devSvcManager->mutex); +} + +struct IDevSvcManager *DevSvcManagerGetInstance() +{ + static struct IDevSvcManager *instance = NULL; + if (instance == NULL) { + instance = (struct IDevSvcManager *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DEVSVC_MANAGER); + } + return instance; +} + diff --git a/core/manager/src/hdf_driver_installer.c b/core/manager/src/hdf_driver_installer.c new file mode 100755 index 00000000..b199b7fe --- /dev/null +++ b/core/manager/src/hdf_driver_installer.c @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_driver_installer.h" +#include "devhost_service.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_object_manager.h" + +#define HDF_LOG_TAG driver_installer + +static int DriverInstallerStartDeviceHost(uint32_t devHostId, const char *devHostName) +{ + struct IDevHostService *hostServiceIf = DevHostServiceNewInstance(devHostId, devHostName); + if ((hostServiceIf == NULL) || (hostServiceIf->StartService == NULL)) { + HDF_LOGE("hostServiceIf or hostServiceIf->StartService is null"); + return HDF_FAILURE; + } + int ret = hostServiceIf->StartService(hostServiceIf); + if (ret != HDF_SUCCESS) { + HDF_LOGE("Start host service failed, ret is: %d", ret); + DevHostServiceFreeInstance(hostServiceIf); + } + return ret; +} + +static void DriverInstallerConstruct(struct DriverInstaller *inst) +{ + struct IDriverInstaller *driverInstallIf = (struct IDriverInstaller *)inst; + driverInstallIf->StartDeviceHost = DriverInstallerStartDeviceHost; +} + +struct HdfObject *DriverInstallerCreate(void) +{ + static bool isDriverInstInit = false; + static struct DriverInstaller driverInstaller; + if (!isDriverInstInit) { + DriverInstallerConstruct(&driverInstaller); + isDriverInstInit = true; + } + return (struct HdfObject *)&driverInstaller; +} + +struct IDriverInstaller *DriverInstallerGetInstance() +{ + static struct IDriverInstaller *installer = NULL; + if (installer == NULL) { + installer = (struct IDriverInstaller *)HdfObjectManagerGetObject(HDF_OBJECT_ID_DRIVER_INSTALLER); + } + return installer; +} + diff --git a/core/manager/src/hdf_host_info.c b/core/manager/src/hdf_host_info.c new file mode 100755 index 00000000..70e9126a --- /dev/null +++ b/core/manager/src/hdf_host_info.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_host_info.h" +#include "osal_mem.h" + +struct HdfHostInfo *HdfHostInfoNewInstance() +{ + return (struct HdfHostInfo *)OsalMemCalloc(sizeof(struct HdfHostInfo)); +} + +void HdfHostInfoFreeInstance(struct HdfHostInfo *hostInfo) +{ + if (hostInfo != NULL) { + OsalMemFree(hostInfo); + } +} + +void HdfHostInfoDelete(struct HdfSListNode *listEntry) +{ + struct HdfHostInfo *hostInfo = (struct HdfHostInfo *)listEntry; + if (hostInfo != NULL) { + HdfHostInfoFreeInstance(hostInfo); + } +} \ No newline at end of file diff --git a/core/manager/src/power_state_manager.c b/core/manager/src/power_state_manager.c new file mode 100755 index 00000000..700453c7 --- /dev/null +++ b/core/manager/src/power_state_manager.c @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "power_state_manager.h" +#include "hdf_object_manager.h" +#include "power_state_token_clnt.h" + +static struct PowerStateTokenClnt *PowerStateManagerGetStateTokenClnt( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + struct HdfSListIterator it; + if (inst == NULL) { + return NULL; + } + HdfSListIteratorInit(&it, &inst->tokens); + while (HdfSListIteratorHasNext(&it)) { + struct PowerStateTokenClnt *tokenClnt = + (struct PowerStateTokenClnt *)HdfSListIteratorNext(&it); + if (tokenClnt->tokenIf == tokenIf) { + return tokenClnt; + } + } + return NULL; +} + +static void PowerStateManagerAcquireWakeLock( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + if (inst == NULL) { + return; + } + struct HdfSRef *sref = &inst->wakeRef; + struct PowerStateTokenClnt *stateTokeClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); + if (stateTokeClnt == NULL) { + return; + } + stateTokeClnt->powerState = POWER_STATE_ACTIVE; + if (sref->Acquire != NULL) { + sref->Acquire(sref); + } +} + +static void PowerStateManagerReleaseWakeLock( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + struct HdfSRef *sref = NULL; + struct PowerStateTokenClnt *stateTokeClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); + if (inst == NULL || stateTokeClnt == NULL) { + return; + } + stateTokeClnt->powerState = POWER_STATE_INACTIVE; + sref = &inst->wakeRef; + if (sref->Release != NULL) { + sref->Release(sref); + } +} + +static void PowerStateManagerConstruct(struct PowerStateManager *inst) +{ + // not support system acquire and release + static struct IHdfSRefListener wakeLockRefListener = { + .OnFirstAcquire = NULL, + .OnLastRelease = NULL, + }; + + inst->AcquireWakeLock = PowerStateManagerAcquireWakeLock; + inst->ReleaseWakeLock = PowerStateManagerReleaseWakeLock; + HdfSListInit(&inst->tokens); + HdfSRefConstruct(&inst->wakeRef, &wakeLockRefListener); +} + +struct PowerStateManager *PowerStateManagerGetInstance() +{ + static struct PowerStateManager powerStateManager = { 0 }; + if (powerStateManager.AcquireWakeLock == NULL) { + PowerStateManagerConstruct(&powerStateManager); + } + return &powerStateManager; +} diff --git a/core/manager/src/power_state_token_clnt.c b/core/manager/src/power_state_token_clnt.c new file mode 100755 index 00000000..ee5dac31 --- /dev/null +++ b/core/manager/src/power_state_token_clnt.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "power_state_token_clnt.h" +#include "osal_mem.h" + +static void PowerStateTokenClntConstruct(struct PowerStateTokenClnt *clnt, struct IPowerStateToken *tokenIf) +{ + clnt->tokenIf = tokenIf; + clnt->powerState = POWER_STATE_INACTIVE; +} + +struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf) +{ + struct PowerStateTokenClnt *tokenClnt = + (struct PowerStateTokenClnt *)OsalMemCalloc(sizeof(struct PowerStateTokenClnt)); + if (tokenClnt != NULL) { + PowerStateTokenClntConstruct(tokenClnt, tokenIf); + return tokenClnt; + } + return tokenClnt; +} + +void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt) +{ + if (tokenClnt != NULL) { + OsalMemFree(tokenClnt); + } +} diff --git a/core/shared/include/devhost_service_if.h b/core/shared/include/devhost_service_if.h new file mode 100755 index 00000000..a09a958b --- /dev/null +++ b/core/shared/include/devhost_service_if.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVHOST_SERVICE_IF_H +#define DEVHOST_SERVICE_IF_H + +#include "hdf_device_info.h" +#include "hdf_object.h" + +struct IDevHostService { + struct HdfObject object; + int (*AddDevice)(struct IDevHostService *, const struct HdfDeviceInfo *); + int (*DelDevice)(struct IDevHostService *, const struct HdfDeviceInfo *); + int (*StartService)(struct IDevHostService *); +}; + +#endif /* DEVHOST_SERVICE_IF_H */ diff --git a/core/shared/include/device_token_if.h b/core/shared/include/device_token_if.h new file mode 100755 index 00000000..a91672c2 --- /dev/null +++ b/core/shared/include/device_token_if.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVICE_TOKEN_IF_H +#define DEVICE_TOKEN_IF_H + +#include "hdf_object.h" + +struct IHdfDeviceToken { + struct HdfObject object; +}; + +#endif /* DEVICE_TOKEN_IF_H */ diff --git a/core/shared/include/devmgr_service_if.h b/core/shared/include/devmgr_service_if.h new file mode 100755 index 00000000..cc1d127d --- /dev/null +++ b/core/shared/include/devmgr_service_if.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVMGR_SERVICE_IF_H +#define DEVMGR_SERVICE_IF_H + +#include "devhost_service_if.h" +#include "device_token_if.h" +#include "hdf_object.h" +#include "power_state_token_if.h" + +struct IDevmgrService { + struct HdfDeviceObject object; + int (*AttachDeviceHost)(struct IDevmgrService *, uint16_t, struct IDevHostService *); + int (*AttachDevice)(struct IDevmgrService *, const struct HdfDeviceInfo *, struct IHdfDeviceToken *); + int (*StartService)(struct IDevmgrService *); + void (*AcquireWakeLock)(struct IDevmgrService *, struct IPowerStateToken *); + void (*ReleaseWakeLock)(struct IDevmgrService *, struct IPowerStateToken *); +}; + +#endif /* DEVMGR_SERVICE_IF_H */ diff --git a/core/shared/include/devsvc_manager_if.h b/core/shared/include/devsvc_manager_if.h new file mode 100755 index 00000000..d1787ec4 --- /dev/null +++ b/core/shared/include/devsvc_manager_if.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVSVC_MANAGER_IF_H +#define DEVSVC_MANAGER_IF_H + +#include "hdf_device_desc.h" +#include "hdf_object.h" + +struct IDevSvcManager { + struct HdfObject object; + int (*AddService)(struct IDevSvcManager *, const char *, struct HdfDeviceObject *); + int (*SubscribeService)(struct IDevSvcManager *, const char *, struct SubscriberCallback); + int (*UnsubscribeService)(struct IDevSvcManager *, const char *); + struct HdfObject *(*GetService)(struct IDevSvcManager *, const char *); + struct HdfDeviceObject *(*GetObject)(struct IDevSvcManager *, const char *); + void (*RemoveService)(struct IDevSvcManager *, const char *); +}; + +#endif /* DEVSVC_MANAGER_IF_H */ diff --git a/core/shared/include/hdf_attribute_manager.h b/core/shared/include/hdf_attribute_manager.h new file mode 100755 index 00000000..8b0dd595 --- /dev/null +++ b/core/shared/include/hdf_attribute_manager.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_ATTRIBUTE_MANAGER_H +#define HDF_ATTRIBUTE_MANAGER_H + +#include "hdf_slist.h" + +bool HdfAttributeManagerGetHostList(struct HdfSList *hostList); +struct HdfSList *HdfAttributeManagerGetDeviceList(uint16_t hostId, const char *hostName); +void ReleaseHcsTree(void); + +#endif /* HDF_ATTRIBUTE_MANAGER_H */ diff --git a/core/shared/include/hdf_device_info.h b/core/shared/include/hdf_device_info.h new file mode 100755 index 00000000..eaebf28a --- /dev/null +++ b/core/shared/include/hdf_device_info.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_DEVICE_INFO_H +#define HDF_DEVICE_INFO_H + +#include "hdf_device_desc.h" +#include "hdf_slist.h" + +struct HdfDeviceInfo { + struct HdfSListNode node; + uint16_t hostId; + uint16_t deviceId; + uint16_t policy; + uint16_t priority; + uint16_t preload; + uint16_t permission; + const char *moduleName; + const char *svcName; + const char *deviceMatchAttr; +}; + +struct HdfDeviceInfo *HdfDeviceInfoNewInstance(void); +void HdfDeviceInfoFreeInstance(struct HdfDeviceInfo *deviceInfo); +void HdfDeviceInfoDelete(struct HdfSListNode *listEntry); + +#endif /* HDF_DEVICE_INFO_H */ diff --git a/core/shared/include/hdf_io_service.h b/core/shared/include/hdf_io_service.h new file mode 100755 index 00000000..cd9e2f10 --- /dev/null +++ b/core/shared/include/hdf_io_service.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_IO_SERVICE_H +#define HDF_IO_SERVICE_H + +#include "hdf_io_service_if.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define DEV_NODE_PATH "/dev/" +#define DEV_MGR_NODE "dev_mgr" +#define MAX_MODE_SIZE 0777 + +struct HdfIoService *HdfIoServiceObtain( + struct HdfObject *object, struct HdfIoDispatcher *dispatcher); +struct HdfIoService *HdfIoServiceAdapterObtain(const char* serviceName, mode_t mode); +void HdfIoServiceAdapterRecycle(struct HdfIoService *service); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_IO_SERVICE_H */ + diff --git a/core/shared/include/hdf_object_manager.h b/core/shared/include/hdf_object_manager.h new file mode 100755 index 00000000..b0471275 --- /dev/null +++ b/core/shared/include/hdf_object_manager.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_OBJECT_MANAGER_H +#define HDF_OBJECT_MANAGER_H + +#include +#include "hdf_object.h" + +enum { + HDF_OBJECT_ID_DEVMGR_SERVICE = 0, + HDF_OBJECT_ID_DEVSVC_MANAGER, + HDF_OBJECT_ID_DEVHOST_SERVICE, + HDF_OBJECT_ID_DRIVER_INSTALLER, + HDF_OBJECT_ID_DRIVER_LOADER, + HDF_OBJECT_ID_DEVICE, + HDF_OBJECT_ID_DEVICE_TOKEN, + HDF_OBJECT_ID_DEVICE_SERVICE, + HDF_OBJECT_ID_REMOTE_SERVICE, + HDF_OBJECT_ID_MAX +}; + +struct HdfObjectCreator { + struct HdfObject *(*Create)(void); + void (*Release)(struct HdfObject *); +}; + +const struct HdfObjectCreator *HdfObjectManagerGetCreators(int objectId); +struct HdfObject *HdfObjectManagerGetObject(int ObjectId); +void HdfObjectManagerFreeObject(struct HdfObject *object); + +#endif /* HDF_OBJECT_MANAGER_H */ diff --git a/core/shared/include/hdf_service_record.h b/core/shared/include/hdf_service_record.h new file mode 100755 index 00000000..8d510cd0 --- /dev/null +++ b/core/shared/include/hdf_service_record.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEVSVC_RECORD_H +#define DEVSVC_RECORD_H + +#include "hdf_object.h" +#include "hdf_slist.h" + +struct DevSvcRecord { + struct HdfSListNode entry; + uint32_t key; + struct HdfDeviceObject *value; +}; + +struct DevSvcRecord *DevSvcRecordNewInstance(void); +void DevSvcRecordFreeInstance(struct DevSvcRecord *inst); +void DevSvcRecordDelete(struct HdfSListNode *listEntry); + +#endif /* DEVSVC_RECORD_H */ + diff --git a/core/shared/include/power_state_token_if.h b/core/shared/include/power_state_token_if.h new file mode 100755 index 00000000..0ccb291f --- /dev/null +++ b/core/shared/include/power_state_token_if.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef POWER_STATE_TOKEN_IF_H +#define POWER_STATE_TOKEN_IF_H + +typedef enum { + POWER_STATE_IDLE, /* Idle state */ + POWER_STATE_ACTIVE, /* Activated state */ + POWER_STATE_INACTIVE, /* Error state */ +} HdfPowerState; + +struct IPowerStateToken { + void (*AcquireWakeLock)(struct IPowerStateToken *); + void (*ReleaseWakeLock)(struct IPowerStateToken *); +}; + +#endif /* POWER_STATE_TOKEN_IF_H */ \ No newline at end of file diff --git a/core/shared/src/hdf_device_info.c b/core/shared/src/hdf_device_info.c new file mode 100755 index 00000000..5048a506 --- /dev/null +++ b/core/shared/src/hdf_device_info.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_device_info.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG device_info + +static void HdfDeviceInfoConstruct(struct HdfDeviceInfo *deviceInfo) +{ + deviceInfo->hostId = 0; + deviceInfo->deviceId = 0; + deviceInfo->policy = SERVICE_POLICY_INVALID; + deviceInfo->priority = 0; + deviceInfo->preload = DEVICE_PRELOAD_ENABLE; + deviceInfo->permission = 0; + deviceInfo->svcName = NULL; + deviceInfo->moduleName = NULL; + deviceInfo->deviceMatchAttr = NULL; +} + +struct HdfDeviceInfo *HdfDeviceInfoNewInstance() +{ + struct HdfDeviceInfo *deviceInfo = + (struct HdfDeviceInfo*)OsalMemCalloc(sizeof(struct HdfDeviceInfo)); + if (deviceInfo != NULL) { + HdfDeviceInfoConstruct(deviceInfo); + return deviceInfo; + } + HDF_LOGE("Create device deviceInfo failed"); + return NULL; +} + +void HdfDeviceInfoFreeInstance(struct HdfDeviceInfo *deviceInfo) +{ + if (deviceInfo != NULL) { + OsalMemFree(deviceInfo); + } +} + +void HdfDeviceInfoDelete(struct HdfSListNode *listEntry) +{ + struct HdfDeviceInfo *deviceInfo = (struct HdfDeviceInfo *)listEntry; + HdfDeviceInfoFreeInstance(deviceInfo); +} + diff --git a/core/shared/src/hdf_io_service.c b/core/shared/src/hdf_io_service.c new file mode 100755 index 00000000..43df0750 --- /dev/null +++ b/core/shared/src/hdf_io_service.c @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_io_service.h" +#include "hdf_vnode_adapter.h" + +struct HdfIoService *HdfIoServiceObtain( + struct HdfObject *object, struct HdfIoDispatcher *dispatcher) +{ + struct HdfIoService *service = HdfIoServiceAdapterObtain(NULL, 0); + if ((service != NULL) && (service->dispatcher == NULL)) { + service->dispatcher = dispatcher; + service->target = object; + } + return service; +} + +struct HdfIoService *HdfIoServiceBind(const char *serviceName, mode_t permission) +{ + return HdfIoServiceAdapterObtain(serviceName, permission); +} + +void HdfIoServiceRecycle(struct HdfIoService *service) +{ + HdfIoServiceAdapterRecycle(service); +} + diff --git a/core/shared/src/hdf_object_manager.c b/core/shared/src/hdf_object_manager.c new file mode 100755 index 00000000..bf8640c7 --- /dev/null +++ b/core/shared/src/hdf_object_manager.c @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_object_manager.h" + +struct HdfObject *HdfObjectManagerGetObject(int objectId) +{ + struct HdfObject *object = NULL; + const struct HdfObjectCreator *targetCreator = HdfObjectManagerGetCreators(objectId); + if ((targetCreator != NULL) && (targetCreator->Create != NULL)) { + object = targetCreator->Create(); + if (object != NULL) { + object->objectId = objectId; + } + } + return object; +} + +void HdfObjectManagerFreeObject(struct HdfObject *object) +{ + const struct HdfObjectCreator *targetCreator = NULL; + if (object == NULL) { + return; + } + targetCreator = HdfObjectManagerGetCreators(object->objectId); + if ((targetCreator == NULL) || (targetCreator->Release == NULL)) { + return; + } + targetCreator->Release(object); +} \ No newline at end of file diff --git a/core/shared/src/hdf_service_record.c b/core/shared/src/hdf_service_record.c new file mode 100755 index 00000000..91f53d84 --- /dev/null +++ b/core/shared/src/hdf_service_record.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_service_record.h" +#include "osal_mem.h" + +struct DevSvcRecord *DevSvcRecordNewInstance(void) +{ + return (struct DevSvcRecord *)OsalMemCalloc(sizeof(struct DevSvcRecord)); +} + +void DevSvcRecordFreeInstance(struct DevSvcRecord *inst) +{ + if (inst != NULL) { + OsalMemFree(inst); + } +} + +void DevSvcRecordDelete(struct HdfSListNode *listEntry) +{ + if (listEntry != NULL) { + OsalMemFree(listEntry); + } +} + diff --git a/include/config/device_resource_if.h b/include/config/device_resource_if.h new file mode 100755 index 00000000..85918cbd --- /dev/null +++ b/include/config/device_resource_if.h @@ -0,0 +1,470 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup DriverConfig + * @{ + * + * @brief Defines an API for HDF driver developers to read driver configuration information. + * + * During version compilation of the device resource source file defined by developers, the compilation tool + * (for example, the compilation tool of the HCS file is hc-gen) generates bytecodes. When the HDF starts, + * it transfers the bytecode memory to the DriverConfig module. The DriverConfig module converts + * the bytecodes into a configuration tree and provides an API for developers to query the tree. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file device_resource_if.h + * + * @brief Declares the API for querying the configuration tree. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef DEVICE_RESOURCE_IF_H +#define DEVICE_RESOURCE_IF_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates configuration file types. + */ +typedef enum { + HDF_CONFIG_SOURCE = 0, /**< HDF configuration file */ + INVALID, /**< Invalid configuration file type */ +} DeviceResourceType; + +/** + * @brief Defines the attributes of a tree node in the configuration tree. + * + * The tree node attributes are saved in a linked list. The information about each node in the linked list contains + * the attribute name, attribute value, and pointer that points to the next attribute. + */ +struct DeviceResourceAttr { + const char *name; /**< Pointer to the attribute name */ + const char *value; /**< Pointer to the attribute value */ + struct DeviceResourceAttr *next; /**< Pointer to the next attribute of the node in the configuration tree. */ +}; + +/** + * @brief Defines a tree node in the configuration tree. + * + * The tree node information includes the node name, unique node ID, node attributes, parent node, child nodes, + * and sibling nodes. + */ +struct DeviceResourceNode { + const char *name; /**< Pointer to the node name */ + uint32_t hashValue; /**< Unique ID of a node */ + struct DeviceResourceAttr *attrData; /**< Pointer to the node attributes */ + struct DeviceResourceNode *parent; /**< Pointer to the parent node */ + struct DeviceResourceNode *child; /**< Pointer to a child node */ + struct DeviceResourceNode *sibling; /**< Pointer to a sibling node */ +}; + +/** + * @brief Provides functions for obtaining information about the device resource configuration tree. + * + * This structure provides functions for obtaining information about the device resource configuration tree, + * including the root node, the unit attribute data, and the String attribute data. + * + * @since 1.0 + * @version 1.0 + */ +struct DeviceResourceIface { + /** + * @brief Obtains the root node of the configuration tree. + * + * When the driver framework is started, a configuration tree is created. You can use this function to obtain + * the root node of the configuration tree. + * + * @return Returns the root node of the configuration tree if the operation is successful; + * returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ + const struct DeviceResourceNode *(*GetRootNode)(void); + /** + * @brief Obtains the value of a BOOL attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * + * @return Returns the value of the BOOL attribute if the operation is successful; + * returns false if node and attrName are null pointers. + * @since 1.0 + * @version 1.0 + */ + bool (*GetBool)(const struct DeviceResourceNode *node, const char *attrName); + /** + * @brief Obtains the value of a Uint8 attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the attribute value is obtained successfully; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint8)(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint8_t def); + /** + * @brief Obtains the value of a Unit8 array attribute numbered index of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param index Indicates the number of the index (counting from 0) where the value is to obtain. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the array attribute value is obtained successfully; returns a negative value + * otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint8ArrayElem)(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint8_t *value, uint8_t def); + /** + * @brief Obtains the values of a Uint8 array attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param value Indicates the pointer to the array that stores the obtained data. The memory of the array is applied + * by the user. + * @param len Indicates the length of the array. + * @param def Indicates the value to fill into value if the operation fails. If the obtained attribute value + * contains 16-bit, 32-bit, or 64-bit data, the element corresponding to the 16-bit, 32-bit, or 64-bit data in the + * array is filled using the value of def, and the other elements are filled with the actual value obtained. + * If the failure is caused by other exceptions, the first element in the array is filled using the value of + * def. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint8Array)(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint32_t len, + uint8_t def); + /** + * @brief Obtains the value of a Uint16 attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint16)(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint16_t def); + /** + * @brief Obtains the value of a Uint16 array attribute numbered index of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param index Indicates the number of the index (counting from 0) where the value is to obtain. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint16ArrayElem)(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint16_t *value, uint16_t def); + /** + * @brief Obtains the values of a Uint16 array attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param value Indicates the pointer to the array that stores the obtained data. The memory of the array is applied + * by the user. + * @param len Indicates the length of the array. + * @param def Indicates the value to fill into value if the operation fails. If the obtained attribute value + * contains 32-bit or 64-bit data, the element corresponding to the 32-bit or 64-bit data in the array is filled + * using the value of def, and the other elements are filled with the actual value obtained. If the failure + * is caused by other exceptions, the first element in the array is filled using the value of def. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint16Array)(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, + uint32_t len, uint16_t def); + /** + * @brief Obtains the value of a Uint32 attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint32)(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, uint32_t def); + /** + * @brief Obtains the value of a Uint32 array attribute numbered index of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param index Indicates the number of the index (counting from 0) where the value is to obtain. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint32ArrayElem)(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint32_t *value, uint32_t def); + /** + * @brief Obtains the values of a Uint32 array attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param value Indicates the pointer to an array that stores the obtained data. + * @param len Indicates the pointer to the array that stores the obtained data. The memory of the array is applied + * by the user. + * @param def Indicates the value to fill into value if the operation fails. If the obtained attribute value + * contains 64-bit data, the element corresponding to the 64-bit data in the array is filled using the value of + * def, and the other elements are filled with the actual value obtained. If the failure is caused by other + * exceptions, the first element in the array is filled using the value of def. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint32Array)(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, + uint32_t len, uint32_t def); + /** + * @brief Obtains the value of a Uint64 attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint64)(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, uint64_t def); + /** + * @brief Obtains the value of a Uint64 array attribute numbered index of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param index Indicates the number of the index (counting from 0) where the value is to obtain. + * @param value Indicates the pointer to the memory that stores the obtained data. The memory is applied + * by the user. + * @param def Indicates the value to fill into the memory pointed by value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint64ArrayElem)(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + uint64_t *value, uint64_t def); + /** + * @brief Obtains the values of a Uint64 array attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param value Indicates the pointer to the array that stores the obtained data. The memory of the array is applied + * by the user. + * @param len Indicates the length of the array. + * @param def Indicates the value to fill into the first element in the value array if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetUint64Array)(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, + uint32_t len, uint64_t def); + /** + * @brief Obtains the value of a String attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the attribute. + * @param value Indicates the double pointer to the memory where the obtained data is stored. The string memory is + * provided by the function implementer. Users only need to transfer the double pointer. The memory cannot be + * released after being used. + * @param def Indicates the value to be passed to value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetString)(const struct DeviceResourceNode *node, const char *attrName, const char **value, + const char *def); + /** + * @brief Obtains the value of a String array attribute numbered index of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * @param index Indicates the number of the index (counting from 0) where the value is to obtain. + * @param value Indicates the double pointer to the memory where the obtained data is stored. The string memory is + * provided by the function implementer. Users only need to transfer the double pointer. The memory cannot be + * released after being used. + * @param def def Indicates the value to be passed to value if the operation fails. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetStringArrayElem)(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, + const char **value, const char *def); + /** + * @brief Obtains the number of values for an array attribute of a configuration tree node. + * + * @param node Indicates the pointer to the configuration tree node. + * @param attrName Indicates the pointer to the name of the array attribute. + * + * @return Returns the number of values for an array attribute if the operation is successful; + * return a negative value otherwise. + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetElemNum)(const struct DeviceResourceNode *node, const char *attrName); + /** + * @brief Obtains a specified child node of the current tree node based on the value of a specific reserved + * attribute (for example, the reserved attribute of the HCS is match_attr). + * + * There is a specific reserved attribute in the syntax of the device resource configuration source file. + * If this attribute is set for a tree node, you can obtain the node based on the attribute value. + * Users can set the attribute value based on the usage of their own nodes, but they must ensure that the attribute + * values are unique. + * + * @param node Indicates the pointer to the node for whom a child node is to be obtained. The node can be the child + * node's parent node or grandparent node. + * @param attrValue Indicates the pointer to the value of the reserved attribute configured for the child node. + * + * @return Returns the target node if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ + const struct DeviceResourceNode *(*GetNodeByMatchAttr)(const struct DeviceResourceNode *node, + const char *attrValue); + /** + * @brief Obtains the child node with a specified node name from a parent node. + * + * @param node Indicates the pointer to the parent node. + * @param nodeName Indicates the pointer to the name of the child node to obtain. + * + * @return Returns the child nodes if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ + const struct DeviceResourceNode *(*GetChildNode)(const struct DeviceResourceNode *node, const char *nodeName); + /** + * @brief Obtains the node that is specified by a node-type attribute of a configuration tree node. + * + * If the attribute value is a configuration tree node, the path of the node is converted to a globally unique + * hashValue when the device resource source file is compiled (for example, the compilation tool of the HCS + * source file is hc-gen). For details about the hashValue, see {@link struct DeviceResourceNode}. + * When you obtain a tree node using the node-type attribute, you obtain the hashValue through the node-type + * attribute first, and then traverse the tree to obtain the tree node corresponding to the hashValue. + * + * @param node Indicates the pointer to the tree node whose attribute is to obtain. + * @param attrName Indicates the pointer to the name of attribute whose value is a node path. + * @return Returns the target node if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ + const struct DeviceResourceNode *(*GetNodeByRefAttr)(const struct DeviceResourceNode *node, const char *attrName); +}; + +/** + * @brief Obtains the device resource interface handle of the corresponding configuration tree type. + * + * You can use the obtained handle to use the device resource interface. + * + * @param type Indicates the type of the device resource interface handle to obtain. + * + * @return Returns the device resource interface handle if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ +struct DeviceResourceIface *DeviceResourceGetIfaceInstance(DeviceResourceType type); + +/** + * @brief Traverses the attributes of the current configuration tree node. + * + * This operation is a for loop in essence. + * + * @param node Indicates the configuration tree node to traverse. + * @param attr Indicates the traversed attributes. + * @since 1.0 + * @version 1.0 + */ +#define DEV_RES_NODE_FOR_EACH_ATTR(node, attr) \ + for ((attr) = (node)->attrData; (attr) != NULL; (attr) = (attr)->next) + +/** + * @brief Traverses the child nodes of the current configuration tree node. + * + * This operation is a for loop in essence. + * + * @param node Indicates the configuration tree node to traverse. + * @param childNode Indicates the traversed child nodes. + * @since 1.0 + * @version 1.0 + */ +#define DEV_RES_NODE_FOR_EACH_CHILD_NODE(node, childNode) \ + for ((childNode) = (node)->child; (childNode) != NULL; (childNode) = (childNode)->sibling) + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // DEVICE_RESOURCE_IF_H +/** @} */ diff --git a/include/core/hdf_device_desc.h b/include/core/hdf_device_desc.h new file mode 100755 index 00000000..500f7020 --- /dev/null +++ b/include/core/hdf_device_desc.h @@ -0,0 +1,343 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup Core + * @{ + * + * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * + * The HDF implements driver framework capabilities such as driver loading, service management, + * and driver message model. You can develop drivers based on the HDF. + * + * @since 1.0 + */ + +/** + * @file hdf_device_desc.h + * + * @brief Declares functions related to driver loading, service obtaining, and power management. + * + * @since 1.0 + */ + +#ifndef HDF_DEVICE_DESC_H +#define HDF_DEVICE_DESC_H + +#include "hdf_device_section.h" +#include "hdf_object.h" +#include "hdf_sbuf.h" + +/** + * @brief The maximum priority for loading the host and device. + */ +#define MAX_PRIORITY_NUM 200 + +/** + * @brief Enumerates policies for releasing driver services developed based on the HDF. + * + * If a driver is developed based on the HDF and uses the service management feature of the HDF, you need to + * configure the policy for releasing services to external systems. + * + * @since 1.0 + */ +typedef enum { + /** The driver does not provide services externally. */ + SERVICE_POLICY_NONE = 0, + /** The driver provides services for kernel-level applications. */ + SERVICE_POLICY_PUBLIC, + /** The driver provides services for both kernel- and user-level applications. */ + SERVICE_POLICY_CAPACITY, + /** Driver services are not released externally but can be subscribed to. */ + SERVICE_POLICY_FRIENDLY, + /** Driver services are only internally available. + They are not released externally and cannot be subscribed to by external users. */ + SERVICE_POLICY_PRIVATE, + /** The service policy is incorrect. */ + SERVICE_POLICY_INVALID +} ServicePolicy; + +/** + * @brief Enumerates driver loading policies. + * + * If a driver developed based on the HDF needs to use the on-demand loading mechanism in the HDF, the PRELOAD + * field must be correctly set in the driver configuration information to control the driver loading mode. + * + * @since 1.0 + */ +typedef enum { + DEVICE_PRELOAD_ENABLE = 0, /**< The driver is loaded during system startup by default. */ + DEVICE_PRELOAD_DISABLE, /**< The driver is not loaded during system startup by default. */ + DEVICE_PRELOAD_INVALID /**< The loading policy is incorrect. */ +} DevicePreload; + +/** + * @brief Defines the device object. + * + * This structure is a device object defined by the HDF and is used to store private data and interface information + * of a device. + * + * @since 1.0 + */ +struct HdfDeviceObject { + /** Pointer to the service interface object, which is registered with the HDF by the driver */ + struct IDeviceIoService *service; + /** Pointer to the private data of the device, which is read by the HDF from the configuration file and + transmitted to the driver. */ + const struct DeviceResourceNode *property; +}; + +/** + * @brief Defines the client object structure of the I/O service. + * + * This structure describes the invoker information of the I/O servcie. + * + * @since 1.0 + */ +struct HdfDeviceIoClient { + /** Device object corresponding to the client object */ + struct HdfDeviceObject *device; + /** Private data of the client object. The driver can use priv to bind the internal data with the client. */ + void *priv; +}; + +/** + * @brief Defines the driver service. + * + * When a driver releases services to user-level applications, the service interface must inherit this structure + * and implements the Dispatch function in the structure. + * + * @since 1.0 + */ +struct IDeviceIoService { + /** Driver service object ID */ + struct HdfObject object; + /** + * @brief Called when the driver service is enabled by a user-level application. + * + * @param client Indicates the pointer to the client object of the service. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ + int32_t (*Open)(struct HdfDeviceIoClient *client); + /** + * @brief Called when the driver service is invoked by a user-level application. + * + * @param client Indicates the pointer to the client object of the service. + * @param cmdId Indicates the command word of the service interface. + * @param data Indicates the pointer to the data passed by the invoker. + * @param reply Indicates the pointer to the data that needs to be returned to the invoker. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ + int32_t (*Dispatch)(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply); + /** + * @brief Called when the driver service is released by a user-level application. + * + * @param client Indicates the pointer to the client object of the service. + * + * @since 1.0 + */ + void (*Release)(struct HdfDeviceIoClient *client); +}; + +/** + * @brief Called when the driver subscribes to other driver services. + * + * The callback is used in the service subscription mechanism. After the driver is registered with the HDF, the HDF + * proactively invokes the callback after the subscribed-to driver is loaded. + * + * @since 1.0 + */ +struct SubscriberCallback { + /** Driver object of the subscriber */ + struct HdfDeviceObject *deviceObject; + /** + * @brief Called by the HDF when the subscribed-to driver service is loaded. + * + * @param deviceObject Indicates the pointer to the variable of the {@link HdfDeviceObject} type. This variable + * is generated by the HDF and passed to the driver. + * @param service Indicates the pointer to the service object. + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + */ + int32_t (*OnServiceConnected)(struct HdfDeviceObject *deviceObject, const struct HdfObject *service); +}; + +/** + * @brief Defines the power management functions provided by the HDF for the driver. + * + * To use the power management mechanism provided by the HDF, implement operations of IPowerEventListener and + * invoke {@linkHdfDeviceRegisterPowerListener} to register the operations with the HDF. + * + * @since 1.0 + */ +struct IPowerEventListener { + /** Wakes up the driver device. The driver developer implements the operation. */ + void (*Resume)(struct HdfDeviceObject *deviceObject); + /** Hibernates the driver device. The driver developer implements the operation. */ + void (*Suspend)(struct HdfDeviceObject *deviceObject); +}; + +/** + * @brief Defines the entry structure of the driver in the HDF. + * + * This structure must be used as the entry for the driver to use the HDF mechanism. + * + * @since 1.0 + */ +struct HdfDriverEntry { + /** Driver version */ + int32_t moduleVersion; + /** Driver module name, which is used to match the driver information in the configuration file. */ + const char *moduleName; + /** + * @brief Binds the external service interface of a driver to the HDF. This function is implemented by the driver + * developer and called by the HDF. + * + * @param deviceObject Indicates the pointer to the variable of the {@link HdfDeviceObject} type. This variable + * is generated by the HDF and passed to the driver. Then, the service object of the driver is bound to the + * service parameter of deviceObject. + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + */ + int32_t (*Bind)(struct HdfDeviceObject *deviceObject); + /** + * @brief Initializes the driver. This function is implemented by the driver developer and called by the HDF. + * + * @param deviceObject Indicates the pointer to the variable of the {@link HdfDeviceObject} type. It is the same + * as the parameter of {@link Bind}. + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + */ + int32_t (*Init)(struct HdfDeviceObject *deviceObject); + /** + * @brief Releases driver resources. This function is implemented by the driver developer. When an exception + * occurs during driver loading or the driver is uninstalled, the HDF calls this function to release the + * driver resources. + * + * @param deviceObject Indicates the pointer to the variable of the {@link HdfDeviceObject} type. It is the same + * as the parameter of {@link Bind}. + * + * @since 1.0 + */ + void (*Release)(struct HdfDeviceObject *deviceObject); +}; + +/** + * @brief Registers the driver with the HDF. + * + * For a driver developed based on the HDF, {@link HDF_INIT} must be used to register an entry with the HDF, and the + * registered object must be of the {@link HdfDriverEntry} type. + * + * @param module Indicates the global variable of the {@link HdfDriverEntry} type + * + * @since 1.0 + */ +#define HDF_INIT(module) HDF_DRIVER_INIT(module) + +/** + * @brief Obtains the driver service object based on a driver service name. + * + * @param serviceName Indicates the pointer to the released driver service name. + * + * @return Returns the driver service object if the operation is successful; returns NULL otherwise. + * @since 1.0 + */ +const struct HdfObject *DevSvcManagerClntGetService(const char *svcName); + +/** + * @brief Obtains the service name of a driver. + * + * If a driver does not save its service name, it can use this function to obtain the service name. \n + * + * @param deviceObject Indicates the pointer to the driver device object. + * + * @return Returns the service name if the operation is successful; returns NULL otherwise. + * @since 1.0 + */ +const char *HdfDeviceGetServiceName(const struct HdfDeviceObject *deviceObject); + +/** + * @brief Subscribes to a driver service. + * + * If the driver loading time is not perceived, this function can be used to subscribe to the driver service. (The + * driver service and the subscriber must be on the same host.) After the subscribed-to driver service is loaded by the + * HDF, the framework proactively releases the service interface to the subscriber. \n + * + * @param deviceObject Indicates the pointer to the driver device object of the subscriber. + * @param serviceName Indicates the pointer to the driver service name. + * @param callback Indicates the callback invoked by the HDF after the subscribed-to driver service is loaded. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * @since 1.0 + */ +int32_t HdfDeviceSubscribeService( + struct HdfDeviceObject *deviceObject, const char *serviceName, struct SubscriberCallback callback); + +/** + * @brief Sends event messages. + * + * When the driver service invokes this function to send a message, all user-level applications that have registered + * listeners through {@link HdfDeviceRegisterEventListener} will receive the message. + * + * @param deviceObject Indicates the pointer to the driver device object. + * @param id Indicates the ID of the message sending event. + * @param data Indicates the pointer to the message content sent by the driver. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * @since 1.0 + */ +int32_t HdfDeviceSendEvent(const struct HdfDeviceObject *deviceObject, uint32_t id, const struct HdfSBuf *data); + + +/** + * @brief Sends an event message to a specified client object. + * + * When the driver service invokes this function to send a message, the user-level applications that have registered + * listeners through {@link HdfDeviceRegisterEventListener} and correspond to this client object will receive + * the message. + * + * @param client Indicates the pointer to the client object of the driver service. + * @param id Indicates the ID of the message sending event. + * @param data Indicates the pointer to the message content sent by the driver. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * @since 1.0 */ +int32_t HdfDeviceSendEventToClient(const struct HdfDeviceIoClient *client, uint32_t id, const struct HdfSBuf *data); + +#endif /* HDF_DEVICE_DESC_H */ +/** @} */ diff --git a/include/core/hdf_io_service_if.h b/include/core/hdf_io_service_if.h new file mode 100755 index 00000000..918f0077 --- /dev/null +++ b/include/core/hdf_io_service_if.h @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/** + * @addtogroup Core + * @{ + * + * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * + * The HDF implements driver framework capabilities such as driver loading, service management, + * and driver message model. You can develop drivers based on the HDF. + * + * @since 1.0 + */ + +/** + * @file hdf_io_service_if.h + * + * @brief Declares the structures defining driver service objects and event listeners, as well as the functions for + * obtaining a driver service object, dispatching a driver service call, and registering or unregistering an + * event listener. + * + * @since 1.0 + */ +#ifndef HDF_IO_SERVICE_IF_H +#define HDF_IO_SERVICE_IF_H + +#include +#include "hdf_dlist.h" +#include "hdf_object.h" +#include "hdf_sbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Called when a driver event occurs. + * + * You can implement this function and bind it to the custom {@link HdfDevEventlistener} object. \n + * + * @param priv Indicates the pointer to the private data bound to this listener. + * @param id Indicates the serial number of the driver event occurred. + * @param data Indicates the pointer to the content data of the driver event. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +typedef int (*OnEventReceived)(void *priv, uint32_t id, struct HdfSBuf *data); + +/** + * @brief Defines a driver event listener object. + * + * @since 1.0 + */ +struct HdfDevEventlistener { + /** Callback invoked when the monitored device reports an event */ + OnEventReceived callBack; + /** Intrusive list node used by the HDF to manage listeners. You can ignore this node. */ + struct DListHead listNode; + /** Private data of the listener, which is passed as the first input parameter in callback */ + void *priv; +}; + +/** + * @brief Defines a driver service call dispatcher. + * + * @since 1.0 + */ +struct HdfIoDispatcher { + /** Dispatches a driver service call. service indicates the pointer to the driver service object, id + indicates the command word of the function, data indicates the pointer to the data you want to pass to + the driver, and reply indicates the pointer to the data returned by the driver. */ + int (*Dispatch)(struct HdfObject *service, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply); +}; + +/** + * @brief Defines a driver service object. + * + * @since 1.0 + */ +struct HdfIoService { + /** Base class object */ + struct HdfObject object; + /** Pointer to the bound service entity, which is used for framework management. You can ignore it. */ + struct HdfObject *target; + /** Service call dispatcher */ + struct HdfIoDispatcher *dispatcher; +}; + +/** + * @brief Obtains a driver service object. + * + * @param serviceName Indicates the pointer to the name of the service to obtain. + * @param permission Indicates the permission to create device nodes. The default value 0 can be used + * when this function is called from user space. + * @return Returns the pointer to the driver service object if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct HdfIoService *HdfIoServiceBind(const char *serviceName, mode_t permission); + +/** + * @brief Destroys a specified driver service object to release resources if it is no longer required. + * + * @param service Indicates the pointer to the driver service object to destroy. + * + * @since 1.0 + */ +void HdfIoServiceRecycle(struct HdfIoService *service); + +/** + * @brief Registers a custom {@link HdfDevEventlistener} for listening for events reported + * by a specified driver service object. + * + * @param target Indicates the pointer to the driver service object to listen, which is obtained through + * the {@link HdfIoServiceBind} function. + * @param listener Indicates the pointer to the listener to register. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener); + +/** + * @brief Unregisters a previously registered {@link HdfDevEventlistener} to release resources + * if it is no longer required. + * + * @param target Indicates the pointer to the driver service object that has been listened. + * @param listener Indicates the listener object registered by {@link HdfDeviceRegisterEventListener}. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfDeviceUnregisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_IO_SERVICE_IF_H */ +/** @} */ diff --git a/include/core/hdf_object.h b/include/core/hdf_object.h new file mode 100755 index 00000000..af028d27 --- /dev/null +++ b/include/core/hdf_object.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup Core + * @{ + * + * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * + * The HDF implements driver framework capabilities such as driver loading, service management, + * and driver message model. You can develop drivers based on the HDF. + * + * @since 1.0 + */ + +/** + * @file hdf_object.h + * + * @brief Declares the base object provided by the HDF for the driver. + * + * @since 1.0 + */ + +#ifndef HDF_OBJECT_H +#define HDF_OBJECT_H + +#include + +/** + * @brief Describes base class objects defined by the HDF. + * + * @since 1.0 + */ +struct HdfObject { + int32_t objectId; /**< Base object ID */ +}; + +#endif /* HDF_OBJECT_H */ +/** @} */ diff --git a/include/net/hdf_netbuf.h b/include/net/hdf_netbuf.h new file mode 100755 index 00000000..cd7b24e6 --- /dev/null +++ b/include/net/hdf_netbuf.h @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_netbuf.h + * + * @brief Declares network data buffers and provides APIs for operating buffer queues. + * + * This file describes the following network data operations for network device driver development: \n + * + * Applying for, releasing, and moving a network data buffer + * Initializing a network data buffer queue, placing a network data buffer to a queue, and removing a network data + * buffer from a queue + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_NETBUF_H +#define HDF_NETBUF_H + +#include "los_spinlock.h" +#include "hdf_dlist.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates the segments of a network data buffer. + * + * The entire network data buffer is divided into three segments: a header, data, and a tail. + * The header and tail are used to extend both ends of the data segment. + * + * @since 1.0 + */ +enum { + E_HEAD_BUF, /**< Header buffer segment */ + E_DATA_BUF, /**< Data segment */ + E_TAIL_BUF, /**< Tail buffer segment */ + MAX_BUF_NUM /**< Maximum number of buffer segments */ +}; + +struct BufField { + uint32_t offset; + uint32_t len; +}; + +/** + * @brief Defines the reserved field of a network data buffer used to store private information. + * + * The length of the reserved field is 68 bytes. + */ +#define MAX_NETBUF_RESEVER_SIZE 68 + +/** + * @brief Records and saves a network data buffer. + * + * This structure is used to transmit network data between the protocol stack and network driver. + * + * @since 1.0 + */ +struct NetBuf { + struct DListHead dlist; /**< Doubly linked list. Generally, multiple network data buffers are + linked by using a doubly linked list. */ + struct BufField bufs[MAX_BUF_NUM]; /**< Defines buffer segments used to record the offset address + (based on the memory buffer address) and length of each buffer segment, + including the header buffer segment, data segment, and tail buffer segment. + For details, see {@link MAX_BUF_NUM}. */ + uint8_t *mem; /**< Memory buffer address */ + uint32_t len; /**< Length of the memory buffer */ + uint32_t dataLen; /**< Actual data length of the network data buffer */ + void *dev; /**< Network device that receives the network data */ + uint32_t qmap; /**< Queue mappings of the network data buffer */ + uint8_t rsv[MAX_NETBUF_RESEVER_SIZE]; /**< Reserved field. For details, see {@link MAX_NETBUF_RESEVER_SIZE}. */ +}; + +/** + * @brief Indicates the queues for storing network data. + * + * Queues can be used to process multiple pieces of network data in a centralized manner, improving efficiency. + * + * @since 1.0 + */ +struct NetBufQueue { + struct DListHead dlist; /**< Doubly linked list. Generally, multiple network data buffers are linked + by using a doubly linked list. */ + uint32_t size; /**< Number of network data buffers in the queue */ + struct Spinlock lock; /**< Queue operation lock */ +}; + +/** + * @brief Initializes a network data buffer queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @since 1.0 + */ +static inline void NetBufQueueInit(struct NetBufQueue *q) +{ + DListHeadInit(&q->dlist); + LOS_SpinInit(&q->lock); + q->size = 0; +} + +/** + * @brief Obtains the size of a network data buffer queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns the size of the network data buffer queue. + * + * @since 1.0 + */ +static inline uint32_t NetBufQueueSize(const struct NetBufQueue *q) +{ + return q->size; +} + +/** + * @brief Checks whether the network data buffer queue is empty. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns true if the queue is empty; returns false otherwise. + * + * @since 1.0 + */ +static inline bool NetBufQueueIsEmpty(const struct NetBufQueue *q) +{ + return DListIsEmpty(&q->dlist); +} + +/** + * @brief Adds a network data buffer to the tail of a queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * @param nb Indicates the pointer to the network data buffer. + * + * @since 1.0 + */ +void NetBufQueueEnqueue(struct NetBufQueue *q, struct NetBuf *nb); + +/** + * @brief Adds a network data buffer to the header of a queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * @param nb Indicates the pointer to the network data buffer. + * + * @since 1.0 + */ +void NetBufQueueEnqueueHead(struct NetBufQueue *q, struct NetBuf *nb); + +/** + * @brief Obtains a network data buffer from the header of a queue and deletes it from the queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns the pointer to the first network data buffer if the queue is not empty; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct NetBuf *NetBufQueueDequeue(struct NetBufQueue *q); + +/** + * @brief Obtains a network data buffer from the tail of a queue and deletes it from the queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns the pointer to the last network data buffer if the queue is not empty; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct NetBuf *NetBufQueueDequeueTail(struct NetBufQueue *q); + +/** + * @brief Obtains the network data buffer from the header of a queue, without deleting it from the queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns the pointer to the first network data buffer if the queue is not empty; + * returns NULL otherwise. + * + * @since 1.0 + */ +static inline struct NetBuf *NetBufQueueAtHead(const struct NetBufQueue *q) +{ + return (DListIsEmpty(&q->dlist)) ? NULL : DLIST_FIRST_ENTRY(&q->dlist, struct NetBuf, dlist); +} + +/** + * @brief Obtains the network data buffer from the tail of a queue, without deleting it from the queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @return Returns the pointer to the last network data buffer if the queue is not empty; + * returns NULL otherwise. + * + * @since 1.0 + */ +static inline struct NetBuf *NetBufQueueAtTail(const struct NetBufQueue *q) +{ + return (DListIsEmpty(&q->dlist)) ? NULL : DLIST_LAST_ENTRY(&q->dlist, struct NetBuf, dlist); +} + +/** + * @brief Clears a network data buffer queue and releases the network data buffer in the queue. + * + * @param q Indicates the pointer to the network data buffer queue. + * + * @since 1.0 + */ +void NetBufQueueClear(struct NetBufQueue *q); + +/** + * @brief Moves all network data buffers from one queue to another and clears the source queue. + * + * @param q Indicates the pointer to the target network data buffer queue. + * @param add Indicates the pointer to the source network data buffer queue. + * + * @since 1.0 + */ +void NetBufQueueConcat(struct NetBufQueue *q, struct NetBufQueue *add); + +struct NetDevice; + +/** + * @brief Applies for a network data buffer. + * + * @param size Indicates the size of the network data buffer. + * + * @return Returns the pointer to the network data buffer if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct NetBuf *NetBufAlloc(uint32_t size); + +/** + * @brief Releases a network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * + * @since 1.0 + */ +void NetBufFree(struct NetBuf *nb); + +/** + * @brief Applies for a network data buffer based on the reserved space and requested size set by a network device. + * + * @param dev Indicates the pointer to the network device. + * @param size Indicates the size of the network data buffer applied. + * + * @return Returns the pointer to the network data buffer if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size); + +/** + * @brief Performs operations based on the segment ID of a network data buffer. + * The function is opposite to that of {@link NetBufPop}. + * + * Description: + * ID Type | Result + * -------|--------- + * E_HEAD_BUF | The length of the header buffer segment is increased and the length of the data segment is reduced. + * E_DATA_BUF | The length of the data segment is increased and the length of the tail buffer segment is reduced. + * E_TAIL_BUF | The length of the tail buffer segment is increased and the length of the data segment is reduced. + * + * @param nb Indicates the pointer to the network data buffer. + * @param id Indicates the buffer segment ID. + * @param len Indicates the operation length. + * + * @return Returns the start address of the data segment if the operation is successful; + * returns NULL if the operation length exceeds the space of a specified buffer segment. + * + * @since 1.0 + */ +void *NetBufPush(struct NetBuf *nb, uint32_t id, uint32_t len); + +/** + * @brief Performs operations based on the segment ID of a network data buffer. + * The function is opposite to that of {@link NetBufPush}. + * + * Description: + * ID Type | Result + * -------|--------- + * E_HEAD_BUF | The length of the header buffer segment is reduced and the length of the data segment is increased. + * E_DATA_BUF| The length of the data segment is reduced and the length of the tail buffer segment is increased. + * E_TAIL_BUF | The length of the tail buffer segment is reduced and the length of the data segment is increased. + * + * @param nb Indicates the pointer to the network data buffer. + * @param id Indicates the buffer segment ID. + * @param len Indicates the operation length. + * + * @return Returns the start address of the data segment if the operation is successful; + * returns NULL if the operation length exceeds the space of a specified buffer segment. + * + * @since 1.0 + */ +void *NetBufPop(struct NetBuf *nb, uint32_t id, uint32_t len); + +/** + * @brief Obtains the address of a specified buffer segment in a network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * @param id Indicates the buffer segment ID. + * + * @return Returns the address of the specified buffer segment if the operation is successful; + * returns NULL if the buffer segment ID is invalid. + * + * @since 1.0 + */ +static inline uint8_t *NetBufGetAddress(const struct NetBuf *nb, uint32_t id) +{ + if (id < MAX_BUF_NUM) { + return (nb->mem + nb->bufs[id].offset); + } + + return NULL; +} + +/** + * @brief Obtains the size of a specified buffer segment space in a network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * @param id Indicates the buffer segment ID. + * + * @return Returns the size of the specified buffer segment space if the operation is successful; + * returns NULL if the buffer segment ID is invalid. + * + * @since 1.0 + */ +static inline uint32_t NetBufGetRoom(const struct NetBuf *nb, uint32_t id) +{ + if (id < MAX_BUF_NUM) { + return nb->bufs[id].len; + } + + return 0; +} + +/** + * @brief Obtains the actual data length of the data segment of a network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * + * @return Returns the actual data length of the data segment. + * + * @since 1.0 + */ +static inline uint32_t NetBufGetDataLen(const struct NetBuf *nb) +{ + return nb->dataLen; +} + +/** + * @brief Adjusts the size of a network data buffer space. + * + * This function is used to apply for a new network data buffer based on the configured reserved space and + * the size of the source network data buffer, and copy the actual data to the new network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * @param head Indicates the size of the header buffer segment reserved. + * @param tail Indicates the size of the tail buffer segment reserved. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + */ +int32_t NetBufResizeRoom(struct NetBuf *nb, uint32_t head, uint32_t tail); + +/** + * @brief Copies data in a network data buffer to another network data buffer. + * + * @param nb Indicates the pointer to the network data buffer. + * @param cnb Indicates the pointer to the target network data buffer. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + */ +uint32_t NetBufConcat(struct NetBuf *nb, struct NetBuf *cnb); + +/** + * @brief Converts the pbuf structure of Lightweight TCP/IP Stack (lwIP) to a network data buffer. + * + * When a network device is specified, the reserved space of the network device will be added to + * the size of the converted network data buffer. + * + * @param netdev Indicates the pointer to the network device. + * @param lwip_buf Indicates the pointer to the data buffer of lwIP. + * + * @return Returns the pointer to the network data buffer if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct NetBuf *Pbuf2NetBuf(const struct NetDevice *netdev, struct pbuf *lwipBuf); + +/** + * @brief Converts a network data buffer to the pbuf structure of Lightweight TCP/IP Stack (lwIP). + * + * @param nb Indicates the pointer to the network data buffer. + * + * @return Returns the pointer to the pbuf structure if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct pbuf *NetBuf2Pbuf(const struct NetBuf *nb); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* HDF_NETBUF_H */ diff --git a/include/osal.h b/include/osal.h new file mode 100755 index 00000000..837354df --- /dev/null +++ b/include/osal.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OSAL_H +#define OSAL_H + +#include "osal/osal_firmware.h" +#include "osal/osal_irq.h" +#include "osal/osal_mem.h" +#include "osal/osal_mutex.h" +#include "osal/osal_sem.h" +#include "osal/osal_spinlock.h" +#include "osal/osal_thread.h" +#include "osal/osal_time.h" +#include "osal/osal_timer.h" +#include "utils/hdf_base.h" +#include "utils/hdf_log.h" +#include "utils/hdf_dlist.h" + +#endif /* OSAL_H */ diff --git a/include/osal/osal_atomic.h b/include/osal/osal_atomic.h new file mode 100755 index 00000000..db472553 --- /dev/null +++ b/include/osal/osal_atomic.h @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_atomic.h + * + * @brief Declares atomic and bit operation interfaces. + * + * This file provides interfaces such as reading and setting an atomic, + * incrementing and decrementing an atomic counter by 1. + * This file also provides interfaces such as checking the bit status of a variable, + * and setting and clearing the bit value of a variable. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef OSAL_ATOMIC_H +#define OSAL_ATOMIC_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes an atomic. + */ +typedef struct { + volatile int32_t counter;/**< Counter (an atomic variable). + * An operation on the atomic is to operate this variable. + */ +} OsalAtomic; + +/** + * @brief Reads the counter of an atomic. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * + * @return Returns the counter. + * @since 1.0 + * @version 1.0 + */ +int32_t OsalAtomicRead(const OsalAtomic *v); + +/** + * @brief Sets the counter for an atomic. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * @param counter Indicates the counter to set. + * + * @since 1.0 + * @version 1.0 + */ +void OsalAtomicSet(OsalAtomic *v, int32_t counter); + +/** + * @brief Increments the counter of an atomic by 1. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * + * @since 1.0 + * @version 1.0 + */ +void OsalAtomicInc(OsalAtomic *v); + +/** + * @brief Decrements the counter of an atomic by 1. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * + * @since 1.0 + * @version 1.0 + */ +void OsalAtomicDec(OsalAtomic *v); + +/** + * @brief Tests the value of a specified bit of a variable. + * + * @param nr Indicates the bit of the variable. The value ranges from 0 to 31. + * @param addr Indicates the pointer to the variable. + * + * @return Returns the bit value. + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTestBit(unsigned long nr, const volatile unsigned long *addr); + +/** + * @brief Sets the value of a specified bit of the variable and returns the bit value before the setting. + * + * @param nr Indicates the bit of the variable. The value ranges from 0 to 31. + * @param addr Indicates the pointer to the variable. + * + * @return Returns the bit value before the setting. + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTestSetBit(unsigned long nr, volatile unsigned long *addr); + +/** + * @brief Clears the value of a specified bit of the variable and returns the bit value before clearing. + * + * @param nr Indicates the bit of the variable. The value ranges from 0 to 31. + * @param addr Indicates the pointer to the variable. + * + * @return Returns the bit value before the bit is cleared. + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTestClearBit(unsigned long nr, volatile unsigned long *addr); + +/** + * @brief Clears the value of a specified bit of the variable. + * + * @param nr Indicates the bit of the variable. The value ranges from 0 to 31. + * @param addr Indicates the pointer to the variable. + * + * @since 1.0 + * @version 1.0 + */ +void OsalClearBit(unsigned long nr, volatile unsigned long *addr); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_ATOMIC_H */ +/** @} */ diff --git a/include/osal/osal_file.h b/include/osal/osal_file.h new file mode 100755 index 00000000..0601b391 --- /dev/null +++ b/include/osal/osal_file.h @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_file.h + * + * @brief Declares the file structures and interfaces. + * + * This file provides interfaces for opening, closing, reading, and writing a file, and setting the read/write offset. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef OSAL_FILE_H +#define OSAL_FILE_H + +#include "hdf_base.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Opens a file in read-only mode. + */ +#define OSAL_O_RD_ONLY 0 +/** + * @brief Opens a file in write-only mode. + */ +#define OSAL_O_WR_ONLY 1 +/** + * @brief Opens a file in read and write mode. + */ +#define OSAL_O_RDWR 2 + +/** + * @brief Defines the read permission for the owner. + */ +#define OSAL_S_IREAD 00400 +/** + * @brief Defines the write permission for the owner. + */ +#define OSAL_S_IWRITE 00200 +/** + * @brief Defines the execution permission for the owner. + */ +#define OSAL_S_IEXEC 00100 + +/** + * @brief Defines the read permission for the group. + */ +#define OSAL_S_IRGRP 00040 +/** + * @brief Defines the write permission for the group. + */ +#define OSAL_S_IWGRP 00020 +/** + * @brief Defines the execution permission for the group. + */ +#define OSAL_S_IXGRP 00010 + +/** + * @brief Defines the read permission for others. + */ +#define OSAL_S_IROTH 00004 +/** + * @brief Defines the write permission for others. + */ +#define OSAL_S_IWOTH 00002 +/** + * @brief Defines the execution permission for others. + */ +#define OSAL_S_IXOTH 00001 + +/** + * @brief Defines the offset from the file header. + */ +#define OSAL_SEEK_SET 0 +/** + * @brief Defines the offset from the current position. + */ +#define OSAL_SEEK_CUR 1 +/** + * @brief Defines the offset from the end of the file. + */ +#define OSAL_SEEK_END 2 + +/** + * @brief Declares a file type. + */ +typedef struct { + void *realFile; /**< Pointer to a file object to access */ +} OsalFile; + +/** + * @brief Opens a file. + * + * @param file Indicates the pointer to the file type {@link OsalFile}. + * @param path Indicates the pointer to the name of the file to open. + * @param flags Indicates the mode of opening the file. For details, see {@link OSAL_O_RD_ONLY}. + * @param rights Indicates the permissions required for opening the file. For details, see {@link OSAL_S_IREAD}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to open the file. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalFileOpen(OsalFile *file, const char *path, int flags, uint32_t rights); + +/** + * @brief Writes a file. + * + * @param file Indicates the pointer to the file type {@link OsalFile}. + * @param string Indicates the pointer to the content to write. + * @param length Indicates the length of the content to write. + * + * @return Returns a value listed below: \n + * ssize_t | Description + * -----------------------------------------| ----------------------- + * Greater than 0 | The length of the file content is successfully written. + * HDF_FAILURE {@link HDF_STATUS} | Failed to invoke the system function to write the file. + * HDF_ERR_INVALID_PARAM {@link HDF_STATUS} | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +ssize_t OsalFileWrite(OsalFile *file, const void *string, uint32_t length); + +/** + * @brief Closes a file. + * + * @param file Indicates the pointer to the file type {@link OsalFile}. + * + * @since 1.0 + * @version 1.0 + */ +void OsalFileClose(OsalFile *file); + +/** + * @brief Reads a file. + * + * @param file Indicates the pointer to the file type {@link OsalFile}. + * @param buf Indicates the pointer to the buffer for storing the content to read. + * @param length Indicates the length of the content to read. + * + * @return Returns a value listed below: \n + * ssize_t | Description + * -----------------------------------------| ----------------------- + * Greater than 0 | The length of the file content is successfully read. + * HDF_FAILURE {@link HDF_STATUS} | Failed to invoke the system function to read the file. + * HDF_ERR_INVALID_PARAM {@link HDF_STATUS} | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +ssize_t OsalFileRead(OsalFile *file, void *buf, uint32_t length); + +/** + * @brief Sets the file read/write offset. + * + * @param file Indicates the pointer to the file type {@link OsalFile}. + * @param offset Indicates the offset to set. + * @param whence Indicates the position from which the offset is to set. For details, see {@link OSAL_SEEK_SET}. + * + * off_t | Description + * -----------------------------------------| ----------------------- + * Greater than 0 | The offset is set. + * HDF_FAILURE {@link HDF_STATUS} | Failed to invoke the system function to set the file offset. + * HDF_ERR_INVALID_PARAM {@link HDF_STATUS} | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +off_t OsalFileLseek(OsalFile *file, off_t offset, int32_t whence); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_FILE_H */ +/** @} */ diff --git a/include/osal/osal_firmware.h b/include/osal/osal_firmware.h new file mode 100755 index 00000000..7c394cd7 --- /dev/null +++ b/include/osal/osal_firmware.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_firmware.h + * + * @brief Declares firmware structures and interfaces. + * + * This file provides operations such as requesting and reading a firmware file, setting the offset for reading + * a firmware file, and releasing a firmware file. The firmware file can be read in split mode. + * The size of the firmware block to read each time is defined by the macro {@link HDF_FW_BLOCK_SIZE}. + * The firmware file is requested by calling {@link OsalRequestFirmware}, the firmware block is read from + * the firmware file by calling {@link OsalReadFirmware}, and the firmware block can also be randomly read + * at a specified position by calling {@link OsalSeekFirmware}. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef OSAL_FIRMWARE_H +#define OSAL_FIRMWARE_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Defines the data structure for operating a firmware file. + */ +struct OsalFirmware { + uint32_t fwSize; /**< Firmware file size, which is returned by calling {@link OsalRequestFirmware}. */ + void *para; /**< Pointer to a firmware file, which is returned by calling {@link OsalRequestFirmware}. + * You do not need to allocate space. + */ +}; + +/** + * @brief Defines the data structure for reading a firmware file. + * + * This structure declares the firmware block to read each time. The firmware file can be read in split mode. + */ +struct OsalFwBlock { + uint8_t *data; /**< Firmware content read this time. You do not need to allocate space. */ + bool endFlag; /**< Whether the firmware file is read completely */ + uint32_t dataSize; /**< Firmware block size read this time */ + int32_t curOffset; /**< Offset in the firmware file */ +}; + +/** + * @brief Requests a firmware file based on its name and device information. + * + * @param fw Indicates the pointer to the firmware file {@link OsalFirmware}, which cannot be empty. + * @param fwName Indicates the pointer to the firmware file name, which cannot be empty. + * @param device Indicates the pointer to the information about the device that requests the firmware file. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalRequestFirmware(struct OsalFirmware *fw, const char *fwName, void *device); + +/** + * @brief Reads a firmware file. + * + * @param fw Indicates the pointer to the firmware file {@link OsalFirmware}. + * @param block Indicates the pointer to the firmware block to read. For details, see {@link OsalFwBlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSeekFirmware(struct OsalFirmware *fw, uint32_t offset); + +/** + * @brief Releases a firmware file. + * + * After the firmware file is read, this function is called to release the firmware file. + * + * @param fw Indicates the pointer to the firmware file {@link OsalFirmware}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalReadFirmware(struct OsalFirmware *fw, struct OsalFwBlock *block); + +/** + * Release firmware resource + * + * @param : fw Firmware parameter, see detail in OsalFirmware + * block Firmware data block, see detail in hdf_FWBlock + * @return : true or false + */ +int32_t OsalReleaseFirmware(struct OsalFirmware *fw); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_FIRMWARE_H */ +/** @} */ diff --git a/include/osal/osal_io.h b/include/osal/osal_io.h new file mode 100755 index 00000000..916c55ee --- /dev/null +++ b/include/osal/osal_io.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_io.h + * + * @brief Declares I/O interfaces. + * + * This file provides operations, such as reading data from and writing data into an I/O address space, + * remapping an I/O address space to its virtual address space, and unmapping an I/O virtual address + * associated with the physical address. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef OSAL_IO_H +#define OSAL_IO_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Writes one byte of data into an I/O address space. + * + * @param value Indicates the data to write. + * @param address Indicates the address to write. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_WRITEB(value, address) writeb(value, address) +/** + * @brief Writes a short integer into an I/O address space. + * + * @param value Indicates the data to write. + * @param address Indicates the address to write. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_WRITEW(value, address) writew(value, address) +/** + * @brief Writes an integer into an I/O address space. + * + * @param value Indicates the data to write. + * @param address Indicates the address to write. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_WRITEL(value, address) writel(value, address) + +/** + * @brief Reads one byte of data from an I/O address space. + * + * @param address Indicates the address to read. + * @return Returns the byte. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_READB(address) readb(address) +/** + * @brief Reads a short integer from an I/O address space. + * + * @param address Indicates the address to read. + * @return Returns the short integer. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_READW(address) readw(address) +/** + * @brief Reads an integer from an I/O address space. + * + * @param address Indicates the address to read. + * @return Returns the integer. + * + * @since 1.0 + * @version 1.0 + */ +#define OSAL_READL(address) readl(address) + +/** + * @brief Remaps an I/O physical address to its virtual address. + * + * @param phys_addr Indicates the I/O physical address. + * @param size Indicates the size of the physical address to remap. + * @return Returns the virtual address. + * + * @since 1.0 + * @version 1.0 + */ +static inline void *OsalIoRemap(unsigned long phys_addr, unsigned long size) +{ + return ioremap(phys_addr, size); +} + +/** + * @brief Unmaps an I/O virtual address associated with the physical address. + * + * The virtual address is the one returned by calling {@link OsalIoRemap}. + * + * @param addr Indicates the pointer to the virtual address to unmap. + * + * @since 1.0 + * @version 1.0 + */ +static inline void OsalIoUnmap(void *addr) +{ + iounmap(addr); +} + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_IO_H */ +/** @} */ diff --git a/include/osal/osal_irq.h b/include/osal/osal_irq.h new file mode 100755 index 00000000..f0eb190c --- /dev/null +++ b/include/osal/osal_irq.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_irq.h + * + * @brief Declares interrupt request (IRQ) interfaces and common IRQ trigger modes. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef OSAL_IRQ_H +#define OSAL_IRQ_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Enumerates interrupt trigger modes. + * + * @since 1.1 + */ +typedef enum { + OSAL_IRQF_TRIGGER_NONE = 0, /**< Edge-triggered is not set */ + OSAL_IRQF_TRIGGER_RISING = 1, /**< Rising edge triggered */ + OSAL_IRQF_TRIGGER_FALLING = 2, /**< Failing edge triggered */ + OSAL_IRQF_TRIGGER_HIGH = 4, /**< High-level triggered */ + OSAL_IRQF_TRIGGER_LOW = 8, /**< Low-level triggered */ +} OSAL_IRQ_TRIGGER_MODE; + +/** + * @brief Defines an IRQ type. + */ +typedef uint32_t (*OsalIRQHandle)(uint32_t irqId, void *dev); + +/** + * @brief Registers an IRQ. + * + * @param irqId Indicates the IRQ ID. + * @param config Indicates the interrupt trigger mode. For details, see {@link OSAL_IRQ_TRIGGER_MODE}. + * @param handle Indicates the interrupt processing function. + * @param name Indicates the pointer to the device name for registering an IRQ. + * @param dev Indicates the pointer to the parameter passed to the interrupt processing function. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to register the IRQ. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalRegisterIrq(uint32_t irqId, uint32_t config, OsalIRQHandle handle, const char *name, void *dev); + +/** + * @brief Unregisters an IRQ. + * + * @param irqId Indicates the IRQ ID. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to unregister the IRQ. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalUnregisterIrq(uint32_t irqId); + +/** + * @brief Enables an IRQ. + * + * @param irqId Indicates the IRQ ID. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalEnableIrq(uint32_t irqId); + +/** + * @brief Disables an IRQ. + * + * @param irqId Indicates the IRQ ID. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalDisableIrq(uint32_t irqId); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_IRQ_H */ +/** @} */ diff --git a/include/osal/osal_mem.h b/include/osal/osal_mem.h new file mode 100755 index 00000000..f9516d63 --- /dev/null +++ b/include/osal/osal_mem.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_mem.h + * + * @brief Declares the driver memory request and release interfaces. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_MEM_H +#define OSAL_MEM_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Allocates memory of a specified size. + * + * @param size Indicates the size of memory to allocate. + * + * @return Returns the pointer to the allocated memory if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ +void *OsalMemAlloc(size_t size); + +/** + * @brief Allocates memory of a specified size, and clears the allocated memory. + * + * @param size Indicates the size of memory to allocate. + * + * @return Returns the pointer to the allocated memory if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ +void *OsalMemCalloc(size_t size); + +/** + * @brief Allocates memory of a specified size, and aligns the memory address on a given boundary. + * + * @param alignment Indicates the memory boundary alignment. The value must be a power of 2. + * @param size Indicates the size of memory to allocate. + * + * @return Returns the pointer to the allocated memory if the operation is successful; returns NULL otherwise. + * @since 1.0 + * @version 1.0 + */ +void *OsalMemAllocAlign(size_t alignment, size_t size); + +/** + * @brief Releases memory. + * + * @param mem Indicates the pointer to the memory to release. + * @since 1.0 + * @version 1.0 + */ +void OsalMemFree(void *mem); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_MEM_H */ +/** @} */ diff --git a/include/osal/osal_mutex.h b/include/osal/osal_mutex.h new file mode 100755 index 00000000..65d4a48a --- /dev/null +++ b/include/osal/osal_mutex.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_mutex.h + * + * @brief Declares mutex types and interfaces. + * + * This file provides interfaces for initializing and destroying a mutex, locking a mutex, + * locking a mutex upon timeout, and unlocking a mutex. The mutex must be destroyed after being used. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_MUTEX_H +#define OSAL_MUTEX_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a mutex. + */ +struct OsalMutex { + void *realMutex; /**< Pointer to a mutex object to operate */ +}; + +/** + * @brief Defines a mutex. + */ +#define OSAL_DECLARE_MUTEX(mutex) struct OsalMutex mutex + +/** + * @brief Initializes a mutex. + * + * @param mutex Indicates the pointer to the mutex {@link OsalMutex}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to initialize the mutex. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalMutexInit(struct OsalMutex *mutex); + +/** + * @brief Destroys a mutex. + * + * @param mutex Indicates the pointer to the mutex {@link OsalMutex}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to destroy the mutex. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalMutexDestroy(struct OsalMutex *mutex); + +/** + * @brief Locks a mutex. + * + * @param mutex Indicates the pointer to the mutex {@link OsalMutex}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to lock the mutex. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalMutexLock(struct OsalMutex *mutex); + +/** + * @brief Locks a mutex with a specified timeout duration. + * + * @param mutex Indicates the pointer to the mutex {@link OsalMutex}. + * @param ms Indicates the timeout duration, in milliseconds. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to lock the mutex. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_TIMEOUT | Timeout occurs. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalMutexTimedLock(struct OsalMutex *mutex, uint32_t ms); + +/** + * @brief Unlocks a mutex. + * + * @param mutex Indicates the pointer to the mutex {@link OsalMutex}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to unlock the mutex. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalMutexUnlock(struct OsalMutex *mutex); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_MUTEX_H */ +/** @} */ diff --git a/include/osal/osal_sem.h b/include/osal/osal_sem.h new file mode 100755 index 00000000..fe59a08b --- /dev/null +++ b/include/osal/osal_sem.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_sem.h + * + * @brief Declares semaphore structures and interfaces. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_SEM_H +#define OSAL_SEM_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a semaphore. + */ +struct OsalSem { + void *realSemaphore; /**< Pointer to a semaphore to operate */ +}; + +/** + * @brief Defines a semaphore. + */ +#define OSAL_DECLARE_SEMAPHORE(sem) struct OsalSem sem + +/** + * @brief Initializes a semaphore. + * + * @param sem Indicates the pointer to the semaphore {@link OsalSem}. + * @param value Indicates the initial value of the semaphore. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to initialize the semaphore. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSemInit(struct OsalSem *sem, uint32_t value); + +/** + * @brief Waits for a semaphore. + * + * @param sem Indicates the pointer to the semaphore {@link OsalSem}. + * @param ms Indicates the timeout interval. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to wait for the semaphore. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_TIMEOUT | Timeout occurs. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSemWait(struct OsalSem *sem, uint32_t ms); + +/** + * @brief Releases a semaphore. + * + * @param sem Indicates the pointer to the semaphore {@link OsalSem}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to release the semaphore. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSemPost(struct OsalSem *sem); + +/** + * @brief Destroys a semaphore. + * + * @param sem Indicates the pointer to the semaphore {@link OsalSem}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to destroy the semaphore. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSemDestroy(struct OsalSem *sem); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_SEM_H */ +/** @} */ diff --git a/include/osal/osal_spinlock.h b/include/osal/osal_spinlock.h new file mode 100755 index 00000000..a7c7a6f2 --- /dev/null +++ b/include/osal/osal_spinlock.h @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_spinlock.h + * + * @brief Declares spinlock types and interfaces. + * + * This file provides the interfaces for initializing, destroying, obtaining, and releasing a spinlock, + * the interfaces for obtaining a spinlock and disabling the interrupt request (IRQ), releasing a spinlock + * and enabling the IRQ, obtaining a spinlock, disabling the IRQ, and saving its status, and releasing a spinlock, + * enabling the IRQ, and restoring the saved IRQ status. The spinlock needs to be destroyed when it is no longer used. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_SPINLOCK_H +#define OSAL_SPINLOCK_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a spinlock. + */ +typedef struct { + void *realSpinlock; /**< Pointer to a spinlock */ +} OsalSpinlock; + +/** + * @brief Defines a spinlock. + */ +#define OSAL_DECLARE_SPINLOCK(spinlock) OsalSpinlock spinlock + +/** + * @brief Initializes a spinlock. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to initialize the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinInit(OsalSpinlock *spinlock); + +/** + * @brief Destroys a spinlock. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to destroy the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinDestroy(OsalSpinlock *spinlock); + +/** + * @brief Obtains a spinlock. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to obtain the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinLock(OsalSpinlock *spinlock); + +/** + * @brief Releases a spinlock. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to release the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinUnlock(OsalSpinlock *spinlock); + +/** + * @brief Obtains a spinlock and disables the IRQ. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to obtain the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinLockIrq(OsalSpinlock *spinlock); + +/** + * @brief Releases a spinlock and enables the IRQ. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to release the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinUnlockIrq(OsalSpinlock *spinlock); + +/** + * @brief Obtains a spinlock, disables the IRQ, and saves its status. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * @param flags Indicates the pointer to the status of the IRQ register. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to obtain the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinLockIrqSave(OsalSpinlock *spinlock, uint32_t *flags); + +/** + * @brief Releases a spinlock, enables the IRQ, and restores the saved IRQ status. + * + * @param spinlock Indicates the pointer to the spinlock {@link OsalSpinlock}. + * @param flags Indicates the pointer to the value used to restore the IRQ register. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to release the spinlock. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalSpinUnlockIrqRestore(OsalSpinlock *spinlock, uint32_t *flags); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_SPINLOCK_H */ +/** @} */ diff --git a/include/osal/osal_thread.h b/include/osal/osal_thread.h new file mode 100755 index 00000000..796d03b4 --- /dev/null +++ b/include/osal/osal_thread.h @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_thread.h + * + * @brief Declares thread types and interfaces. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_THREAD_H +#define OSAL_THREAD_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Enumerates thread priorities. + */ +typedef enum { + OSAL_THREAD_PRI_LOW, /**< Low priority */ + OSAL_THREAD_PRI_DEFAULT, /**< Default priority */ + OSAL_THREAD_PRI_HIGH, /**< High priority */ + OSAL_THREAD_PRI_HIGHEST /**< Highest priority */ +} OSAL_THREAD_PRIORITY; + +/** + * @brief Describes thread parameters. + */ +struct OsalThreadParam { + char *name; /**< Thread name */ + size_t stackSize; /**< Stack size of a thread */ + OSAL_THREAD_PRIORITY priority; /**< Thread priority */ +}; + +/** + * @brief Defines a thread callback function type. + */ +typedef int (*OsalThreadEntry)(void *); + +/** + * @brief Describes a thread. + */ +struct OsalThread { + int32_t status; /**< Thread running status */ + void *realThread; /**< Pointer to a created thread object */ +}; + +/** + * @brief Defines a thread macro. + */ +#define OSAL_DECLARE_THREAD(thread) struct OsalThread thread + +/** + * @brief Creates a thread. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @param threadEntry Indicates the thread callback function {@link OsalThreadEntry}. + * @param entryPara Indicates the pointer to the parameter passed to the thread callback function. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalThreadCreate(struct OsalThread *thread, OsalThreadEntry threadEntry, void *entryPara); +/** + * @brief Starts a thread. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @param param Indicates the pointer to the parameter used to start a thread. For details, see {@link OsalThreadParam}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to start the thread. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalThreadStart(struct OsalThread *thread, const struct OsalThreadParam *param); + +/** + * @brief Destroys a thread. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to destroy the thread. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalThreadDestroy(struct OsalThread *thread); + +/** + * @brief Suspends a thread. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to suspend the thread. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalThreadSuspend(struct OsalThread *thread); + +/** + * @brief Resumes a thread. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @since 1.0 + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to resume the thread. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @version 1.0 + */ +int32_t OsalThreadResume(struct OsalThread *thread); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_THREAD_H */ +/** @} */ diff --git a/include/osal/osal_time.h b/include/osal/osal_time.h new file mode 100755 index 00000000..71152dab --- /dev/null +++ b/include/osal/osal_time.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_time.h + * + * @brief Declares the time, sleep, and delay interfaces. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_TIME_H +#define OSAL_TIME_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Defines time. + */ +typedef struct { + uint64_t sec; /**< Second */ + uint64_t usec; /**< Microsecond */ +} OsalTimespec; + +/** + * @brief Describes thread sleep, in seconds. + * + * When a thread invokes this function, the CPU is released and the thread enters the sleep state. + * + * @param sec Indicates the sleep time, in seconds. + * @since 1.0 + * @version 1.0 + */ +void OsalSleep(uint32_t sec); + +/** + * @brief Describes thread sleep, in milliseconds. + * + * When a thread invokes this function, the CPU is released and the thread enters the sleep state. + * + * @param ms Indicates the sleep time, in milliseconds. + * @since 1.0 + * @version 1.0 + */ +void OsalMSleep(uint32_t ms); + +/** + * @brief Obtains the second and microsecond time. + * + * @param time Indicates the pointer to the time structure {@link OsalTimespec}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to obtain time. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalGetTime(OsalTimespec *time); + +/** + * @brief Obtains time difference. + * + * @param start Indicates the pointer to the start time {@link OsalTimespec}. + * @param end Indicates the pointer to the end time {@link OsalTimespec}. + * @param diff Indicates the pointer to the time difference {@link OsalTimespec}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalDiffTime(const OsalTimespec *start, const OsalTimespec *end, OsalTimespec *diff); + +/** + * @brief Obtains the system time. + * + * @return Returns the system time, in milliseconds. + * @since 1.0 + * @version 1.0 + */ +uint64_t OsalGetSysTimeMs(void); + +/** + * @brief Describes thread delay, in milliseconds. + * + * When a thread invokes this function, the CPU is not released. This function returns after waiting for milliseconds. + * + * @param ms Indicates the delay time, in milliseconds. + * @since 1.0 + * @version 1.0 + */ +void OsalMDelay(uint32_t ms); + +/** + * @brief Describes thread delay, in microseconds. + * + * When a thread invokes this function, the CPU is not released. This function returns after waiting for microseconds. + * + * @param us Indicates the delay time, in microseconds. + * @since 1.0 + * @version 1.0 + */ +void OsalUDelay(uint32_t us); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_TIME_H */ +/** @} */ diff --git a/include/osal/osal_timer.h b/include/osal/osal_timer.h new file mode 100755 index 00000000..3adeb79c --- /dev/null +++ b/include/osal/osal_timer.h @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup OSAL + * @{ + * + * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. + * + * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, + * atomic, firmware, and I/O operation modules. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file osal_timer.h + * + * @brief Declares timer types and interfaces. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef OSAL_TIMER_H +#define OSAL_TIMER_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a timer. + */ +typedef struct { + void *realTimer; /**< Pointer to a timer object */ +} OsalTimer; + +/** + * @brief Describes a timer execution function type. + */ +typedef void (*OsalTimerFunc)(uintptr_t arg); + +/** + * @brief Defines a timer macro. + */ +#define OSAL_DECLARE_TIMER(timer) OsalTimer timer + +/** + * @brief Creates a timer. + * + * @param timer Indicates the pointer to the timer {@link OsalTimer}. + * @param interval Indicates the timer interval. + * @param func Indicates the timer execution function {@link OsalTimerFunc}. + * @param arg Indicates the argument passed to the timer execution function. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTimerCreate(OsalTimer *timer, uint32_t interval, OsalTimerFunc func, uintptr_t arg); + +/** + * @brief Deletes a timer. + * + * @param timer Indicates the pointer to the timer {@link OsalTimer}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to delete the timer. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTimerDelete(OsalTimer *timer); + +/** + * @brief Starts a timer. + * + * @param timer Indicates the pointer to the timer {@link OsalTimer}. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to start the timer. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTimerStartOnce(OsalTimer *timer); + +/** + * @brief Starts a periodic timer. + * + * @param timer Indicates the pointer to the timer {@link OsalTimer}. + * @param interval Indicates the timer interval, in milliseconds. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function to start the timer. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTimerStartLoop(OsalTimer *timer); + +/** + * @brief Sets the interval of a timer. + * + * @param timer Indicates the pointer to the timer {@link OsalTimer}. + * @param interval Indicates the timer interval, in milliseconds. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_FAILURE | Failed to invoke the system function. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * + * @since 1.0 + * @version 1.0 + */ +int32_t OsalTimerSetTimeout(OsalTimer *timer, uint32_t interval); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_TIMER_H */ +/** @} */ diff --git a/include/platform/gpio_if.h b/include/platform/gpio_if.h new file mode 100755 index 00000000..b6277e46 --- /dev/null +++ b/include/platform/gpio_if.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup GPIO + * @{ + * + * @brief Provides standard general-purpose input/output (GPIO) interfaces for driver development. + * + * You can use this module to perform operations on a GPIO pin, including setting the input/output direction, + * reading/writing the level value, and setting the interrupt service routine (ISR) function. + * + * @since 1.0 + */ + +/** + * @file gpio_if.h + * + * @brief Declares the standard GPIO interface functions. + * + * @since 1.0 + */ + +#ifndef GPIO_IF_H +#define GPIO_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates GPIO level values. + * + * @since 1.0 + */ +enum GpioValue { + GPIO_VAL_LOW = 0, /**< Low GPIO level */ + GPIO_VAL_HIGH = 1, /**< High GPIO level */ + GPIO_VAL_ERR, /**< Invalid GPIO level */ +}; + +/** + * @brief Enumerates GPIO directions. + * + * @since 1.0 + */ +enum GpioDirType { + GPIO_DIR_IN = 0, /**< Input direction */ + GPIO_DIR_OUT = 1, /**< Output direction */ + GPIO_DIR_ERR, /**< Invalid direction */ +}; + +/** + * @brief Defines the function type of a GPIO interrupt service routine (ISR). + * + * This function is used when you call {@link GpioSetIrq} to register the ISR for a GPIO pin. + * + * @param gpio Indicates the GPIO number of the ISR. + * @param data Indicates the pointer to the private data passed to this ISR (The data is specified when the ISR + * is registered). + * + * @return Returns 0 if the ISR function type is successfully defined; returns a negative value otherwise. + * @see GpioSetIrq + * @since 1.0 + */ +typedef int32_t (*GpioIrqFunc)(uint16_t gpio, void *data); + +/** + * @brief Reads the level value of a GPIO pin. + * + * Before using this function, you need to call {@link GpioSetDir} to set the GPIO pin direction to input. + * + * @param gpio Indicates the GPIO pin number. + * @param val Indicates the pointer to the read level value. For details, see {@link GpioValue}. + * + * @return Returns 0 if the GPIO pin level value is successfully read; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioRead(uint16_t gpio, uint16_t *val); + +/** + * @brief Writes the level value for a GPIO pin. + * + * Before using this function, you need to call {@link GpioSetDir} to set the GPIO pin direction to output. + * + * @param gpio Indicates the GPIO pin number. + * @param val Indicates the level value to be written. For details, see {@link GpioValue}. + * + * @return Returns 0 if the GPIO pin level value is successfully written; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioWrite(uint16_t gpio, uint16_t val); + +/** + * @brief Sets the input/output direction for a GPIO pin. + * + * Generally, you can set the direction to input when external level signals need to be read, and set the + * direction to output when the level signals need to be sent externally. + * + * @param gpio Indicates the GPIO pin number. + * @param dir Indicates the direction to set. For details, see {@link GpioDirType}. + * + * @return Returns 0 if the GPIO pin direction is successfully set; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioSetDir(uint16_t gpio, uint16_t dir); + +/** + * @brief Obtains the input/output direction of a GPIO pin. + * + * @param gpio Indicates the GPIO pin number. + * @param dir Indicates the pointer to the obtained input/output direction. For details, see {@link GpioDirType}. + * + * @return Returns 0 if the GPIO pin direction is successfully obtained; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioGetDir(uint16_t gpio, uint16_t *dir); + +/** + * @brief Sets the ISR function for a GPIO pin. + * + * Before using a GPIO pin as an interrupt, you must call this function to set an ISR function for this GPIO pin, + * including the ISR parameters and the interrupt trigger mode. + * After the setting is successful, you also need to call {@link GpioEnableIrq} to enable the interrupt, so that + * the ISR function can respond correctly. + * + * @param gpio Indicates the GPIO pin number. + * @param mode Indicates the interrupt trigger mode. For details, see {@link OSAL_IRQF_TRIGGER_RISING}. + * @param func Indicates the ISR function to set, which is specified by {@link GpioIrqFunc}. + * @param arg Indicates the pointer to the parameters passed to the ISR function. + * + * @return Returns 0 if the ISR function of the GPIO pin is successfully set; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); + +/** + * @brief Cancels the setting of the ISR function for a GPIO pin. + * + * If you do not need the GPIO pin as an interrupt, call this function to cancel the ISR function set via + * {@link GpioSetIrq}. Since this ISR function is no longer valid, you are advised to use {@link GpioDisableIrq} to + * disable the GPIO pin interrupt. + * + * @param gpio Indicates the GPIO pin number. + * + * @return Returns 0 if the ISR function of the GPIO pin is successfully cancelled; returns a negative value + * otherwise. + * @since 1.0 + */ +int32_t GpioUnSetIrq(uint16_t gpio); + +/** + * @brief Enables a GPIO pin interrupt. + * + * Before enabling the interrupt, you must call {@link GpioSetIrq} to set the ISR function for the GPIO pin. + * + * @param gpio Indicates the GPIO pin number. + * + * @return Returns 0 if the GPIO pin interrupt is successfully enabled; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioEnableIrq(uint16_t gpio); + +/** + * @brief Disables a GPIO pin interrupt. + * + * You can call this function when you need to temporarily mask a GPIO pin interrupt or cancel an ISR function. + * + * @param gpio Indicates the GPIO pin number. + * + * @return Returns 0 if the GPIO pin interrupt is successfully disabled; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioDisableIrq(uint16_t gpio); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* GPIO_IF_H */ +/** @} */ diff --git a/include/platform/hdf_platform.h b/include/platform/hdf_platform.h new file mode 100755 index 00000000..040e5afe --- /dev/null +++ b/include/platform/hdf_platform.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup COMMON + * @{ + * + * @brief Provides common APIs of the platform driver. + * + * This module also provides DevHandle, which represents the common data structure of the platform driver. + * + * @since 1.0 + */ + +/** + * @file hdf_platform.h + * + * @brief Declares common APIs of the platform driver. + * + * @since 1.0 + */ + +#ifndef HDF_PLATFORM_H +#define HDF_PLATFORM_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Defines the common device handle of the platform driver. + * + * The handle is associated with a specific platform device and is used as the + * first input parameter for all APIs of the platform driver. + * + * @since 1.0 + */ +struct DevHandle { + /** Pointer to a specific platform device */ + void *object; +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* HDF_PLATFORM_H */ +/** @} */ diff --git a/include/platform/i2c_if.h b/include/platform/i2c_if.h new file mode 100755 index 00000000..a78c518a --- /dev/null +++ b/include/platform/i2c_if.h @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup I2C + * @{ + * + * @brief Provides standard Inter-Integrated Circuit (I2C) interfaces. + * + * This module allows a driver to perform operations on an I2C controller for accessing devices on the I2C bus, + * including creating and destroying I2C controller handles as well as reading and writing data. + * + * @since 1.0 + */ + +/** + * @file i2c_if.h + * + * @brief Declares the standard I2C interface functions. + * + * @since 1.0 + */ + +#ifndef I2C_IF_H +#define I2C_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Defines the I2C transfer message used during custom transfers. + * + * @attention This structure does not limit the data transfer length specified by len. + * The specific I2C controller determines the maximum length allowed. \n + * The device address addr indicates the original device address and does not need to + * contain the read/write flag bit. + * + * @since 1.0 + */ +struct I2cMsg { + /** Address of the I2C device */ + uint16_t addr; + /** Address of the buffer for storing transferred data */ + uint8_t *buf; + /** Length of the transferred data */ + uint16_t len; + /** + * Transfer Mode Flag | Description + * ------------| ----------------------- + * I2C_FLAG_READ | Read flag + * I2C_FLAG_ADDR_10BIT | 10-bit addressing flag + * I2C_FLAG_READ_NO_ACK | No-ACK read flag + * I2C_FLAG_IGNORE_NO_ACK | Ignoring no-ACK flag + * I2C_FLAG_NO_START | No START condition flag + * I2C_FLAG_STOP | STOP condition flag + */ + uint16_t flags; +}; + +/** + * @brief Enumerates flags used for transferring I2C messages. + * + * Multiple flags can be used to jointly control a single I2C message transfer. + * If a bit is set to 1, the corresponding feature is enabled. If a bit is set to 0, + * the corresponding feature is disabled. + * + * @since 1.0 + */ +enum I2cFlag { + /** Read flag. The value 1 indicates the read operation, and 0 indicates the write operation. */ + I2C_FLAG_READ = (0x1 << 0), + /** 10-bit addressing flag. The value 1 indicates that a 10-bit address is used. */ + I2C_FLAG_ADDR_10BIT = (0x1 << 4), + /** Non-ACK read flag. The value 1 indicates that no ACK signal is sent during the read process. */ + I2C_FLAG_READ_NO_ACK = (0x1 << 11), + /** Ignoring no-ACK flag. The value 1 indicates that the non-ACK signal is ignored. */ + I2C_FLAG_IGNORE_NO_ACK = (0x1 << 12), + /** + * No START condition flag. The value 1 indicates that there is no START condition for the message + * transfer. + */ + I2C_FLAG_NO_START = (0x1 << 14), + /** STOP condition flag. The value 1 indicates that the current transfer ends with a STOP condition. */ + I2C_FLAG_STOP = (0x1 << 15), +}; + +/** + * @brief Obtains the handle of an I2C controller. + * + * You must call this function before accessing the I2C bus. + * + * @param number Indicates the I2C controller ID. + * + * @return Returns the pointer to the {@link DevHandle} of the I2C controller if the operation is successful; + * returns NULL otherwise. + * @since 1.0 + */ +struct DevHandle *I2cOpen(int16_t number); + + /** + * @brief Releases the handle of an I2C controller. + * + * If you no longer need to access the I2C controller, you should call this function to close its handle so as + * to release unused memory resources. + * + * @param handle Indicates the pointer to the device handle of the I2C controller. + * + * @since 1.0 + */ +void I2cClose(struct DevHandle *handle); + +/** + * @brief Launches a custom transfer to an I2C device. + * + * @param handle Indicates the pointer to the device handle of the I2C controller obtained via {@link I2cOpen}. + * @param msgs Indicates the pointer to the I2C transfer message structure array. + * @param count Indicates the length of the message structure array. + * + * @return Returns the number of transferred message structures if the operation is successful; + * returns a negative value otherwise. + * @see I2cMsg + * @attention This function does not limit the number of message structures specified by count or the data + * length of each message structure. The specific I2C controller determines the maximum number and data length allowed. + * + * @since 1.0 + */ +int32_t I2cTransfer(struct DevHandle *handle, struct I2cMsg *msgs, int16_t count); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* I2C_IF_H */ +/** @} */ diff --git a/include/platform/rtc_if.h b/include/platform/rtc_if.h new file mode 100755 index 00000000..b73a433f --- /dev/null +++ b/include/platform/rtc_if.h @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup RTC + * @{ + * + * @brief Provides standard real-time clock (RTC) APIs. + * + * These APIs allow you to perform operations such as reading or writing system time, reading or writing alarm time, + * setting alarm interrupts, registering alarm callbacks, setting the external frequency, resetting the RTC driver, + * and customizing RTC configurations. \n + * The RTC driver provides precise real time for the operating system (OS). If the OS is powered off, the RTC driver + * continues to keep track of the system time using an external battery. + * + * @since 1.0 + */ + +/** + * @file rtc_if.h + * + * @brief Declares the standard RTC APIs. + * + * @since 1.0 + */ + +#ifndef RTC_IF_H +#define RTC_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates alarm indexes. + * + * The alarm indexes will be used when you perform operations related to alarms. + * + * @since V1.0 + */ +enum RtcAlarmIndex { + RTC_ALARM_INDEX_A = 0, /**< Index of alarm A */ + RTC_ALARM_INDEX_B = 1, /**< Index of alarm B */ +}; + +/** + * @brief Defines a callback that will be invoked when an alarm is generated at the specified time. + * + */ +typedef int32_t (*RtcAlarmCallback)(enum RtcAlarmIndex); + +/** + * @brief Defines the RTC information. + * + * The RTC information includes the year, month, day, day of the week, hour, minute, second, and millisecond. + * The start time is 1970/01/01 Thursday 00:00:00 (UTC). + */ +struct RtcTime { + uint8_t second; /**< Second. The value ranges from 0 to 59. */ + uint8_t minute; /**< Minute. The value ranges from 0 to 59. */ + uint8_t hour; /**< Hour. The value ranges from 0 to 23. */ + uint8_t day; /**< Day. The value ranges from 1 to 31. */ + uint8_t weekday; /**< Day of the week. The value ranges from 1 to 7, representing Monday to Sunday. */ + uint8_t month; /**< Month. The value ranges from 1 to 12. */ + uint16_t year; /**< Year. The value is greater than or equal to 1970. */ + uint16_t millisecond; /**< Millisecond. The value ranges from 0 to 990, with a precision of 10 milliseconds. */ +}; + +/** + * @brief Opens the RTC device to obtain its handle. + * + * The OS supports only one RTC device. + * + * @return Returns {@link DevHandle} if the operation is successful; returns NULL if the operation fails. + * @since 1.0 + */ +struct DevHandle *RtcOpen(void); + +/** + * @brief Releases a specified handle of the RTC device. + * + * @param handle Indicates the pointer to the RTC device handle to release, which is created via {@link RtcGetHandle}. + * + * @since 1.0 + */ +void RtcClose(struct DevHandle *handle); + +/** + * @brief Reads time from the RTC driver. + * + * The time information includes the year, month, day, day of the week, hour, minute, second, and millisecond. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param time Indicates the pointer to the time information read from the RTC driver. + * For details, see {@link RtcTime}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcReadTime(struct DevHandle *handle, struct RtcTime *time); + +/** + * @brief Writes format-compliant time to the RTC driver. + * + * Note that the RTC start time is 1970/01/01 Thursday 00:00:00 (UTC). Set the maximum value of year based on + * the requirements specified in the product manual of the in-use component. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param time Indicates the pointer to the time information to write. For details, see {@link RtcTime}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time); + +/** + * @brief Reads the RTC alarm time that was set last time. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param alarmIndex Indicates the RTC alarm index. For details, see {@link RtcAlarmIndex}. + * @param time Indicates the pointer to the RTC alarm time information. For details, see {@link RtcTime}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcReadAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time); + +/** + * @brief Writes the RTC alarm time based on the alarm index. + * + * Note that the RTC start time is 1970/01/01 Thursday 00:00:00 (UTC). Set the maximum value of year based on + * the requirements specified in the product manual of the in-use component. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param alarmIndex Indicates the RTC alarm index. For details, see {@link RtcAlarmIndex}. + * @param tm Indicates the pointer to the RTC alarm time information. For details, see {@link RtcTime}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time); + +/** + * @brief Registers {@link RtcAlarmCallback} that will be invoked when an alarm is generated at the specified time. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param alarmIndex Indicates the RTC alarm index. For details, see {@link RtcAlarmIndex}. + * @param cb Indicates the callback to register. For details, see {@link RtcAlarmCallback}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcRegisterAlarmCallback(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb); + +/** + * @brief Enables or disables alarm interrupts. + * + * Before performing alarm operations, you need to call this function to enable alarm interrupts, + * so that the {@link RtcRegisterAlarmCallback} will be called when the alarm is not generated upon a timeout. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param alarmIndex Indicates the RTC alarm index. For details, see {@link RtcAlarmIndex}. + * @param enable Specifies whether to enable RTC alarm interrupts. The value 1 means to + * enable alarm interrupts and value 0 means to disable alarm interrupts. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcAlarmInterruptEnable(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, uint8_t enable); + +/** + * @brief Reads the RTC external frequency. + * + * This function reads the frequency of the external crystal oscillator connected to the RTC driver. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param freq Indicates the pointer to the frequency of the external crystal oscillator, in Hz. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq); + +/** + * @brief Sets the frequency of the external crystal oscillator connected to the RTC driver. + * + * Note that the frequency must be configured in accordance with the requirements specified in the product manual of + * the in-use component. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param freq Indicates the frequency to set for the external crystal oscillator, in Hz. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcSetFreq(struct DevHandle *handle, uint32_t freq); + +/** + * @brief Resets the RTC driver. + * + * After the reset, the configuration registers are restored to the default values. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcReset(struct DevHandle *handle); + +/** + * @brief Reads the configuration of a custom RTC register based on the register index. + * + * One index corresponds to one byte of the configuration value. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param usrDefIndex Indicates the index of the custom register. + * @param value Indicates the pointer to the configuration value of the specified register index. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcReadReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t *value); + +/** + * @brief Writes the configuration of a custom RTC register based on the register index. + * + * One index corresponds to one byte of the configuration value. + * + * @param handle Indicates the pointer to the RTC device handle, which is obtained via {@link RtcGetHandle}. + * @param usrDefIndex Indicates the index of the custom register. + * @param value Indicates the configuration value to write at the index of the register. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * For details, see {@link HDF_STATUS}. + * @since 1.0 + */ +int32_t RtcWriteReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t value); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* RTC_IF_H */ +/** @} */ + diff --git a/include/platform/sdio_if.h b/include/platform/sdio_if.h new file mode 100755 index 00000000..a26c9e4d --- /dev/null +++ b/include/platform/sdio_if.h @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup SDIO + * @{ + * + * @brief Declares standard APIs of basic secure digital input and output (SDIO) capabilities. + * + * You can use this module to access the SDIO and enable the driver to operate an SDIO-compliant device. + * These capabilities include reading and writing data based on SDIO, setting the block size, + * applying for and releasing interrupts, enabling and disabling devices, and occupying and releasing the bus. + * + * @since 1.0 + */ + + /** + * @file sdio_if.h + * + * @brief Declares the standard SDIO APIs. + * + * @since 1.0 + */ + +#ifndef SDIO_IF_H +#define SDIO_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates SDIO common information types. + * + * When obtaining SDIO common information by calling {@link SdioGetCommonInfo} or setting the information + * by calling {@link SdioSetCommonInfo}, you need to pass the information type. + */ +typedef enum { + SDIO_FUNC_INFO = 0, /**< Functionality information */ + SDIO_OTHER_INFO, /**< Other information */ +} SdioCommonInfoType; + +/** + * @brief Defines the SDIO capabilities. + * + * You can obtain and set the SDIO capabilities by calling {@link SdioGetCommonInfo} and {@link SdioSetCommonInfo} + * with {@link SdioCommonInfo} and {@link SdioCommonInfoType} passed. + */ +typedef struct { + uint32_t maxBlockNum; /**< Maximum number of blocks in a request */ + uint32_t maxBlockSize; /**< Maximum number of bytes in a block. + * The value ranges from 1 to 2048. + */ + uint32_t maxRequestSize; /**< Maximum number of bytes in a request. + * The value ranges from 1 to 2048. + */ + uint32_t enTimeout; /**< Maximum timeout duration, in milliseconds. + * The value cannot exceed 1 second. + */ + uint32_t funcNum; /**< Functionality number, ranging from 1 to 7. */ + uint32_t irqCap; /**< IRQ capabilities */ + void *data; /**< Private data */ +} SdioFuncInfo; + +/** + * @brief Defines SDIO common information. + * + * You can obtain and set common SDIO information by calling {@link SdioGetCommonInfo} and {@link SdioSetCommonInfo} + * with {@link SdioCommonInfo} and {@link SdioCommonInfoType} passed. + */ +typedef union { + SdioFuncInfo funcInfo; /**< Functionality information */ +} SdioCommonInfo; + +/** + * @brief Defines the function type of an SDIO IRQ. + * + * This function is registered when you call {@link SdioClaimIrq} to request the SDIO IRQ. + * + * @param data Indicates the private data passed to this IRQ (The data is specified when the IRQ is registered). + * + * @since 1.0 + */ +typedef void SdioIrqHandler(void *); + +/** + * @brief Opens an SDIO controller with a specified bus number. + * + * Before using the SDIO interface, you can obtain the device handle of the SDIO controller + * by calling {@link SdioOpen}. This function is used in pair with {@link SdioClose}. + * + * @param busNum Indicates the bus number. + * + * @return Returns the device handle {@link DevHandle} of the SDIO controller if the operation is successful; + * returns NULL otherwise. + * @since 1.0 + */ +struct DevHandle *SdioOpen(int16_t busNum); + +/** + * @brief Closes an SDIO controller. + * + * After the SDIO interface is used, you can close the SDIO controller by calling {@link SdioClose}. + * This function is used in pair with {@link SdioOpen}. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller. + * + * @since 1.0 + */ +void SdioClose(struct DevHandle *handle); + +/** + * @brief Incrementally reads a given length of data from the specified SDIO address. + * + * If the length of the data to read is greater than the size of a block, the data is read by block, + * and the remaining data that is smaller than one block is read by byte. Otherwise, data is read by byte. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to read. + * @param addr Indicates the start address of the data to read. + * @param size Indicates the length of the data to read. + * @param timeOut Indicates the timeout duration for reading data, in milliseconds. + * If the value is 0,the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, + uint32_t size, uint32_t timeOut); + +/** + * @brief Incrementally writes a given length of data into the specified SDIO address. + * + * If the length of the data to write is greater than the size of a block, the data is written by block first, + * and the remaining data that is smaller than one block is written by byte. Otherwise, data is written by byte. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to write. + * @param addr Indicates the start address of the data to write. + * @param size Indicates the length of the data to write. + * @param timeOut Indicates the timeout duration for writing data, in milliseconds. + * If the value is 0, the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, + uint32_t size, uint32_t timeOut); + +/** + * @brief Reads a given length of data from the fixed SDIO address. + * + * If the length of the data to read is greater than the size of a block, the data is read by block, + * and the remaining data that is smaller than one block is read by byte. Otherwise, data is read by byte. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to read. + * @param addr Indicates the fixed address of the data to read. + * @param size Indicates the length of the data to read. + * @param timeOut Indicates the timeout duration for reading data, in milliseconds. + * If the value is 0, the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut); + +/** + * @brief Writes a given length of data into the fixed SDIO address. + * + * If the length of the data to write is greater than the size of a block, the data is written by block first, + * and the remaining data that is smaller than one block is written by byte. Otherwise, data is written by byte. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to write. + * @param addr Indicates the fixed address of the data to write. + * @param size Indicates the length of the data to write. + * @param timeOut Indicates the timeout duration for writing data, in milliseconds. + * If the value is 0, the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut); + +/** + * @brief Reads a given length of data from the address space of SDIO function 0. + * + * Currently, only one byte of data can be read. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to read. + * @param addr Indicates the start address of the data to read. + * @param size Indicates the length of the data to read. + * @param timeOut Indicates the timeout duration for reading data, in milliseconds. + * If the value is 0, the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut); + +/** + * @brief Writes a given length of data into the address space of SDIO function 0. + * + * Currently, only one byte of data can be written. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param data Indicates the pointer to the data to write. + * @param addr Indicates the start address of the data to write. + * @param size Indicates the length of the data to write. + * @param timeOut Indicates the timeout duration for writing data, in milliseconds. + * If the value is 0, the default value is used. The default value varies according to the application. + * Generally, the default value is 1 second. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut); + +/** + * @brief Sets the block size. + * + * If data to read or write is performed, use this function to set the block size. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param blockSize Indicates the block size to be set. If the value is 0, the default value is used. + * The value ranges from 1 to 2048 bytes. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioSetBlockSize(struct DevHandle *handle, uint32_t blockSize); + +/** + * @brief Obtains common information. + * + * You can call this function to obtain the capabilities and private data of the I/O function. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param info Indicates the pointer to the common information to be obtained. + * For details, see {@link SdioCommonInfo}. + * @param infoType Indicates the type of the common information to be obtained. + * For details, see {@link SdioCommonInfoType}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType); + +/** + * @brief Sets common information. + * + * You can call this function to set the maximum timeout duration and private data. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param info Indicates the pointer to the common information to be set. + * For details, see {@link SdioCommonInfo}. + * @param infoType Indicates the type of the common information to be set. + * For details, see {@link SdioCommonInfoType}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType); + +/** + * @brief Flushes data. + * + * You can call this function when an SDIO needs to be reinitialized or an unexpected error occurs. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioFlushData(struct DevHandle *handle); + +/** + * @brief Claims a host exclusively. + * + * You can call this function to enable the SDIO module to exclusively claim a host + * and then perform operations on the devices connected to the host. After performing required operations, + * release the host by calling {@link SdioReleaseHost}. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @since 1.0 + */ +void SdioClaimHost(struct DevHandle *handle); + +/** + * @brief Releases the exclusively claimed host. + * + * This function is used in pair with {@link SdioClaimHost}. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @since 1.0 + */ +void SdioReleaseHost(struct DevHandle *handle); + +/** + * @brief Enables the SDIO device so that its register can be accessed. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioEnableFunc(struct DevHandle *handle); + +/** + * @brief Disables the SDIO device. + * + * This function is used in pair with {@link SdioEnableFunc}. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioDisableFunc(struct DevHandle *handle); + +/** + * @brief Claims an SDIO IRQ. + * + * When there is data, commands, or events, the IRQ function is executed. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * @param irqHandler Indicates the pointer to the SDIO IRQ function. For details, see {@link SdioIrqHandler}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler); + +/** + * @brief Releases an SDIO IRQ. + * + * This function is used in pair with {@link SdioClaimIrq}. + * + * @param handle Indicates the pointer to the device handle of the SDIO controller obtained by {@link SdioOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * @since 1.0 + */ +int32_t SdioReleaseIrq(struct DevHandle *handle); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* SDIO_IF_H */ +/** @} */ \ No newline at end of file diff --git a/include/platform/spi_if.h b/include/platform/spi_if.h new file mode 100755 index 00000000..ea4f4752 --- /dev/null +++ b/include/platform/spi_if.h @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup SPI + * @{ + * + * @brief Defines standard APIs of the Serial Peripheral Interface (SPI) capabilities. + * + * The SPI module abstracts the SPI capabilities of different system platforms to provide stable APIs + * for driver development. + * This module can create and destroy SPI device handles, read and write SPI data, + * and obtain and set configuration parameters. + * + * @since 1.0 + */ + +/** + * @file spi_if.h + * + * @brief Defines standard SPI-specific interfaces for driver development. + * + * A driver needs to use the SPI-specific interfaces for data writing and reading + * before performing any operations on an SPI-compliant device. + * + * @since 1.0 + */ + +#ifndef SPI_IF_H +#define SPI_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Indicates the SPI clock phase. The value 0 indicates that data will be sampled on the first clock edge, + * and 1 indicates that data will be sampled on the second clock edge. + * + * @since 1.0 + */ +#define SPI_CLK_PHASE (1 << 0) +/** + * @brief Indicates the SPI clock polarity. The value 0 indicates a low-level clock signal in the idle state, + * and 1 indicates a high-level clock signal in the idle state. + * + * @since 1.0 + */ +#define SPI_CLK_POLARITY (1 << 1) +/** + * @brief Indicates that a single data line is used for both input and output. + * + * @since 1.0 + */ +#define SPI_MODE_3WIRE (1 << 2) +/** + * @brief Indicates the SPI loopback mode. + * + * @since 1.0 + */ +#define SPI_MODE_LOOP (1 << 3) +/** + * @brief Indicates the SPI data transfer order. The value 0 indicates that data is transferred from the most + * significant bit (MSB) to the least significant bit (LSB), and 1 indicates the opposite. + * + * @since 1.0 + */ +#define SPI_MODE_LSBFE (1 << 4) +/** + * @brief Indicates that there is only one SPI device, and no chip select (CS) is required. + * + * @since 1.0 + */ +#define SPI_MODE_NOCS (1 << 5) +/** + * @brief Indicates that the CS level is high when an SPI device is selected. + * + * @since 1.0 + */ +#define SPI_MODE_CS_HIGH (1 << 6) +/** + * @brief Indicates that the SPI device is set to low for pausing data transfer. + * + * @since 1.0 + */ +#define SPI_MODE_READY (1 << 7) + +/** + * @brief Enumerates transfer modes of SPI data. + * + * @attention The specific SPI controller determines which variables in this structure are supported. + * + * @since 1.0 + */ +enum SpiTransferMode { + SPI_INTERRUPT_TRANSFER = 0, /**< Interrupt transfer mode */ + SPI_POLLING_TRANSFER, /**< Polling transfer mode */ + SPI_DMA_TRANSFER, /**< Direct Memory Access (DMA) transfer mode */ +}; + +/** + * @brief Defines the general SPI device descriptor, which can be used as the unique identifier of an SPI device. + * When operating an SPI device, you need to specify a descriptor of the {@link SpiDevInfo} type, and obtain the + * handle of the SPI device by calling {@link SpiOpen}. + * + * @since 1.0 + */ +struct SpiDevInfo { + uint32_t busNum; /**< SPI bus number */ + uint32_t csNum; /**< SPI device chip select (CS) */ +}; + +/** + * @brief Defines the custom SPI transfer message. + * + * @attention The specific SPI controller determines whether speed, delayUs, + * and csChange are supported. + * + * @since 1.0 + */ +struct SpiMsg { + uint8_t *wbuf; /**< Address of the write buffer */ + uint8_t *rbuf; /**< Address of the read buffer */ + uint32_t len; /**< Length of the read and write buffers. The read buffer and the write + * buffer have the same length. + */ + uint32_t speed; /**< Current message transfer speed */ + uint16_t delayUs; /**< Delay (in microseconds) before starting the next transfer. + * The value 0 indicates there is no delay between transfers. + */ + uint8_t csChange; /**< Whether to switch off the CS before the next transfer when the current transfer has been + * completed. 1 indicates to switch off the CS; 0 indicates to switch on the CS. + */ +}; + +/** + * @brief Defines the configuration of an SPI device. + * + * @attention The specific SPI controller determines which variables in this structure are supported. + * + * @since 1.0 + */ +struct SpiCfg { + uint32_t maxSpeedHz; /**< Maximum clock frequency */ + uint16_t mode; /**< Input and output mode of SPI data | Description + * -----------------| ----------------------- + * SPI_CLK_PHASE | SPI clock phase. + * SPI_CLK_POLARITY | SPI clock polarity. + * SPI_MODE_3WIRE | A single data line is used for both input and output. + * SPI_MODE_LOOP | SPI loopback mode. + * SPI_MODE_LSBFE | SPI data transfer order + * SPI_MODE_NOCS | There is only one SPI device, and no CS is required. + * SPI_MODE_CS_HIGH | The CS level is high when an SPI device is selected. + * SPI_MODE_READY | The SPI device is set to low for pausing data transfer. + */ + uint8_t transferMode; /**< Data transfer mode, as defined in {@link SpiTransferMode}. */ + uint8_t bitsPerWord; /**< Data transfer bit width */ +}; + +/** + * @brief Obtains the handle of an SPI device. + * + * @param info Indicates the pointer to the SPI device information. + * + * @return Returns the pointer to the handle of the SPI device if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct DevHandle *SpiOpen(const struct SpiDevInfo *info); + +/** + * @brief Releases the handle of an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * + * @since 1.0 + */ +void SpiClose(struct DevHandle *handle); + +/** + * @brief Launches a custom transfer to an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * @param msgs Indicates the pointer to the data to transfer. + * @param count Indicates the length of the message structure array. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * @see SpiMsg + * @since 1.0 + */ +int32_t SpiTransfer(struct DevHandle *handle, struct SpiMsg *msgs, uint32_t count); + +/** + * @brief Reads data of a specified length from an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * @param buf Indicates the pointer to the buffer for receiving the data. + * @param len Indicates the length of the data to read. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len); + +/** + * @brief Writes data of a specified length to an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * @param buf Indicates the pointer to the data to write. + * @param len Indicates the length of the data to write. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len); + +/** + * @brief Sets configuration parameters for an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * @param cfg Indicates the pointer to the configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t SpiSetCfg(struct DevHandle *handle, struct SpiCfg *cfg); + +/** + * @brief Obtains the configuration parameters of an SPI device. + * + * @param handle Indicates the pointer to the SPI device handle obtained via {@link SpiOpen}. + * @param cfg Indicates the pointer to the configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t SpiGetCfg(struct DevHandle *handle, struct SpiCfg *cfg); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* SPI_IF_H */ +/** @} */ diff --git a/include/platform/uart_if.h b/include/platform/uart_if.h new file mode 100755 index 00000000..15394259 --- /dev/null +++ b/include/platform/uart_if.h @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup UART + * @{ + * + * @brief Defines standard APIs of universal asynchronous receiver/transmitter (UART) capabilities. + * + * You can use this module to access the UART and enable the driver to operate a UART-compliant device. + * The functions in this module help you to obtain and release the UART device handle, read and write data, + * obtain and set the baud rate and device attributes. + * + * @since 1.0 + */ + +/** + * @file uart_if.h + * + * @brief Declares standard UART APIs. + * + * @since 1.0 + */ + +#ifndef UART_IF_H +#define UART_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Defines basic attributes of the UART port. + * + * You can configure the attributes via {@link UartSetAttribute}. If the parameters are not set, + * default attributes are used. + * + * @attention The UART controller determines which UART attribute parameters are supported. + * + * @since 1.0 + */ +struct UartAttribute { + /** + * Data Bit | Description + * ------------| ----------------------- + * UART_ATTR_DATABIT_8 | 8 data bits + * UART_ATTR_DATABIT_7 | 7 data bits + * UART_ATTR_DATABIT_6 | 6 data bits + * UART_ATTR_DATABIT_5 | 5 data bits + */ + unsigned int dataBits : 4; +/** + * @brief Indicates the UART word length, which is 8 data bits per frame. + * + * @since 1.0 + */ +#define UART_ATTR_DATABIT_8 0 +/** + * @brief Indicates the UART word length, which is 7 data bits per frame. + * + * @since 1.0 + */ +#define UART_ATTR_DATABIT_7 1 +/** + * @brief Indicates the UART word length, which is 6 data bits per frame. + * + * @since 1.0 + */ +#define UART_ATTR_DATABIT_6 2 +/** + * @brief Indicates the UART word length, which is 5 data bits per frame. + * + * @since 1.0 + */ +#define UART_ATTR_DATABIT_5 3 + /** + * Parity Bit | Description + * ------------| ----------------------- + * UART_ATTR_PARITY_NONE | No parity bit + * UART_ATTR_PARITY_ODD | Odd parity bit + * UART_ATTR_PARITY_EVEN | Even parity bit + * UART_ATTR_PARITY_MARK | 1 + * UART_ATTR_PARITY_SPACE | 0 + */ + unsigned int parity : 4; +/** + * @brief Indicates that the UART device has no parity bit. + * + * @since 1.0 + */ +#define UART_ATTR_PARITY_NONE 0 +/** + * @brief Indicates that the UART device has an odd parity bit. + * + * @since 1.0 + */ +#define UART_ATTR_PARITY_ODD 1 +/** + * @brief Indicates that the UART device has an even parity bit. + * + * @since 1.0 + */ +#define UART_ATTR_PARITY_EVEN 2 +/** + * @brief Indicates that the parity bit is 1. + * + * @since 1.0 + */ +#define UART_ATTR_PARITY_MARK 3 +/** +* @brief Indicates that the parity bit is 0. + * + * @since 1.0 + */ +#define UART_ATTR_PARITY_SPACE 4 + /** + * Stop Bit | Description + * ------------| ----------------------- + * UART_ATTR_STOPBIT_1 | 1 stop bit + * UART_ATTR_STOPBIT_1P5 | 1.5 stop bits + * UART_ATTR_STOPBIT_2 | 2 stop bits + */ + unsigned int stopBits : 4; +/** + * @brief Indicates that the UART device has 1 stop bit. + * + * @since 1.0 + */ +#define UART_ATTR_STOPBIT_1 0 +/** + * @brief Indicates that the UART device has 1.5 stop bits. + * + * @since 1.0 */ +#define UART_ATTR_STOPBIT_1P5 1 +/** + * @brief Indicates that the UART device has 2 stop bits. + * + * @since 1.0 + */ +#define UART_ATTR_STOPBIT_2 2 + /** + * RTS | Description + * ------------| ----------------------- + * UART_ATTR_RTS_DIS | RTS disabled + * UART_ATTR_RTS_EN | RTS enabled + */ + unsigned int rts : 1; +/** +* @brief Indicates that Request To Send (RTS) is disabled for the UART device. + * + * @since 1.0 + */ +#define UART_ATTR_RTS_DIS 0 +/** + * @brief Indicates that RTS is enabled for the UART device. + * + * @since 1.0 + */ +#define UART_ATTR_RTS_EN 1 + /** + * CTS | Description + * ------------| ----------------------- + * UART_ATTR_CTS_DIS | CTS disabled + * UART_ATTR_CTS_EN | CTS enabled + */ + unsigned int cts : 1; +/** + * @brief Indicates that Clear To Send (CTS) is disabled for the UART device. + * + * @since 1.0 + */ +#define UART_ATTR_CTS_DIS 0 +/** + * @brief Indicates that CTS is enabled for the UART device. + * + * @since 1.0 + */ +#define UART_ATTR_CTS_EN 1 + /** + * Receiver FIFO | Description + * ------------| ----------------------- + * UART_ATTR_RX_FIFO_DIS | FIFO disabled + * UART_ATTR_RX_FIFO_EN | FIFO enabled + */ + unsigned int fifoRxEn : 1; +/** + * @brief Indicates that First In First Out (FIFO) is disabled for the receiving UART. + * + * @since 1.0 + */ +#define UART_ATTR_RX_FIFO_DIS 0 +/** + * @brief Indicates that FIFO is enabled for the receiving UART. + * + * @since 1.0 + */ +#define UART_ATTR_RX_FIFO_EN 1 + /** + * Transmitter FIFO | Description + * ------------| ----------------------- + * UART_ATTR_TX_FIFO_DIS | FIFO disabled + * UART_ATTR_TX_FIFO_EN | FIFO enabled + */ + unsigned int fifoTxEn : 1; +/** + * @brief Indicates that FIFO is disabled for the transmitting UART. + * + * @since 1.0 + */ +#define UART_ATTR_TX_FIFO_DIS 0 +/** + * @brief Indicates that FIFO is enabled for the transmitting UART. + * + * @since 1.0 + */ +#define UART_ATTR_TX_FIFO_EN 1 + /** Reserved bits */ + unsigned int reserved : 16; +}; + +/** + * @brief Enumerates UART transmission modes. + * + * @attention The UART controller determines whether an enumerated transmission mode is supported. + * + * @since 1.0 + */ +enum UartTransMode { + UART_MODE_RD_BLOCK = 0, /**< Blocking mode */ + UART_MODE_RD_NONBLOCK, /**< Non-blocking mode */ + UART_MODE_DMA_RX_EN, /**< DMA enabled for data receiving */ + UART_MODE_DMA_RX_DIS, /**< DMA disabled for data receiving */ + UART_MODE_DMA_TX_EN, /**< DMA enabled for data transmitting */ + UART_MODE_DMA_TX_DIS, /**< DMA disabled for data transmitting */ +}; + +/** + * @brief Obtains the UART device handle. + * + * Before accessing the UART device, you must call this function to obtain the UART device handle. + * + * @param port Indicates the UART port. + * + * @return Returns the pointer to the UART device handle if the handle is obtained; returns NULL otherwise. + * @since 1.0 + */ +struct DevHandle *UartOpen(uint32_t port); + +/** + * @brief Releases the UART device handle. + * + * If you no longer need to access the UART device, you should call this function to close its handle so as to + * release unused memory resources. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * + * @since 1.0 + */ +void UartClose(struct DevHandle *handle); + +/** + * @brief Reads data of a specified size from a UART device. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param data Indicates the pointer to the buffer for receiving the data. + * @param size Indicates the size of the data to read. + * + * @return Returns the size of the data that is successfully read; returns a negative number if the reading fails. + * @since 1.0 + */ +int32_t UartRead(struct DevHandle *handle, uint8_t *data, uint32_t size); + +/** + * @brief Writes data of a specified size into a UART device. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param data Indicates the pointer to the data to write. + * @param size Indicates the size of the data to write. + * + * @return Returns 0 if the data is successfully written; returns a negative number otherwise. + * @since 1.0 + */ +int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size); + +/** + * @brief Obtains the baud rate of the UART device. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param baudRate Indicates the pointer to the obtained baud rate. + * + * @return Returns 0 if the baud rate is obtained; returns a negative number otherwise. + * @since 1.0 + */ +int32_t UartGetBaud(struct DevHandle *handle, uint32_t *baudRate); + +/** + * @brief Sets the baud rate for the UART device. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param baudRate Indicates the baud rate to set. + * + * @return Returns 0 if the setting is successful; returns a negative number otherwise. + * @since 1.0 + */ +int32_t UartSetBaud(struct DevHandle *handle, uint32_t baudRate); + +/** + * @brief Obtains the UART attribute. + * + * UART attributes include data bits, stop bits, parity bit, CTS, RTS, and receiving and transmitting FIFO. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param attribute Indicates the pointer to the obtained UART attribute. + * + * @return Returns 0 if the UART attribute is obtained; returns a negative number otherwise. + * @since 1.0 */ +int32_t UartGetAttribute(struct DevHandle *handle, struct UartAttribute *attribute); + +/** + * @brief Sets the UART attribute. + * + * UART attributes include data bits, stop bits, parity bit, CTS, RTS, and receiving and transmitting FIFO. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param attribute Indicates the pointer to the UART attribute to set. + * + * @return Returns 0 if the setting is successful; returns a negative number otherwise. + * @since 1.0 + */ +int32_t UartSetAttribute(struct DevHandle *handle, struct UartAttribute *attribute); + +/** + * @brief Sets the UART transmission mode. + * + * @param handle Indicates the pointer to the UART device handle, which is obtained via {@link UartOpen}. + * @param mode Indicates a transmission mode enumerated in {@linkUartTransMode}. + * + * @return Returns 0 if the setting is successful; returns a negative number otherwise. + * @since 1.0 + */ +int32_t UartSetTransMode(struct DevHandle *handle, enum UartTransMode mode); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PAL_UART_IF_H */ +/** @} */ diff --git a/include/platform/watchdog_if.h b/include/platform/watchdog_if.h new file mode 100755 index 00000000..8816e2c4 --- /dev/null +++ b/include/platform/watchdog_if.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WATCHDOG + * @{ + * + * @brief Provides watchdog APIs, such as setting the watchdog timeout duration and feeding a watchdog (resetting + * a watchdog timer). + * + * If an error occurs in the main program of the system, for example, if the program crashes or the watchdog timer + * is not reset in time, the watchdog timer generates a reset signal, and the system restores from the suspending + * state to the normal state. + * + * @since 1.0 + */ + +/** + * @file watchdog_if.h + * + * @brief Declares standard watchdog APIs. + * + * @since 1.0 + */ + +#ifndef WATCHDOG_IF_H +#define WATCHDOG_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates watchdog statuses. + * + * To obtain the watchdog status, call the {@link WatchdogGetStatus} function. + * + * @since 1.0 + */ +enum WatchdogStatus { + WATCHDOG_STOP, /**< Stopped */ + WATCHDOG_START, /**< Started */ +}; + +/** + * @brief Opens a watchdog. + * + * Before operating a watchdog, you must call this function to open it and obtain its device handle. + * + * @param wdtId Indicates the watchdog ID. + * + * @return Returns the pointer to the device handle of the watch dog if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct DevHandle *WatchdogOpen(int16_t wdtId); + + /** + * @brief Closes a watchdog. + * + * If you no longer need a watchdog, call this function to close it and release its device handle to prevent + * unnecessary use of memory resources. + * + * @param handle Indicates the pointer to the watchdog device handle. + * + * @since 1.0 + */ +void WatchdogClose(struct DevHandle *handle); + +/** + * @brief Obtains the watchdog status. + * + * For the available watchdog statuses, see {@link WatchdogStatus}. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * @param status Indicates the pointer to the watchdog status. + * + * @return Returns 0 if the watchdog status is obtained; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t WatchdogGetStatus(struct DevHandle *handle, int32_t *status); + +/** + * @brief Starts a watchdog. + * + * This function starts the watchdog timer. You must feed the watchdog periodically; otherwise, the watchdog hardware + * will reset the system upon a timeout. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * + * @return Returns 0 if the watchdog is successfully started; returns a negative value otherwise. + * @attention If the watchdog timer has started before this function is called, calling this function will succeed; + * however, the watchdog hardware determines whether to reset the timer. + * + * @since 1.0 + */ +int32_t WatchdogStart(struct DevHandle *handle); + +/** + * @brief Stops a watchdog. + * + * If the watchdog has stopped before this function is called, calling this function will succeed. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * + * @return Returns 0 if the watchdog is successfully stopped; returns a negative value otherwise. + * @since 1.0 + */ +int32_t WatchdogStop(struct DevHandle *handle); + +/** + * @brief Sets the watchdog timeout duration. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * @param seconds Indicates the timeout duration, in seconds. + * + * @return Returns 0 if the setting is successful; returns a negative value otherwise. + * @since 1.0 + */ +int32_t WatchdogSetTimeout(struct DevHandle *handle, uint32_t seconds); + +/** + * @brief Obtains the watchdog timeout duration. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * @param seconds Indicates the pointer to the timeout duration, in seconds. + * + * @return Returns 0 if the watchdog timeout duration is obtained; returns a negative value otherwise. + * @since 1.0 + */ +int32_t WatchdogGetTimeout(struct DevHandle *handle, uint32_t *seconds); + +/** + * @brief Feeds a watchdog, that is, resets a watchdog timer. + * + * After a watchdog is started, you must feed it to reset the watchdog timer periodically. + * If you do not do so, the watchdog hardware will reset the system upon a timeout. + * + * @param handle Indicates the pointer to the watchdog handle, which is obtained via {@link WatchdogOpen}. + * + * @return Returns 0 if the watchdog is fed; returns a negative value otherwise. + * @since 1.0 + */ +int32_t WatchdogFeed(struct DevHandle *handle); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* WATCHDOG_IF_H */ +/** @} */ diff --git a/include/utils/hdf_base.h b/include/utils/hdf_base.h new file mode 100755 index 00000000..3d07aa35 --- /dev/null +++ b/include/utils/hdf_base.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup DriverUtils + * @{ + * + * @brief Defines common macros and interfaces of the driver module. + * + * This module provides interfaces such as log printing, doubly linked list operations, and work queues. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_base.h + * + * @brief Declares driver common types, including the enumerated values returned by the function + * and the macro for obtaining the array size. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef HDF_BASE_TYPE_H +#define HDF_BASE_TYPE_H + +#if defined(__KERNEL__) +#include +#else +#include +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Enumerates HDF return value types. + */ +typedef enum { + HDF_SUCCESS = 0, /**< The operation is successful. */ + HDF_FAILURE = -1, /**< Failed to invoke the OS underlying function. */ + HDF_ERR_NOT_SUPPORT = -2, /**< Not supported. */ + HDF_ERR_INVALID_PARAM = -3, /**< Invalid parameter. */ + HDF_ERR_INVALID_OBJECT = -4, /**< Invalid object. */ + HDF_ERR_MALLOC_FAIL = -6, /**< Memory allocation fails. */ + HDF_ERR_TIMEOUT = -7, /**< Timeout occurs. */ + HDF_ERR_THREAD_CREATE_FAIL = -10, /**< Failed to create a thread. */ + HDF_ERR_QUEUE_FULL = -15, /**< The queue is full. */ + HDF_ERR_DEVICE_BUSY = -16, /**< The device is busy. */ + HDF_ERR_IO = -17, /**< I/O error. */ + HDF_ERR_BAD_FD = -18, /**< Incorrect file descriptor. */ + +#define HDF_BSP_ERR_START (-100) /**< Defines the start of the Board Support Package (BSP) module error codes. */ +#define HDF_BSP_ERR_NUM(v) (HDF_BSP_ERR_START + (v)) /**< Defines the BSP module error codes. */ + HDF_BSP_ERR_OP = HDF_BSP_ERR_NUM(-1), /**< Failed to operate a BSP module. */ + HDF_ERR_BSP_PLT_API_ERR = HDF_BSP_ERR_NUM(-2), /**< The platform API of the BSP module is incorrect. */ + HDF_PAL_ERR_DEV_CREATE = HDF_BSP_ERR_NUM(-3), /**< Failed to create a BSP module device. */ + HDF_PAL_ERR_INNER = HDF_BSP_ERR_NUM(-4), /**< Internal error codes of the BSP module. */ + +#define HDF_DEV_ERR_START (-200) /**< Defines the start of the device module error codes. */ +#define HDF_DEV_ERR_NUM(v) (HDF_DEV_ERR_START + (v)) /**< Defines the device module error codes. */ + HDF_DEV_ERR_NO_MEMORY = HDF_DEV_ERR_NUM(-1), /**< Failed to allocate memory to the device module. */ + HDF_DEV_ERR_NO_DEVICE = HDF_DEV_ERR_NUM(-2), /**< The device module has no device. */ + HDF_DEV_ERR_NO_DEVICE_SERVICE = HDF_DEV_ERR_NUM(-3), /**< The device module has no device service. */ + HDF_DEV_ERR_DEV_INIT_FAIL = HDF_DEV_ERR_NUM(-4), /**< Failed to initialize a device module. */ + HDF_DEV_ERR_PUBLISH_FAIL = HDF_DEV_ERR_NUM(-5), /**< The device module failed to release a service. */ + HDF_DEV_ERR_ATTACHDEV_FAIL = HDF_DEV_ERR_NUM(-6), /**< Failed to attach a device to a device module. */ + HDF_DEV_ERR_NODATA = HDF_DEV_ERR_NUM(-7), /**< Failed to read data from a device module. */ + HDF_DEV_ERR_NORANGE = HDF_DEV_ERR_NUM(-8), /**< The device module data is out of range. */ + HDF_DEV_ERR_OP = HDF_DEV_ERR_NUM(-10), /**< Failed to operate a device module. */ +} HDF_STATUS; + +/** + * @brief Indicates that the function keeps waiting to obtain a semaphore or mutex. + */ +#define HDF_WAIT_FOREVER 0xFFFFFFFF + +/** + * @brief Defines the array size. + */ +#define HDF_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + +/** + * @brief Defines a time conversion unit, for example, the unit for converting from second to millisecond. + */ +#define HDF_KILO_UNIT 1000 + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_BASE_TYPE_H */ +/** @} */ diff --git a/include/utils/hdf_dlist.h b/include/utils/hdf_dlist.h new file mode 100755 index 00000000..531420e7 --- /dev/null +++ b/include/utils/hdf_dlist.h @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/** + * @addtogroup DriverUtils + * @{ + * + * @brief Defines common macros and interfaces of the driver module. + * + * This module provides interfaces such as log printing, doubly linked list operations, and work queues. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_dlist.h + * + * @brief Declares doubly linked list structures and interfaces. + * + * This file provides interfaces such as inserting a node from the head or tail of a doubly linked list, + * checking whether a doubly linked list is empty, traversing a doubly linked list, and merging doubly linked lists. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_LIST_H +#define HDF_LIST_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a doubly linked list. + */ +struct DListHead { + struct DListHead *next; /**< Pointer to the next node */ + struct DListHead *prev; /**< Pointer to the previous node */ +}; + +/** + * @brief Initializes a doubly linked list. + * + * @param head Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline void DListHeadInit(struct DListHead *head) +{ + head->next = head; + head->prev = head; +} + +/** + * @brief Checks whether a doubly linked list is empty. + * + * @param head Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline bool DListIsEmpty(const struct DListHead *head) +{ + return (head->next == head) ? true : false; +} +/** + * @brief Removes a node from a doubly linked list. + * + * @param entry Indicates the pointer to the node to remove. For details, see {@link DListHead}. + * The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline void DListRemove(struct DListHead *entry) +{ + entry->prev->next = entry->next; + entry->next->prev = entry->prev; + + entry->prev = NULL; + entry->next = NULL; +} + +/** + * @brief Inserts a node from the head of a doubly linked list. + * + * @param entry Indicates the pointer to the node to insert. For details, see {@link DListHead}. + * The parameter cannot be empty. + * @param head Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline void DListInsertHead(struct DListHead *entry, struct DListHead *head) +{ + entry->next = head->next; + entry->prev = head; + + head->next->prev = entry; + head->next = entry; +} + +/** + * @brief Inserts a node from the tail of a doubly linked list. + * + * @param entry Indicates the pointer to the node to insert. For details, see {@link DListHead}. + * The parameter cannot be empty. + * @param head Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline void DListInsertTail(struct DListHead *entry, struct DListHead *head) +{ + entry->next = head; + entry->prev = head->prev; + + head->prev->next = entry; + head->prev = entry; +} + +/** + * @brief Merges two linked lists by adding the list specified by list to + * the head of the list specified by head and initializes the merged list. + * + * @param list Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @param head Indicates the pointer to the linked list {@link DListHead}. The parameter cannot be empty. + * @since 1.0 + * @version 1.0 + */ +static inline void DListMerge(struct DListHead *list, struct DListHead *head) +{ + list->next->prev = head; + list->prev->next = head->next; + + head->next->prev = list->prev; + head->next = list->next; + + DListHeadInit(list); +} + +/** + * @brief Obtains the address of a structure variable from its member address. + * + * @param ptr Indicates the structure member address. + * @param type Indicates the structure type. + * @param member Indicates the structure member. + * @since 1.0 + * @version 1.0 + */ +#define CONTAINER_OF(ptr, type, member) \ + (type *)((char *)(ptr) - (char *)&((type *)0)->member) + +/** + * @brief Obtains the first node of a doubly linked list. + * + * @param ptr Indicates the structure member address. + * @param type Indicates the structure type. + * @param member Indicates the structure member. + * @since 1.0 + * @version 1.0 + */ +#define DLIST_FIRST_ENTRY(ptr, type, member) \ + CONTAINER_OF((ptr)->next, type, member) + +/** + * @brief Obtains the last node of a doubly linked list. + * + * @param ptr Indicates the structure member address. + * @param type Indicates the structure type. + * @param member Indicates the structure member. + * @since 1.0 + * @version 1.0 + */ +#define DLIST_LAST_ENTRY(ptr, type, member) \ + CONTAINER_OF((ptr)->prev, type, member) + +/** + * @brief Traverses all nodes in a doubly linked list. + * + * @param pos Indicates the pointer to the structure variable. + * @param head Indicates the pointer to the linked list head. + * @param type Indicates the structure type. + * @param member Indicates the member type of the structure. + * @since 1.0 + * @version 1.0 + */ +#define DLIST_FOR_EACH_ENTRY(pos, head, type, member) \ + for ((pos) = CONTAINER_OF((head)->next, type, member); \ + &(pos)->member != (head); \ + (pos) = CONTAINER_OF((pos)->member.next, type, member)) + +/** + * @brief Traverses all nodes in a doubly linked list. + * This function is used to delete the nodes pointed to by pos during traversal. + * + * @param pos Indicates the pointer to the structure variable. + * @param tmp Indicates the pointer to the structure variable, pointing to the next node of pos. + * @param head Indicates the pointer to the linked list head. + * @param type Indicates the structure type. + * @param member Indicates the member type of the structure. + * @since 1.0 + * @version 1.0 + */ +#define DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, head, type, member) \ + for ((pos) = CONTAINER_OF((head)->next, type, member), \ + (tmp) = CONTAINER_OF((pos)->member.next, type, member); \ + &(pos)->member != (head); \ + (pos) = (tmp), (tmp) = CONTAINER_OF((pos)->member.next, type, member)) + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_LIST_H */ +/** @} */ diff --git a/include/utils/hdf_log.h b/include/utils/hdf_log.h new file mode 100755 index 00000000..397e7270 --- /dev/null +++ b/include/utils/hdf_log.h @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup DriverUtils + * @{ + * + * @brief Defines common macros and interfaces of the driver module. + * + * This module provides interfaces such as log printing, doubly linked list operations, and work queues. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_log.h + * + * @brief Declares log printing functions of the driver module. + * This module provides functions for printing logs at the verbose, debug, information, warning, and error levels. + * + * To use these functions, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_LOG_H +#define HDF_LOG_H + +#ifdef HDF_LOG_TAG +#undef HDF_LOG_TAG +#endif /* HDF_LOG_TAG */ + +/** Add quotation mark */ +#define LOG_TAG_MARK_EXTEND(HDF_TAG) #HDF_TAG +#define LOG_TAG_MARK(HDF_TAG) LOG_TAG_MARK_EXTEND(HDF_TAG) + +#ifndef LOG_TAG +#define LOG_TAG LOG_TAG_MARK(HDF_LOG_TAG) +#endif /* LOG_TAG */ + +#if defined(_LINUX_USER_) +#include "cutils/log.h" +#elif defined(__KERNEL__) +#include +#elif defined(__LITEOS__) && defined(__USER__) +#include +#elif defined(__LITEOS__) +#include "los_printf.h" +#else +#include +#endif /* __KERNEL__ */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if defined(_LINUX_USER_) +/** + * @brief Prints logs at the verbose level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGV(...) ALOGV(__VA_ARGS__) +/** + * @brief Prints logs at the debug level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGD(...) ALOGD(__VA_ARGS__) +/** + * @brief Prints logs at the information level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGI(...) ALOGI(__VA_ARGS__) + +/** + * @brief Prints logs at the warning level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGW(...) ALOGW(__VA_ARGS__) + +/** + * @brief Prints logs at the error level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGE(...) ALOGE(__VA_ARGS__) + +#elif defined(__KERNEL__) +#define _HDF_FMT_TAG(TAG, LEVEL) "[" #LEVEL "/" #TAG "] " +#define HDF_FMT_TAG(TAG, LEVEL) _HDF_FMT_TAG(TAG, LEVEL) + +/** + * @brief Prints logs at the verbose level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGV(fmt, args...) printk(KERN_DEBUG HDF_FMT_TAG(HDF_LOG_TAG, V) fmt, ## args) +/** + * @brief Prints logs at the debug level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGD(fmt, args...) printk(KERN_DEBUG HDF_FMT_TAG(HDF_LOG_TAG, D) fmt, ## args) +/** + * @brief Prints logs at the information level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGI(fmt, args...) printk(KERN_INFO HDF_FMT_TAG(HDF_LOG_TAG, I) fmt, ## args) +/** + * @brief Prints logs at the warning level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGW(fmt, args...) printk(KERN_WARNING HDF_FMT_TAG(HDF_LOG_TAG, W) fmt, ## args) +/** + * @brief Prints logs at the error level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGE(fmt, args...) printk(KERN_ERR HDF_FMT_TAG(HDF_LOG_TAG, E) fmt, ## args) + +#elif defined(__LITEOS__) && defined(__USER__) +/** + * @brief Prints logs at the verbose level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGV(fmt, arg...) printf("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the debug level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGD(fmt, arg...) printf("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the information level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGI(fmt, arg...) printf("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the warning level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGW(fmt, arg...) printf("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the error level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGE(fmt, arg...) printf("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) +#elif defined(__LITEOS__) +/** + * @brief Prints logs at the verbose level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGV(fmt, arg...) PRINT_DEBUG("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the debug level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGD(fmt, arg...) PRINT_DEBUG("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the information level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGI(fmt, arg...) PRINT_INFO("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the warning level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGW(fmt, arg...) PRINT_WARN("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the error level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGE(fmt, arg...) PRINT_ERR("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) +#else +/** + * @brief Prints logs at the verbose level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGV(fmt, arg...) printf("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the debug level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGD(fmt, arg...) printf("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the information level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGI(fmt, arg...) printf("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the warning level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGW(fmt, arg...) printf("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) +/** + * @brief Prints logs at the error level. + * + * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_LOGE(fmt, arg...) printf("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) + +#endif /* __KERNEL__ */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_LOG_H */ +/** @} */ diff --git a/include/utils/hdf_workqueue.h b/include/utils/hdf_workqueue.h new file mode 100755 index 00000000..7d009666 --- /dev/null +++ b/include/utils/hdf_workqueue.h @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup DriverUtils + * @{ + * + * @brief Defines common macros and interfaces of the driver module. + * + * This module provides interfaces such as log printing, doubly linked list operations, and work queues. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_workqueue.h + * + * @brief Declares work queue structures and interfaces. + * + * This file provides interfaces such as initializing a work queue, a work item, and a delayed work item, + * adding a work or delayed work item to a work queue, and destroying a work queue, a work item, + * and a delayed work item. You need to define a work queue, a work item, and a delayed work item, + * and then call the initialization function to initialize them. The work item, delayed work item, + * and work queue must be destroyed when they are no longer used. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef HDF_WORKQUEUE_H +#define HDF_WORKQUEUE_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @brief Describes a work execution function type. + * + * The thread of the work queue executes this function after the work item is added to the work queue. + */ +typedef void (*HdfWorkFunc)(void *); + +/** + * @brief Enumerates statuses of a work item or a delayed work item. + */ +enum { + HDF_WORK_BUSY_PENDING = 1 << 0, /**< The work item or delayed work item is pending. */ + HDF_WORK_BUSY_RUNNING = 1 << 1, /**< The work item or delayed work item is running. */ +}; +/** + * @brief Describes a work item and a delayed work item. + * This structure defines the work and delayed work items, and then calls the initialization + * function {@link HdfWorkInit} or {@link HdfDelayedWorkInit} to perform initialization. + * The HdfAddWork() function is to add a work item to a work queue immediately, + * and the HdfAddDelayedWork() function is to add a work item to a work queue after the configured delayed time. + */ +typedef struct { + void *realWork; /**< Pointer to a work item and a delayed work item */ +} HdfWork; + +/** + * @brief Describes a work queue. + */ +typedef struct { + void *realWorkQueue; /**< Pointer to a work queue */ +} HdfWorkQueue; + +/** + * @brief Initializes a work queue. + * + * When a work queue is initialized, a thread is created. The thread cyclically executes the work items + * in the work queue, that is, executes their functions. + * + * @param queue Indicates the pointer to the work queue {@link OsalWorkQueue}. + * @param name Indicates the pointer to the work queue name. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t HdfWorkQueueInit(HdfWorkQueue *queue, char *name); + +/** + * @brief Initializes a work item. + * + * This function uses func and arg to initialize a work item. + * After the work item is added to a work queue, the thread of the work queue executes this function, + * and arg is passed to func. + * + * @param work Indicates the pointer to the work item {@link HdfWork}. + * @param func Indicates the work execution function. + * @param arg Indicates the pointer to the argument of the work execution function. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t HdfWorkInit(HdfWork *work, HdfWorkFunc func, void *arg); + +/** + * @brief Initializes a delayed work item. + * + * This function uses func and arg to initialize a work item. + * The work item is added to a work queue after the configured delayed time. + * The thread of the work queue executes this function, and arg is passed to func. + * + * @param work Indicates the pointer to the delayed work item {@link HdfWork}. + * @param func Indicates the work execution function. + * @param arg Indicates the pointer to the argument of the work execution function. + * + * @return Returns a value listed below: \n + * HDF_STATUS | Description + * ----------------------| ----------------------- + * HDF_SUCCESS | The operation is successful. + * HDF_ERR_INVALID_PARAM | Invalid parameter. + * HDF_ERR_MALLOC_FAIL | Memory allocation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t HdfDelayedWorkInit(HdfWork *work, HdfWorkFunc func, void *arg); + +/** + * @brief Destroys a work item. + * + * @param work Indicates the pointer to the work item {@link HdfWork}. + * @since 1.0 + * @version 1.0 + */ +void HdfWorkDestroy(HdfWork *work); + +/** + * @brief Destroys a work queue. + * + * @param queue Indicates the pointer to the work queue {@link HdfWorkQueue}. + * @since 1.0 + * @version 1.0 + */ +void HdfWorkQueueDestroy(HdfWorkQueue *queue); + +/** + * @brief Destroys a delayed work item. + * + * @param work Indicates the pointer to the delayed work item {@link HdfWork}. + * @since 1.0 + * @version 1.0 + */ +void HdfDelayedWorkDestroy(HdfWork *work); + +/** + * @brief Adds a work item to a work queue. + * + * After a work item is added to a work queue, the thread of the work queue executes the function of the work item. + * + * @param queue Indicates the pointer to the work queue {@link HdfWorkQueue}. + * @param work Indicates the pointer to the work item {@link HdfWork}. + * @return Returns true if the operation is successful; returns false otherwise. + * @since 1.0 + * @version 1.0 + */ +bool HdfAddWork(HdfWorkQueue *queue, HdfWork *work); + +/** + * @brief Adds a delayed work item to a work queue. + * + * A delayed work item is added to a work queue after the configured delayed time (ms), + * and the thread of the work queue executes the work function. + * + * @param queue Indicates the pointer to the work queue {@link HdfWorkQueue}. + * @param work Indicates the pointer to the delayed work item {@link HdfWork}. + * @return Returns true if the operation is successful; returns false otherwise. + * @since 1.0 + * @version 1.0 + */ +bool HdfAddDelayedWork(HdfWorkQueue *queue, HdfWork *work, unsigned long ms); + +/** + * @brief Obtains the status of a work item or delayed work item. + * + * @param work Indicates the pointer to the work item or delayed work item {@link HdfWork}. + * @return Returns HDF_WORK_BUSY_PENDING if the work item is pending; + * returns HDF_WORK_BUSY_RUNNING if the work item is running. + * @since 1.0 + * @version 1.0 + */ +unsigned int HdfWorkBusy(HdfWork *work); + +/** + * @brief Cancels a work item. This function waits until the work item is complete. + * + * @param work Indicates the pointer to the work item {@link HdfWork}. + * @return Returns true if the operation is successful; returns false otherwise. + * @since 1.0 + * @version 1.0 + */ +bool HdfCancelWorkSync(HdfWork *work); + +/** + * @brief Cancels a delayed work item. + * + * @param work Indicates the pointer to the delayed work item {@link HdfWork}. + * @return Returns true if the operation is successful; returns false otherwise. + * @since 1.0 + * @version 1.0 + */ +bool HdfCancelDelayedWorkSync(HdfWork *work); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_WORKQUEUE_H */ +/** @} */ diff --git a/include/wifi/hdf_wifi_event.h b/include/wifi/hdf_wifi_event.h new file mode 100755 index 00000000..a7535d75 --- /dev/null +++ b/include/wifi/hdf_wifi_event.h @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_wifi_event.h + * + * @brief Declares WLAN driver events. + * + * The functions in this file are used to report events such as scanning results, scanning completion, and station + * disconnection to the WPA interface. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef __HDF_WIFI_EVENT_H__ +#define __HDF_WIFI_EVENT_H__ + +#include "hdf_wifi_cmd.h" +#include "wifi_mac80211_ops.h" +#include "net_device.h" +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * @brief Defines the rate information received or sent over WLAN. + * + * @since 1.0 + */ +struct RateInfo { + uint8_t flags; /**< Flag field, used to indicate a specific rate transmission type of 802.11n */ + uint8_t mcs; /**< Modulation and Coding Scheme (MCS) index of the HT/VHT/HE rate */ + uint16_t legacy; /**< 100 kbit/s bit rate defined in 802.11a/b/g */ + uint8_t nss; /**< Number of streams (for VHT and HE only) */ + uint8_t resv; /**< Reserved */ +}; + +/** + * @brief Defines parameters related to the WLAN module that works in station mode. + * + * @since 1.0 + */ +struct StaBssParameters { + uint8_t flags; /**< Flag, used to indicate a specific rate transmission type of 802.11n */ + uint8_t dtimPeriod; /**< Delivery Traffic Indication Message (DTIM) period of BSS */ + uint16_t beaconInterval; /**< Beacon interval */ +}; + +/** + * @brief Defines the update of the Sta flag. + * + * @since 1.0 + */ +struct StaFlagUpdate { + uint32_t mask; /**< Flag mask */ + uint32_t set; /**< Flag value */ +}; + +/** + * @brief Defines station information. + * + * @since 1.0 + */ +struct StationInfo { + uint32_t filled; /**< Flag values of relevant structures */ + uint32_t connectedTime; /**< Duration (in seconds) since the last station connection */ + uint32_t inactiveTime; /**< Duration (in milliseconds) since the last station + * activity + */ + uint16_t llid; /**< Local mesh ID */ + uint16_t plid; /**< Peer mesh ID */ + + uint64_t rxBytes; /**< Received bytes */ + uint64_t txBytes; /**< Transmitted bytes */ + struct RateInfo txRate; /**< Transmission rate */ + struct RateInfo rxRate; /**< Receive rate */ + + uint32_t rxPackets; /**< Received data packets */ + uint32_t txPackets; /**< Transmitted data packets */ + uint32_t txPetries; /**< Number of retransmissions */ + uint32_t txFailed; /**< Number of failed transmissions */ + + uint32_t rxDroppedMisc; /**< Number of receive failures */ + int32_t generation; /**< Generation number */ + struct StaBssParameters bssParam; /**< Current BSS parameters */ + struct StaFlagUpdate staFlags; /**< Station flag masks and values */ + + int64_t offset; /**< Time offset of station */ + const uint8_t *assocReqIes; /**< Information Elements (IEs) in Association Request */ + uint32_t assocReqIesLen; /**< IE length in Association Request */ + uint32_t beaconLossCount; /**< Number of beacon loss events triggered */ + + uint8_t plinkState; /**< Mesh peer state */ + int8_t signal; /**< Signal strength */ + int8_t signalAvg; /**< Average signal strength */ + uint8_t resv1; /**< Reserved */ +}; + +/** + * @brief Defines authentication information. + * + * @since 1.0 + */ +struct Auth { + uint16_t authAlg; /**< Authentication algorithm */ + uint16_t authTransaction; /**< Authentication transaction */ + uint16_t statusCode; /**< Authentication status code */ + uint8_t variable[0]; /**< Algorithm challenge information stored in a flexible array */ +}; + +/** + * @brief Defines deauthentication information. + * + * @since 1.0 + */ +struct Deauth { + uint16_t reasonCode; /**< Deauthentication cause code */ +}; + +/** + * @brief Defines station association request. + * + * @since 1.0 + */ +struct AssocReq { + uint16_t capabInfo; /**< WLAN capability information */ + uint16_t listenInterval; /**< Scan interval */ + uint8_t variable[0]; /**< SSID and rate information stored in a flexible array */ +}; + +/** + * @brief Defines station association response. + * + * @since 1.0 + */ +struct AssocResp { + uint16_t capabInfo; /**< WLAN capability information */ + uint16_t statusCode; /**< Status code */ + uint16_t aid; /**< Authentication ID */ + uint8_t variable[0]; /**< Rate information stored in a flexible array */ +}; + +/** + * @brief Defines station reassociation request. + * + * @since 1.0 + */ +struct ReassocReq { + uint16_t capabInfo; /**< WLAN capability information */ + uint16_t listenInterval; /**< Scan interval */ + uint8_t currentAp[6]; /**< Current AP */ + uint8_t variable[0]; /**< SSID and rate information stored in a flexible array */ +}; + +/** + * @brief Defines station reassociation response. + * + * @since 1.0 + */ +struct ReassocResp { + uint16_t capabInfo; /**< WLAN capability information */ + uint16_t statusCode; /**< Status code */ + uint16_t aid; /**< Authentication ID */ + uint8_t variable[0]; /**< Rate information stored in a flexible array */ +}; + +/** + * @brief Defines station disconnection. + * + * @since 1.0 + */ +struct Disassoc { + uint16_t reasonCode; /**< Cause code */ +}; + +/** + * @brief Defines the update of the Sta flag. + * + * @since 1.0 + */ +struct Beacon { + uint64_t timestamp; /**< Timestamp */ + uint16_t beaconInt; /**< Beacon interval */ + uint16_t capabInfo; /**< WLAN capability information */ + uint8_t variable[0]; /**< SSID and rate information */ +}; + +/** + * @brief Defines scanning response. + * + * @since 1.0 + */ +struct ProbeResp { + uint64_t timestamp; /**< Timestamp */ + uint16_t beaconInt; /**< Beacon interval */ + uint16_t capabInfo; /**< WLAN capability information */ + uint8_t variable[0]; /**< SSID and rate information */ +}; + +/** + * @brief Defines management frame information. + * + * @since 1.0 + */ +struct Ieee80211Mgmt { + uint16_t frameControl; /**< Frame control field */ + uint16_t duration; /**< Duration */ + uint8_t dstAddr[6]; /**< Destination MAC address */ + uint8_t srcAddr[6]; /**< Source MAC address */ + uint8_t bssid[6]; /**< BSS ID */ + uint16_t seqCtrl; /**< Sequence control */ + union { + struct Auth auth; /**< Authentication Information */ + struct Deauth deauth; /**< Deauthentication Information */ + struct AssocReq assocReq; /**< Association request */ + struct AssocResp assocResp; /**< Association response */ + struct ReassocReq reassocReq; /**< Re-authentication */ + struct ReassocResp reassocResp; /**< Re-authentication response */ + struct Disassoc disassoc; /**< Disconnected */ + struct Beacon beacon; /**< Beacon frame */ + struct ProbeResp probeResp; /**< Probe response frame */ + } u; +}; + +/** + * @brief Represents the scanned BSS information. + * + * @since 1.0 + */ +struct ScannedBssInfo { + int32_t signal; /**< Signal strength */ + int16_t freq; /**< Center frequency of the channel where the BSS is located */ + uint8_t arry[2]; /**< Reserved */ + uint32_t mgmtLen; /**< Management frame length */ + struct Ieee80211Mgmt *mgmt; /**< Start address of the management frame */ +}; + +/** + * @brief Defines association results. + * + * @since 1.0 + */ +struct ConnetResult { + uint8_t bssid[ETH_ADDR_LEN]; /**< MAC address of the AP associated with the station */ + uint16_t statusCode; /**< 16-bit status code defined in the IEEE protocol */ + uint8_t *rspIe; /**< Association response IE */ + uint8_t *reqIe; /**< Association request IE */ + uint32_t reqIeLen; /**< Length of the association request IE */ + uint32_t rspIeLen; /**< Length of the association response IE */ + uint16_t connectStatus; /**< Connection status */ + uint16_t freq; /**< Frequency of the AP */ +}; + +/** + * @brief Enumerates MLME management statuses, indicating whether a device is successfully associated or + * fails to be associated. + * + * @since 1.0 + */ +enum WifiHmacMgmtStatus { + WIFI_HMAC_MGMT_SUCCESS = 0, /**< Association succeeds */ + WIFI_HMAC_MGMT_INVALID = 1, /**< Association fails */ + WIFI_HMAC_MGMT_TIMEOUT = 2, /**< Association timeout */ + WIFI_HMAC_MGMT_REFUSED = 3, /**< Association refused */ + WIFI_HMAC_MGMT_TOMANY_REQ = 4, /**< Repeated association request */ + WIFI_HMAC_MGMT_ALREADY_BSS = 5 /**< Associated with the BSS */ +}; + +/** + * @brief Reports a new STA event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param macAddr Indicates the pointer to the MAC address of the station. This parameter cannot be null. + * @param addrLen Indicates the length of the MAC address of the station. The length is fixed to six bytes. + * @param info Indicates the pointer to the station information. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventNewSta(const struct NetDevice *netdev, const uint8_t *macAddr, uint8_t addrLen, + const struct StationInfo *info); + +/** + * @brief Reports a station deletion event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param macAddr Indicates the pointer to the MAC address of the station. This parameter cannot be null. + * @param addrLen Indicates the length of the MAC address of the station. The length is fixed to six bytes. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventDelSta(struct NetDevice *netdev, const uint8_t *macAddr, uint8_t addrLen); + +/** + * @brief Reports a scanned BSS event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param wiphy Indicates the pointer to the physical layer of the wireless network. This parameter cannot be null. + * @param channel Indicates the pointer to the channel information. This parameter cannot be null. + * @param bssInfo Indicates the pointer to the BSS information. This parameter cannot be null. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventInformBssFrame(const struct NetDevice *netdev, struct Wiphy *wiphy, + const struct Ieee80211Channel *channel, const struct ScannedBssInfo *bssInfo); + +/** + * @brief Reports a scanning completion event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param status Indicates the scanning completion status. Value 0 indicates that the scanning is successful, + * and other values indicate that the scanning fails. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventScanDone(const struct NetDevice *netdev, WifiScanStatus status); + +/** + * @brief Reports a connection result event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param result Indicates the pointer to the connection result. This parameter cannot be null. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventConnectResult(const struct NetDevice *netdev, const struct ConnetResult *result); + +/** + * @brief Reports a disconnection event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param reason Indicates the reason for disconnection. + * @param ie Indicates the pointer to the deauth/disassoc frame IE. + * @param ieLen Indicates the length of the deauth/disassoc IE. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventDisconnected(const struct NetDevice *netdev, uint16_t reason, const uint8_t *ie, uint32_t len); + +/** + * @brief Reports a transmission management status event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param buf Indicates the pointer to the transmission management frame. This parameter cannot be null. + * @param len Indicates the length of the transmission management frame. + * @param ack Indicates whether the transmission management frame is acknowledged. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventMgmtTxStatus(const struct NetDevice *netdev, const uint8_t *buf, size_t len, uint8_t ack); + +/** + * @brief Reports a receive management status event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param freq Indicates the frequency of receiving management frame. + * @param sigMbm Indicates the signal strength (in dBm). + * @param buf Indicates the pointer to the receive management frame. This parameter cannot be null. + * @param len Indicates the length of the receive management frame. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventRxMgmt(const struct NetDevice *netdev, int32_t freq, int32_t sigMbm, + const uint8_t *buf, size_t len); + +/** + * @brief Reports a CSA channel switching event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param freq Indicates the frequency of the channel. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventCsaChannelSwitch(const struct NetDevice *netdev, int32_t freq); + +/** + * @brief Reports a timeout disconnection event. + * + * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * + * @return Returns 0 if the event is reported successfully; returns -1 otherwise. + * + * @since 1.0 */ +int32_t HdfWifiEventTimeoutDisconnected(const struct NetDevice *netdev); + +/** + * @brief Reports the event of receiving the EAPOL frame and notifies WPA to read the EAPOL frame. + * + * @param name Indicates the pointer to the network port name, for example, wlan0. + * @param context Indicates the pointer to the context. This parameter is reserved. + * + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * + * @since 1.0 + */ +int32_t HdfWifiEventEapolRecv(const char *name, void *context); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* __HDF_WIFI_EVENT_H__ */ + diff --git a/include/wifi/hdf_wifi_product.h b/include/wifi/hdf_wifi_product.h new file mode 100755 index 00000000..ad3d0a4f --- /dev/null +++ b/include/wifi/hdf_wifi_product.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_wifi_product.h + * + * @brief Declares the data structure of the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDFLITE_HDF_WIFI_PRODUCT_H +#define HDFLITE_HDF_WIFI_PRODUCT_H + +#include "wifi_module.h" +#include "hdf_device_desc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Defines the WLAN module. + * + * @since 1.0 + */ +struct HdfWifiProductData { + char product_name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< WLAN module name, which contains a maximum of 10 bytes */ + char state; /**< WLAN module state */ + struct WifiModule *module; /**< Structure of the WLAN module */ + struct HdfDeviceObject *device; /**< Structure of the Device Object */ +}; + +/** + * @brief Obtains the data structure of the WLAN module. + * + * @return Returns the pointer to the data structure of the WLAN module. For details, see {@link HdfWifiProductData}. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfWifiProductData *HdfWifiGetProduct(void); + +#ifdef __cplusplus +} +#endif +#endif // HDFLITE_HDF_WIFI_PRODUCT_H diff --git a/include/wifi/net_device.h b/include/wifi/net_device.h new file mode 100755 index 00000000..7165154a --- /dev/null +++ b/include/wifi/net_device.h @@ -0,0 +1,690 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file net_device.h + * + * @brief Defines WLAN network device interfaces. + * + * This module provides network device operations for driver development. + * The operations are as follows: + *
  • Initializes, adds, obtains, and deletes a network device.
  • + *
  • Reports network data, informs the network layer of the data link layer status, sets IP addresses, + * and starts or stops Dynamic Host Configuration Protocol (DHCP).
  • + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_NET_DEVICE_MODULE_H +#define HDF_NET_DEVICE_MODULE_H +#include +#include +#include "hdf_netbuf.h" +#include "hdf_log.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef IFNAMSIZ +#define IFNAMSIZ 16 +#endif + +/** + * @brief Indicates a 6-byte MAC address. + */ +#define MAC_ADDR_SIZE 6 +/** + * @brief Indicates that the network port is working. + */ +#define NET_DEVICE_IFF_RUNNING IFF_RUNNING +/** + * @brief Indicates Reverse Address Resolution Protocol (RARP). + */ +#define ETHER_TYPE_RARP 0x8035 +/** + * @brief Indicates Port Access Entity (PAE). + */ +#define ETHER_TYPE_PAE 0x888e +/** + * @brief Indicates Internet Protocol (IP). + */ +#define ETHER_TYPE_IP 0x0800 +/** + * @brief Indicates AppleTalk Address Resolution Protocol (AARP). + */ +#define ETHER_TYPE_AARP 0x80f3 +/** + * @brief Indicates Internetwork Packet Exchange (IPX). + */ +#define ETHER_TYPE_IPX 0x8137 +/** + * @brief Indicates Address Resolution Protocol (ARP). + */ +#define ETHER_TYPE_ARP 0x0806 +/** + * @brief Indicates Internet Protocol version 6 (IPv6). + */ +#define ETHER_TYPE_IPV6 0x86dd +/** + * @brief Indicates Tunneled Direct Link Setup (TDLS). + */ +#define ETHER_TYPE_TDLS 0x890d +/** + * @brief Indicates Virtual Local Area Network (VLAN). + */ +#define ETHER_TYPE_VLAN 0x8100 +/** + * @brief Indicates WLAN Authentication and Privacy Infrastructure (WAPI). + */ +#define ETHER_TYPE_WAI 0x88b4 +/** + * @brief Indicates Link Layer Topology Discovery (LLTD). + */ +#define ETHER_LLTD_TYPE 0x88D9 +/** + * @brief Indicates 802.1x network port authentication. + */ +#define ETHER_ONE_X_TYPE 0x888E +/** + * @brief Indicates a tunnel protocol. + */ +#define ETHER_TUNNEL_TYPE 0x88bd +/** + * @brief Indicates the point-to-point discovery type. + */ +#define ETHER_TYPE_PPP_DISC 0x8863 +/** + * @brief Indicates the point-to-point session discovery type. + */ +#define ETHER_TYPE_PPP_SES 0x8864 +/** + * @brief Indicates IPv6 over Low Power Wireless Personal Area Networks (6LoWPANs). + */ +#define ETHER_TYPE_6LO 0xa0ed + +/** + * @brief Indicates the Transmission Control Protocol (TCP). + */ +#define TCP_PROTOCAL 6 +/** + * @brief Indicates the User Datagram Protocol (UDP). + */ +#define UDP_PROTOCAL 17 +/** + * @brief Indicates the shift in the priority for an IP address. + */ +#define IP_PRI_SHIFT 5 + +/** + * @brief Indicates the source port number of DHCP. + */ +#define DHCP_UDP_SRC_PORT 68 +/** + * @brief Indicates the destination port number of DHCP. + */ +#define DHCP_UDP_DES_PORT 67 + +/** + * @brief Enumerates network interface categories, including lightweight OS and rich OS. + */ +typedef enum { + LITE_OS, /**< Lightweight OS */ + RICH_OS /**< Rich OS */ +} NetIfCategory; + +/** + * @brief Enumerates network interface states, including online and offline. + */ +typedef enum { + NETIF_DOWN, /**< Network interface offline */ + NETIF_UP /**< Network interface online */ +} NetIfStatus; + +/** + * @brief Enumerates network link layer states, including online and offline. + */ +typedef enum { + NETIF_LINK_DOWN, /**< Data link offline */ + NETIF_LINK_UP /**< Data link online */ +} NetIfLinkStatus; + +/** + * @brief Enumerates data link types, including Ethernet and WLAN. + */ +typedef enum { + ETHERNET_LINK = 1, /**< Ethernet */ + WIFI_LINK = 801 /**< WLAN */ +} NetLinkType; + +/** + * @brief Enumerates data processing results, including continuing processing, processing completed, and error. + */ +typedef enum { + PROCESSING_CONTINUE, /**< Continuing processing */ + PROCESSING_COMPLETE, /**< Processing completed */ + PROCESSING_ERROR /**< Error */ +} ProcessingResult; + +/** + * @brief Enumerates data sending results, including sending succeeded, other data being sent at the link layer, + * and data link layer being locked. + */ +typedef enum { + NETDEV_TX_OK = 0x00, /**< Sending succeeded */ + NETDEV_TX_BUSY = 0x10, /**< Other data being sent at the link layer */ + NETDEV_TX_LOCKED = 0x20, /**< Data link layer being locked */ +} NetDevTxResult; + +/** + * @brief Enumerates 802.11 network port types, including AP, STA, and P2P. + */ +typedef enum { + PROTOCOL_80211_IFTYPE_UNSPECIFIED, /**< Unspecified */ + PROTOCOL_80211_IFTYPE_ADHOC, /**< Ad hoc network */ + PROTOCOL_80211_IFTYPE_STATION, /**< Workstation */ + PROTOCOL_80211_IFTYPE_AP, /**< Access point */ + PROTOCOL_80211_IFTYPE_AP_VLAN, /**< Virtual access point */ + PROTOCOL_80211_IFTYPE_WDS, /**< Wireless distributed system */ + PROTOCOL_80211_IFTYPE_MONITOR, /**< Listening */ + PROTOCOL_80211_IFTYPE_MESH_POINT, /**< Mesh network */ + PROTOCOL_80211_IFTYPE_P2P_CLIENT, /**< P2P client */ + PROTOCOL_80211_IFTYPE_P2P_GO, /**< P2P group owner */ + PROTOCOL_80211_IFTYPE_P2P_DEVICE, /**< P2P device */ + PROTOCOL_80211_IFTYPE_NUM, /**< Number of network ports */ + PROTOCOL_80211_IFTYPE_MAX = PROTOCOL_80211_IFTYPE_NUM - 1 /**< Maximum number of 802.11 network port types */ +} Protocol80211IfType; + +/** + * @brief Enumerates network device errors, including common errors and errors in adding network devices to LwIP. + */ +typedef enum { + COMMON_ERROR = 1, /**< Common errors */ + ADD_LWIP_ERROR /**< Errors in adding network devices to LwIP */ +} NetdeviceError; + +/** + * @brief Defines the Ethernet header information of a data frame, including the destination address, source address, + * and Ethernet type. + * + * @since 1.0 + */ +struct EtherHeader { + uint8_t etherDhost[MAC_ADDR_SIZE]; /**< Destination address {@link MAC_ADDR_SIZE} */ + uint8_t etherShost[MAC_ADDR_SIZE]; /**< Source address {@link MAC_ADDR_SIZE} */ + uint16_t etherType; /**< Ethernet type, such as 0x8035 (RARP), 0x888e (EAPOL), PAE/802.1x, + * 0x0800 (IP), 0x86dd (IPV6), and 0x0806 (ARP) + */ +}; + +/** + * @brief Defines the IP header information of a data frame, including the version number, service type, + * and total length. + * + * @since 1.0 + */ +struct IpHeader { + uint8_t versionAndHl; /**< Version and header length */ + uint8_t tos; /**< Service type + * bit7~bit5 | bit4 | bit3 | bit2 | bit1 | bit0 + * ----------|-------|-------|-------|---------|----- + * Priority | Delay | Throughput | Reliability | Transmission Cost | Reservation + */ + uint16_t totLen; /**< Total length of an IP data packet */ + uint16_t id; /**< Each data packet sent by the host */ + uint16_t fragInfo; /**< Fragmentation information */ + uint8_t ttl; /**< Generation time */ + uint8_t protocol; /**< Protocol, such as 1 (ICMP), 2 (IGMP), 6 (TCP), 17 (UDP), and 89 (OSPF) */ + uint16_t check; /**< Header check */ + uint32_t sAddr; /**< Source address */ + uint32_t dAddr; /**< Destination address */ +}; + +/** + * @brief Defines the UDP header information of a data frame, including the source port number and destination + * port number. + * + * @since 1.0 + */ +struct UdpHeader { + uint16_t source; /**< Source port number */ + uint16_t dest; /**< Destination port number */ + uint16_t len; /**< Length of a data packet */ + uint16_t check; /**< Header check */ +}; + +/** + * @brief Defines the TCP header information of a data frame, including the source port number and destination + * port number. + * + * @since 1.0 */ +struct TcpHeader { + uint16_t sPort; /**< Source port number */ + uint16_t dPort; /**< Destination port number */ + uint32_t seqNum; /**< Sequence number */ + uint32_t ackNum; /**< Acknowledgement number */ + uint8_t offset; /**< Header length */ + uint8_t flags; /**< Flags */ + uint16_t window; /**< Window size */ + uint16_t check; /**< Checksum */ + uint16_t urgent; /**< Urgent pointer */ +}; + +/** + * @brief Defines an IPv4 address. + * + * @since 1.0 + */ +typedef struct { + uint32_t addr; /**< IPv4 address */ +} IpV4Addr; + +/** + * @brief Defines a network device notification, including an IP address and the notification type. + * + * @since 1.0 + */ +typedef struct { + uint32_t ipAddr; /**< IP address */ + uint32_t notifyType; /**< Notification type (reserved) */ +} NetDevNotify; + +/** + * @brief Defines the network port type, for example, the WLAN network port. + * + * @since 1.0 + */ +typedef union { + Protocol80211IfType wlanType; /**< WLAN network port type: AP or STA */ +} IfType; + +struct NetDevStats { + uint32_t rxPackets; /**< Total number of received packets */ + uint32_t txPackets; /**< Total number of transmitted packets */ + uint32_t rxBytes; /**< Total number of received bits */ + uint32_t txBytes; /**< Total number of transmitted bits */ + uint32_t rxErrors; /**< Number of received error packets */ + uint32_t txErrors; /**< Transmitted error packets */ + uint32_t rxDropped; /**< Packets that are dropped after being received */ + uint32_t txDropped; /**< Packets dropped before transmission*/ +}; + +/** + * @brief Defines ioctrl data. + * + * @since 1.0 + */ +typedef struct { + uint32_t fake; /**< magic field */ + uint8_t *ifrData; /**< Data pointer */ +} IfReq; + +/** + * @brief Defines a network device, including the network interface category and name, and network port type. + * + * @since 1.0 + */ +typedef struct NetDevice { + NetIfCategory netifCateg; /**< Network interface category {@link NetIfCategory} */ + char name[IFNAMSIZ]; /**< Network device name {@link IFNAMSIZ} */ + NetLinkType LinkLayerType; /**< Data link layer type */ + IfType funType; /**< Network port type */ + char macAddr[MAC_ADDR_SIZE]; /**< MAC address {@link MAC_ADDR_SIZE} */ + uint32_t flags; /**< Network port status */ + uint32_t mtu; /**< Maximum transmission unit */ + int32_t watchdogTime; /**< Watchdog duration */ + uint32_t lastRxTime; /**< Last time when data is received */ + uint16_t hardHeaderLen; /**< Header length */ + uint16_t neededHeadRoom; /**< Length reserved for the header in netbuff{@link NetBuf} */ + uint16_t neededTailRoom; /**< Length reserved for the tail in netbuff{@link NetBuf} */ + uint8_t addrLen; /**< MAC address length */ + void *mlPriv; /**< Private structure for the driver */ + struct WirelessDev *ieee80211Ptr; /**< Pointer to a wireless device */ + void *specialProcPriv; /**< Private structure for data processing */ + struct NetDeviceInterFace *netDeviceIf; /**< Network device interface */ + struct NetDevice *owner; /**< Network device */ + struct NetDevStats stats; /**< Network statistics */ +} NetDevice; + +/** + * @brief Defines interfaces that need to be implemented externally by network devices, including initializing, + * opening, and closing a network device. + * + * @since 1.0 + */ +struct NetDeviceInterFace { + int32_t (*init)(struct NetDevice *netDev); /**< Initializes a network device to be added. */ + void (*deInit)(struct NetDevice *netDev); /**< Deinitializes a network device to be delete. */ + int32_t (*open)(struct NetDevice *netDev); /**< Opens the data link layer. */ + int32_t (*stop)(struct NetDevice *netDev); /**< Closes the data link layer. */ + NetDevTxResult (*xmit)(struct NetDevice *netDev, struct NetBuf *netBuff); /**< Sends data. */ + int32_t (*ioctl)(struct NetDevice *netDev, IfReq *req, int32_t cmd); /**< Used for the control command word. */ + int32_t (*setMacAddr)(struct NetDevice *netDev, void *addr); /**< Sets the MAC address. */ + struct NetDevStats *(*getStats)(struct NetDevice *netDev); /**< Obtains the statistics. */ + void (*setNetIfStatus)(struct NetDevice *netDev, NetIfStatus status); /**< Sets the network port status. */ + uint16_t (*selectQueue)(struct NetDevice *netDev, struct NetBuf *netBuff);/**< Selects a priority queue. */ + uint32_t (*netifNotify)(struct NetDevice *netDev, NetDevNotify *notify); /**< Notifies the network port status. */ + int32_t (*changeMtu)(struct NetDevice *netDev, int32_t newMtu); /**< Changes the maximum number of + * transmission units. + */ + ProcessingResult (*specialEtherTypeProcess)(const struct NetDevice *netDev, struct NetBuf *buff); + /**< Performs private processing without + * involving network-layer data. + */ +}; + +/** + * @brief Initializes a network device to obtain its instance. + * + * @param ifName Indicates the pointer to the network device name. + * @param len Indicates the length of the network device name. + * @param ifCategory Indicates the network port category. + * + * @return Returns the structure {@link NetDevice} for the initialized network device if the operation is successful; + * returns NULL if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory ifCategory); + +/** + * @brief Deletes a network device. + * + * @param netDevice Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the operation is successful; returns a negative value representing {@link HDF_STATUS} + * if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetDeviceDeInit(struct NetDevice *netDevice); + +/** + * @brief Adds a network device to a protocol stack. + * + * @param netDevice Indicates the pointer to the network device structure obtained during initialization. + * @param netDevice Indicates the network port type, as enumerated in {@link Protocol80211IfType}. + * + * @return Returns 0 if the operation is successful; returns a negative value representing {@link HDF_STATUS} + * if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetDeviceAdd(struct NetDevice *netDevice, Protocol80211IfType ifType); + +/** + * @brief Deletes a network device from a protocol stack. + * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained during + * initialization. + * + * @return Returns 0 if the operation is successful; returns a negative value representing {@link HDF_STATUS} + * if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetDeviceDelete(struct NetDevice *netDevice); + +/** + * @brief Obtains the initialized network device instance by a specified device name. + * + * @param name Indicates the pointer to the network device name. + * + * @return Returns the network device structure {@link NetDevice} matching the network device name if the operation is + * successful; returns NULL if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +struct NetDevice *NetDeviceGetInstByName(const char *name); + +/** + * @brief Checks whether there are working devices among the added network devices. + * + * @return Returns true if the added network devices are working; returns false if none of the added + * network devices is working. + * + * @since 1.0 + * @version 1.0 */ +bool NetDeviceIsAnyInstRunning(void); + +/** + * @brief Checks whether a specified network device is working. + * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained during + * initialization. + * + * @return Returns true if the specified network device is working; returns false otherwise. + * + * @since 1.0 + * @version 1.0 + */ +bool NetDeviceIsInstRunning(const struct NetDevice *netDevice); + +/** + * @brief Obtains the number of added network devices. + * + * @return Returns the number of added network devices. + * + * @since 1.0 + * @version 1.0 + */ +uint32_t NetDevGetRegisterCount(void); + +/** + * @brief Obtains the maximum number of network devices that can be registered with this system at the same time. + * + * @return Returns the maximum number of network devices. + * + * @since 1.0 + * @version 1.0 + */ +uint32_t NetDeviceGetCap(void); + +/** + * @brief Obtains a network device instance based on the index number. + * + * @param index Indicates the index number. + * + * @return Returns the network device structure {@link NetDevice} if the operation is successful; returns NULL + * if the operation fails. + * + * @since 1.0 + * @version 1.0 + */ +struct NetDevice *NetDeviceGetInstByIndex(uint32_t index); + +/** + * @brief Sets an IP address, mask, and gateway. + * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained during + * initialization. + * @param ipAddr Indicates the IP address to set. + * @param netMask Indicates the mask to set. + * @param gw Indicates the gateway to set. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, const IpV4Addr *netMask, + const IpV4Addr *gw); + +/** + * @brief Notifies the network layer of the network port state. + * + * @param netDevice Indicates the pointer to the network device obtained during initialization. + * @paramstatus Indicates the network port state, as enumerated in {@link NetIfSatus}. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfSetStatus(const struct NetDevice *netDevice, NetIfStatus status); + +/** + * @brief Notifies the network layer of the data link layer status. + * + * @param netDevice Indicates the pointer to the network device obtained during initialization. + * @param status status Indicates the data link layer status, as enumerated in {@link NetIfLinkSatus}. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfSetLinkStatus(const struct NetDevice *netDevice, NetIfLinkStatus status); + +/** + * @brief Transfers the input data packets from the network side to a protocol stack. + * + * @param buff Indicates the network-side data, in Ether format. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfRx(const struct NetDevice *netDevice, struct NetBuf *buff); + +/** + * @brief Transfers data packets from the network side to a protocol stack in an interrupt processing thread. + * + * @param buff Indicates the network-side data, in Ether format. + * + * @return Returns 0 if the operation is successful; returns a non-zero value {@link HDF_STATUS} if the + * operation fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfRxNi(const struct NetDevice *netDevice, struct NetBuf *buff); + +/** + * @brief Starts the DHCP server. + * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained + * during initialization. + * @param beginIp Indicates the IP address to start. + * @param ipNum Indicates the number of IP addresses. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfDhcpsStart(const struct NetDevice *netDevice, char *ip, u16_t ipNum); + +/** + * @brief Stops the DHCP server. + * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained + * during initialization. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfDhcpsStop(const struct NetDevice *netDevice); + +/** + * @brief Starts the DHCP client of a specified network device. + * + * @param netDevice Indicates the pointer to the network device obtained during initialization. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfDhcpStart(const struct NetDevice *netDevice); + +/** + * @brief Stops the DHCP client of a specified network device. + * + * @param netDevice Indicates the pointer to the network device obtained during initialization. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfDhcpStop(const struct NetDevice *netDevice); + +/** + * @brief Obtains the DHCP negotiation status of a specified network device. + * + * @param netDevice Indicates the pointer to the network device obtained during initialization. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfDhcpIsBound(const struct NetDevice *netDevice); + +#define GET_NET_DEV_FLAGS(dev) ((dev)->flags) +#define GET_NET_DEV_HEAD_ROOM(dev) ((dev)->neededHeadRoom) +#define GET_NET_DEV_TAIL_ROOM(dev) ((dev)->neededTailRoom) +#define GET_NET_DEV_MTU(dev) ((dev)->mtu) +#define GET_NET_DEV_WIRELESS(dev) ((dev)->ieee80211Ptr) +#define GET_NET_DEV_PRIV(dev) ((dev)->mlPriv) +#define GET_NET_DEV_MAC_ADDR(dev) ((dev)->macAddr) +#define GET_NET_DEV_IF(dev) ((dev)->netDeviceIf) +#define GET_NET_DEV_LAST_RX_TIME(dev) ((dev)->lastRxTime) +#define GET_NET_DEV_OWNER(dev) ((dev)->owner) +#define GET_NET_DEV_WATCHDOG_TIME(dev) ((dev)->watchdogTime) +#define GET_NET_DEV_SPECIAL_PROC_PRIV(dev) ((dev)->specialProcPriv) +#ifdef __cplusplus +} +#endif + +#endif /* HDF_NET_DEVICE_MODULE_H */ diff --git a/include/wifi/wifi_inc.h b/include/wifi/wifi_inc.h new file mode 100755 index 00000000..d4288880 --- /dev/null +++ b/include/wifi/wifi_inc.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file wifi_inc.h + * + * @brief Describes the data structure of WLAN features and bus. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDFLITE_WIFI_MODULE_INC_H +#define HDFLITE_WIFI_MODULE_INC_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct WifiModule; +struct WifiFeature; +struct WifiFeatureList; +struct HdfWifiChipData; +struct BusDev; + +/** + * @brief Indicates the length of the name of a WLAN module or feature. + * + * The name of a WLAN module or feature cannot contain more than 10 characters; otherwise, the name will be truncated + * and cannot be identified. + * + * @since 1.0 + */ +#define MAX_WIFI_COMPONENT_NAME_LEN 10 + +/** + * @brief Enumerates feature types of a WLAN module. + * + * You can query and register a feature or bind a feature to a WLAN module based on the feature type. + * + * @since 1.0 + */ +enum WifiMainFeatureType { + HDF_WIFI_FEATURE_BASE, /**< Base feature */ + HDF_WIFI_FEATURE_AP, /**< AP */ + HDF_WIFI_FEATURE_STA, /**< Station */ + HDF_WIFI_FEATURE_P2P, /**< Peer-to-peer (P2P) */ + HDF_WIFI_FEATURE_NAN, /**< Neighbor Awareness Networking (NAN) */ + HDF_WIFI_FEATURE_RTT, /**< Round Trip Time (RTT) */ + HDF_WIFI_FEATURE_NUM = 10 /**< Maximum number of features */ +}; + +/** + * @brief Enumerates bus types of a WLAN module. + * + * @since 1.0 + */ +enum WifiBusType { + BUS_SDIO, /**< Secure Digital Input and Output (SDIO) */ + BUS_USB, /**< Universal Serial Bus (USB) */ +}; + +#ifdef __cplusplus +} +#endif + +#endif // HDFLITE_WIFI_MODULE_INC_H + diff --git a/include/wifi/wifi_mac80211_ops.h b/include/wifi/wifi_mac80211_ops.h new file mode 100755 index 00000000..14873fd7 --- /dev/null +++ b/include/wifi/wifi_mac80211_ops.h @@ -0,0 +1,481 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file wifi_mac80211_ops.h + * + * @brief Declares Media Access Control (MAC) APIs and functions related to control flows. + * + * This file declares APIs for scanning, connection, disconnection, and mode conversion, as well as data + * structures of the parameters of these APIs. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef _WIFI_MAC80211_OPS_H_ +#define _WIFI_MAC80211_OPS_H_ + +#include "net_device.h" +#include "hdf_wifi_cmd.h" + +#define WLAN_MAC_ADDR_LEN 6 +/** + * @brief Enumerates setting types of MAC addresses. + * + * @since 1.0 + */ +enum MacSetType { + MAC_BEACON_SET = 0, /**< Setting a beacon MAC address */ + MAC_BEACON_ADD = 1, /**< Adding a beacon MAC address */ +}; + +/** + * @brief Describes a key. + * + * @since 1.0 + */ +struct KeyParams { + uint8_t *key; /**< Key content */ + uint8_t *seq; /**< Content of a Temporal Key Integrity Protocol (TKIP) or Counter Mode Cipher Block Chaining + * Message Authentication Code Protocol (CCMP) key + */ + int32_t keyLen; /**< Key length */ + int32_t seqLen; /**< Length of a TKIP or CCMP key */ + uint32_t cipher; /**< Cipher suite */ +}; + +/** + * @brief Enumerates frequency bands. + * + * @since 1.0 + */ +enum Ieee80211Band { + IEEE80211_BAND_2GHZ, /**< 2.4 GHz */ + IEEE80211_BAND_5GHZ, /**< 5 GHz */ + IEEE80211_NUM_BANDS /**< Reserved */ +}; + +#define IEEE80211_CHANNEL_RESV 3 +/** + * @brief Describes a communication channel. + * + * @since 1.0 + */ +struct Ieee80211Channel { + enum Ieee80211Band band; /**< Frequency band, either 2.4 GHz or 5 GHz */ + uint16_t centerFreq; /**< Center frequency */ + uint16_t hwValue; /**< Hardware information */ + uint32_t flags; /**< WLAN channel flag */ + int32_t maxAntennaGain; /**< Maximum antenna gain, in dBi */ + int32_t maxPower; /**< Maximum transmit power, in dBm */ + int8_t beaconFound; /**< When a beacon frame is found in this channel */ + uint8_t resv[IEEE80211_CHANNEL_RESV]; /**< Reserved field */ + uint32_t origFlags; /**< Channel flags */ + int32_t origMag; /**< Reserved field */ + int32_t origMpwr; /**< Reserved field */ +}; + +#define IEEE80211_RATE_RESV 2 +/** + * @brief Describes the IEEE 802.11 rate. + * + * @since 1.0 + */ +struct Ieee80211Rate { + uint32_t flags; /**< Rate flag */ + uint16_t bitrate; /**< Bit rate, in 100 kbit/s */ + uint16_t hwValue; /**< Hardware information */ + uint16_t hwValueShort; /**< Hardware information specified when a short preamble is used */ + uint8_t rsv[IEEE80211_RATE_RESV]; /**< Reserved field */ +}; + +#define IEEE80211_HT_MCS_MASK_LEN 10 +#define IEEE80211_MACINFO_RESV 3 +/** + * @brief Describes IEEE 802.11 Modulation and Coding Scheme (MCS) information. + * + * @since 1.0 + */ +struct Ieee80211McsInfo { + uint8_t rxMask[IEEE80211_HT_MCS_MASK_LEN]; /**< Mask for receiving data */ + uint16_t rxHighest; /**< Maximum rate for receiving data */ + uint8_t txParams; /**< Parameters for sending data */ + uint8_t reserved[IEEE80211_MACINFO_RESV]; /**< Reserved field */ +}; + +#define IEEE80211_STAHTCAP_RESV 3 +/** + * @brief Describes the IEEE 802.11 high-throughput (HT) capability. + * + * @since 1.0 + */ +struct Ieee80211StaHtCap { + uint16_t cap; /**< HT capability table provided in 802.11n */ + uint8_t htSupported; /**< Whether the station supports HT */ + uint8_t ampduFactor; /**< Maximum length of an aggregated MAC Protocol Data Unit (A-MPDU) */ + uint8_t ampduDensity; /**< Minimum MPDU start spacing */ + uint8_t aucRsv[IEEE80211_STAHTCAP_RESV]; /**< Reserved field */ + struct Ieee80211McsInfo mcs; /**< MCS rate */ +}; + +/** + * @brief Describes IEEE 802.11 band information. + * + * @since 1.0 + */ +struct Ieee80211SupportedBand { + struct Ieee80211Channel *channels; /**< An array of supported channels */ + struct Ieee80211Rate *bitrates; /**< An array of supported bit rates */ + enum Ieee80211Band band; /**< Band matching this data structure description */ + int32_t nChannels; /**< Length of the array of supported channels */ + int32_t nBitrates; /**< Length of the array of supported bit rates */ + struct Ieee80211StaHtCap htCap; /**< HT capability */ +}; + +#define WIPHY_RSV_SIZE 2 +#define WIPHY_PRIV_SIZE 4 +/** + * @brief Describes a wiphy device. + * + * @since 1.0 + */ +struct Wiphy { + uint8_t permAddr[WLAN_MAC_ADDR_LEN]; /**< Permanent MAC address of the wiphy device. For its length, + * see {@link WLAN_MAC_ADDR_LEN}. + */ + uint8_t addrMask[WLAN_MAC_ADDR_LEN]; /**< MAC address mask of the wiphy device. If the device supports multiple + * virtual MAC addresses, the bit whose value is 1 in the mask + * represents a variable part of the MAC address. + */ + uint32_t flags; /**< Wiphy device attributes */ + uint8_t signalType; /**< Signal type */ + uint8_t maxScanSsids; /**< Maximum number of scanned service set identifiers (SSIDs) */ + uint16_t interfaceModes; /**< Bitmask of an API type that is valid for the wiphy device */ + uint16_t maxScanIeLen; /**< Maximum SSID length */ + uint8_t aucRsv[WIPHY_RSV_SIZE]; /**< Manual alignment of data structures */ + int32_t nCipherSuites; /**< Number of supported cipher suites */ + const uint32_t *cipherSuites; /**< Supported cipher suites */ + uint32_t fragThreshold; /**< Fragment threshold */ + uint32_t rtsThreshold; /**< Request To Send (RTS) threshold */ + struct Ieee80211SupportedBand *bands[IEEE80211_NUM_BANDS]; + /**< Supported bands */ + uint8_t priv[WIPHY_PRIV_SIZE]; /**< Reserved field */ +}; + +#define IEEE80211_MAX_SSID_LEN 32 +/** + * @brief Describes an SSID. + * + * @since 1.0 + */ +struct WifiSsid { + uint8_t ssid[IEEE80211_MAX_SSID_LEN]; /**< SSID content, which contains a maximum of 32 bytes */ + uint8_t ssidLen; /**< SSID length */ +}; + +/** + * @brief Enumerates channel types. + * + * @since 1.0 + */ +enum WifiChannelType { + WIFI_CHAN_NO_HT, /**< non-HT channel */ + WIFI_CHAN_HT20, /**< 20 MHz HT channel */ + WIFI_CHAN_HT40MINUS, /**< 40 MHz minus HT channel (The channel is formed by two 20 MHz HT channels, one as + * the main channel and the other as the auxiliary channel. The center frequency of the main + * channel is lower than that of the auxiliary channel.) + */ + WIFI_CHAN_HT40PLUS /**< 40 MHz plus HT channel (The channel is formed by two 20 MHz HT channels, one as + * the main channel and the other as the auxiliary channel. The center frequency of the main + * channel is higher than that of the auxiliary channel.) + */ +}; + +/** + * @brief Describes a communication channel. + * + * @since 1.0 + */ +struct ChannelDef { + struct Ieee80211Channel *chan; /**< Channel information */ + enum WifiChannelType width; /**< Bandwidth */ + int32_t centerFreq1; /**< Center frequency 1 */ + int32_t centerFreq2; /**< Center frequency 2 */ +}; + +#define WIRELESS_DEV_RESV_SIZE 3 +/** + * @brief Describes a wireless device. + * + * @since 1.0 + */ +struct WirelessDev { + struct NetDevice *netdev; /**< Network device */ + struct Wiphy *wiphy; /**< Wiphy device */ + uint8_t iftype; /**< API type */ + uint8_t resv[WIRELESS_DEV_RESV_SIZE]; /**< Reserved field */ + struct ChannelDef presetChandef; /**< Channel information */ +}; + +#define MAX_SCAN_CHANNELS 14 +#define SCAN_REQUEST_RESV_SIZE 2 +/** + * @brief Describes scan request parameters. + * + * @since 1.0 + */ +struct WifiScanRequest { + struct WifiSsid *ssids; /**< SSIDs to scan for */ + uint32_t nSsids; /**< Number of SSIDs to scan for */ + uint32_t nChannels; /**< Number of channels to scan for */ + uint32_t ieLen; /**< IEEE 802.11 buffer length */ + struct Wiphy *wiphy; /**< A specified wiphy device to scan for */ + struct NetDevice *dev; /**< A specified network device to scan for */ + struct WirelessDev *wdev; /**< A specified wireless device to scan for */ + uint8_t aborted; /**< Whether to abort the scan */ + uint8_t prefixSsidScanFlag; /**< Reserved field */ + uint8_t resv[SCAN_REQUEST_RESV_SIZE]; /**< Reserved field */ + uint8_t *ie; /**< IEEE 802.11 buffer */ + struct Ieee80211Channel *channels[MAX_SCAN_CHANNELS]; /**< Channels to scan for. For details, + * see {@link MAX_SCAN_CHANNELS}. + */ +}; + +#define NL80211_MAX_NR_CIPHER_SUITES 5 +#define NL80211_MAX_NR_AKM_SUITES 2 +/** + * @brief Describes cryptography settings. + * + * @since 1.0 + */ +struct CryptoSettings { + uint32_t wpaVersions; /**< WPA version */ + uint32_t cipherGroup; /**< Cipher group */ + int32_t n_ciphersPairwise; /**< Number of unicast ciphers supported by the access point (AP) */ + uint32_t ciphersPairwise[NL80211_MAX_NR_CIPHER_SUITES]; + /**< Unicast cipher suite. For details, see {@link NL80211_MAX_NR_CIPHER_SUITES}. */ + int32_t n_akmSuites; /**< Number of authentication and key management (AKM) suites */ + uint32_t akmSuites[NL80211_MAX_NR_AKM_SUITES]; + /**< AKM suite data. For details, see {@link NL80211_MAX_NR_AKM_SUITES}. */ + uint16_t controlPortEthertype; /**< Data can be transmitted over an unauthenticated port. */ + int8_t controlPort; /**< Whether the user space control port is authorized. The value true + * indicates that the user space control port is unauthorized. + */ + int8_t controlPortNoEncrypt; /**< Whether to encrypt frames transmitted over the control port. + * The value 1 indicates that the frames are not encrypted. + */ +}; + +#define ETH_ADDR_LEN 6 +/** + * @brief Describes the device MAC address. + * + * @since 1.0 + */ +struct MacAddress { + uint8_t addr[ETH_ADDR_LEN]; /**< Device MAC address */ +}; + +#define WIFI_CONNECT_PARM_RESV_SIZE 3 +/** + * @brief Describes parameters for a connection request. + * + * @since 1.0 + */ +typedef struct WifiConnectParams { + struct Ieee80211Channel *channel; /**< Connection channel. If this parameter is not specified, the connection + * channel is automatically obtained from the scan result. + */ + uint8_t *bssid; /**< AP basic service set identifier (BSSID). If this parameter is not + * specified, the AP BSSID is automatically obtained from the scan result. + */ + uint8_t *ssid; /**< SSID */ + uint8_t *ie; /**< IEEE 802.11 information required for the connection */ + uint32_t ssidLen; /**< SSID length */ + uint32_t ieLen; /**< IEEE 802.11 length */ + struct CryptoSettings crypto; /**< Cryptography information */ + const uint8_t *key; /**< Wired Equivalent Privacy (WEP) key used for Shared Key + * Authentication (SKA) + */ + uint8_t authType; /**< Authorization type */ + uint8_t privacy; /**< Whether to use a privacy-enabled AP */ + uint8_t keyLen; /**< Key length */ + uint8_t keyIdx; /**< Index of the WEP key used for SKA */ + uint8_t mfp; /**< Whether to enable Management Frame Protection (MFP) */ + uint8_t aucResv[WIFI_CONNECT_PARM_RESV_SIZE]; + /**< Reserved field */ +} WifiConnectParams; + +/** + * @brief Describes virtual API parameters. + * + * @since 1.0 + */ +struct VifParams { + int32_t use4Addr; /**< Whether to use a frame containing four addresses */ + uint8_t *macAddr; /**< MAC address */ +}; + +/** + * @brief Describes parameters for canceling a connection. + * + * @since 1.0 + */ +struct StationDelParameters { + const uint8_t *mac; /**< MAC address of the station to which the connection is to be canceled */ + uint8_t subtype; /**< Cancellation type */ + uint16_t reasonCode; /**< Cause of the cancellation */ +}; + +/** + * @brief Describes MAC configuration parameters. + * + * @since 1.0 + */ +typedef struct MacConfigParam { + uint8_t mac[WLAN_MAC_ADDR_LEN]; /**< MAC address. For details about its length, see {@link WLAN_MAC_ADDR_LEN}. */ + uint8_t p2pMode; /**< Whether the peer-to-peer (P2P) mode is used. */ +} Mac80211SetMacParam; + +#define OAL_IEEE80211_MAX_SSID_LEN 32 +/** + * @brief Describes disconnection parameters. + * + * @since 1.0 + */ +typedef struct { + uint8_t macAddr[WLAN_MAC_ADDR_LEN]; /**< Device MAC address */ + uint16_t reasonCode; /**< Disconnection reason code */ +} Mac80211DisconnectParam; + +#define MAC80211_SSIDS_AUC_SIZE 3 +/** + * @brief Describes SSIDs. + * + * @since 1.0 + */ +typedef struct { + uint8_t aucSsid[OAL_IEEE80211_MAX_SSID_LEN]; /**< SSID array */ + uint8_t ssidLen; /**< SSID length */ + uint8_t aucArry[MAC80211_SSIDS_AUC_SIZE]; /**< AuC data array */ +} Mac80211Ssids; + +#define WLAN_SCAN_REQ_MAX_BSS 2 +/** + * @brief Describes beacon parameters. + * + * @since 1.0 + */ +typedef struct { + int32_t interval; /**< Beacon interval */ + int32_t dtimPeriod; /**< Delivery Traffic Indication Message (DTIM) interval */ + WifiBeaconData *beaconData; /**< Beacon frame data */ + uint8_t hiddenSsid; /**< Whether to hide the SSID */ + uint8_t operationType; /**< Operation type */ +} Mac80211beaconParam; + +/** + * @brief Describes MAC-layer control APIs that need to be implemented by the driver. + * + * @since 1.0 + */ +struct WifiMac80211Ops { + int32_t (*changeVirtualIntf)(NetDevice *netDev, uint8_t iftype, uint32_t *flags, + struct VifParams *params); /**< Changing virtual APIs */ + int32_t (*setSsid)(NetDevice *netDev, const uint8_t *ssid, uint32_t ssidLen); /**< Setting the SSID */ + int32_t (*setMeshId)(NetDevice *netDev, const char *meshId, uint32_t meshIdLen); /**< Setting the mesh ID */ + int32_t (*setMacAddr)(NetDevice *netDev, Mac80211SetMacParam *param); /**< Setting the MAC address */ + int32_t (*changeBeacon)(NetDevice *netDev, Mac80211beaconParam *param); /**< Setting the beacon frame + * based on specified parameters + */ + int32_t (*setChannel)(NetDevice *netDev); /**< Setting the channel */ + int32_t (*addKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, + struct KeyParams *params); /**< Adding a key with specified + * parameters + */ + int32_t (*delKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr); + /**< Deleting a key based on a + * specified MAC address + */ + int32_t (*setDefaultKey)(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicas); + /**< Setting the default key */ + int32_t (*startAp)(NetDevice *netDev); /**< Starting an AP */ + int32_t (*stopAp)(NetDevice *netDev); /**< Stopping an AP */ + int32_t (*delStation)(NetDevice *netDev, const uint8_t *macAddr); /**< Deleting a station with a + * specified MAC address + */ + int32_t (*connect)(NetDevice *netDev, WifiConnectParams *param); /**< Starting a connection based + * on the specified parameters + */ + int32_t (*disconnect)(NetDevice *netDev, uint16_t reasonCode); /**< Canceling a connection */ + int32_t (*startScan)(NetDevice *netDev, struct WifiScanRequest *param); /**< Starting a scan based on the + * specified parameters + */ + int32_t (*abortScan)(NetDevice *netDev); /**< Stopping a scan */ +}; + +/** + * @brief Registers a {@link WifiMac80211Ops} object. + * + * @param ops Indicates the pointer to the {@link WifiMac80211Ops} object to register. + * + * @return Returns 0 if the {@link WifiMac80211Ops} object is registered successfully; + * returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t Mac80211RegisterOps(struct WifiMac80211Ops *ops) __attribute__((weak)); + +/** + * @brief Obtains the {@link WifiMac80211Ops} object that the driver needs to implement. + * + * @return Returns the pointer to the {@link WifiMac80211Ops} object. + * + * @since 1.0 + * @version 1.0 + */ +struct WifiMac80211Ops *Mac80211GetOps(void); + +#endif // _WIFI_MAC80211_OPS_H_ diff --git a/include/wifi/wifi_module.h b/include/wifi/wifi_module.h new file mode 100755 index 00000000..2dad717f --- /dev/null +++ b/include/wifi/wifi_module.h @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file wifi_module.h + * + * @brief Provides features of the WLAN module and functions to create and delete modules. + * + * The WifiModule object is a core abstraction of the WLAN driver. It contains a module that communicates with + * user-level processes and also contains features. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDFLITE_WIFI_MODULE_H +#define HDFLITE_WIFI_MODULE_H + +#include "wifi_inc.h" +#include "wifi_module_config.h" + +#ifdef __cplusplus +extern "C" { +#endif +/*********************************************************************** +* +* WLAN MODULE +* +************************************************************************/ +/** + * @brief Defines WLAN module APIs. + * + * The APIs can be used to obtain, initialize, update, and perform other operations on a WLAN module. + * + * @since 1.0 + */ +struct WifiModuleIface { + struct WifiModule *(*getModule)(void); /**< Obtaining a WLAN module */ + int32_t (*updateModule)(struct WifiModule *module); /**< Updating a WLAN module based on a specified + * configuration. + */ + int32_t (*init)(struct WifiModule *module); /**< Initializing a WLAN module */ + int32_t (*deInit)(struct WifiModule *module); /**< Deinitializing a WLAN module */ + + int32_t (*addFeature)(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData); + /**< Adding a feature */ + int32_t (*delFeature)(struct WifiModule *module, uint16_t featureType); /**< Deleting a feature */ +}; + +/** + * @brief Defines the WLAN module. + * + * The structure contains private data, APIs, module configurations, a module that communicates with user-level + * processes, and WLAN features. + * + * @since 1.0 + */ +struct WifiModule { + void *modulePrivate; /**< Private data */ + struct WifiModuleIface *iface; /**< APIs */ + struct WifiModuleConfig moduleConfig; /**< Module configurations */ + struct WifiFeatureList *feList; /**< WLAN features */ +}; + +/** + * @brief Creates a {@link WifiModule} object based on a specified configuration generated by the HCS. + * + * @param config Indicates the pointer to the configuration generated by the HCS. + * + * @return Returns the created {@link WifiModule} object. + * + * @since 1.0 + * @version 1.0 + */ +struct WifiModule *WifiModuleCreate(const struct HdfConfigWifiModuleConfig *config); + +/** + * @brief Deletes a specified {@link WifiModule} object. + * + * @param module Indicates the pointer to the {@link WifiModule} object to delete. + * + * @since 1.0 + * @version 1.0 + */ +void WifiModuleDelete(struct WifiModule *module); + +/*********************************************************************** +* +* WLAN MODULE FEATURE +* +************************************************************************/ +/** + * @brief Defines a WLAN feature. + * + * @since 1.0 + */ +struct WifiFeature { + char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Feature name, which can contain a maximum of 10 characters */ + struct HdfWifiChipData *chip; /**< Chip */ + int32_t (*init)(struct WifiFeature *feature); /**< Function for initializing the feature */ + int32_t (*deInit)(struct WifiFeature *feature); /**< Function for deinitializing the feature */ +}; + +/** + * @brief Defines the WLAN feature list. + * + * @since 1.0 + */ +struct WifiFeatureList { + struct WifiFeature *fe[HDF_WIFI_FEATURE_NUM]; /**< An array of WLAN features */ +}; + +/** + * @brief Deletes a specified feature from a specified module. + * + * @param module Indicates the pointer to the module. + * @param featureType Indicates the type of the feature to delete. + * + * @return Returns 0 if the feature is deleted successfully; returns -1 otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t DelFeature(struct WifiModule *module, uint16_t featureType); + +/** + * @brief Adds a specified feature to a specified module. + * + * @param module Indicates the pointer to the module. + * @param featureType Indicates the type of the feature to add. + * @param featureData Indicates the pointer to the feature to add. + * + * @return Returns 0 if the feature is added successfully; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData); + +/*********************************************************************** +* +* WLAN MODULE CHIP +* +************************************************************************/ +/** + * @brief Defines a WLAN chip. + * + * @since 1.0 + */ +struct HdfWifiChipData { + uint16_t type; /**< Chip type */ + char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Chip name */ + struct WifiMac80211Ops *ops; /**< Chip MAC address */ + int32_t (*init)(struct HdfWifiChipData *chipData, const struct HdfConfigWifiChip *chipConfig); + /**< Function for initializing the chip */ + int32_t (*deinit)(struct HdfWifiChipData *chipData); /**< Function for deinitializing the chip */ +}; + +#define HDF_WIFI_CHIP_DECLARE(chipName) \ + extern struct HdfWifiChipData g_hdf##chipName##ChipDriver __attribute__((weak)) + +#define HDF_WIFI_CHIP(chipName) &g_hdf##chipName##ChipDriver + +#define HDF_WIFI_CHIP_DRIVER(chipName, initFunc, deInitFunc) \ + struct HdfWifiChipData g_hdf##chipName##ChipDriver = { \ + .name = #chipName, \ + .init = initFunc, \ + .deinit = deInitFunc, \ + } + + +#ifdef __cplusplus +} +#endif + +#endif // HDFLITE_WIFI_MODULE_H + diff --git a/include/wifi/wifi_module_config.h b/include/wifi/wifi_module_config.h new file mode 100755 index 00000000..ff20de42 --- /dev/null +++ b/include/wifi/wifi_module_config.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and + * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided + * by the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file wifi_module_config.h + * + * @brief Declares the WLAN module configuration. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDFLITE_WIFI_MODULE_CONFIG_H +#define HDFLITE_WIFI_MODULE_CONFIG_H + +#include "osal.h" +#include "hdf_wifi_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Defines the WLAN module configuration. + * + * @since 1.0 + */ +struct WifiModuleConfig { + const struct HdfConfigWifiModuleConfig *hslConfig; /**< Configuration of each feature of the WLAN module */ +}; +#ifdef __cplusplus +} +#endif + +#endif // HDFLITE_WIFI_MODULE_CONFIG_H diff --git a/model/network/wifi/compoments/eapol/eapol.c b/model/network/wifi/compoments/eapol/eapol.c new file mode 100755 index 00000000..032f7b9b --- /dev/null +++ b/model/network/wifi/compoments/eapol/eapol.c @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "eapol.h" +#include +#include "securec.h" +#include "osal_time.h" +#include "osal_mem.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG HDF_WIFI_EAPOL + +#define RETURN_IF_INPUT_VALID(netDevice, buff) do { \ + if ((netDevice) == NULL || (buff) == NULL) { \ + HDF_LOGE("%s, netdevice = null or buf = null.", __func__); \ + return HDF_ERR_INVALID_PARAM; \ + } \ + if ((netDevice)->specialProcPriv == NULL) { \ + HDF_LOGE("%s : specialProcPriv = null", __func__); \ + return HDF_ERR_INVALID_PARAM; \ + } \ + } while (0) \ + +static int32_t EnableEapol(const struct NetDevice *netDevice, struct EapolEnable *buff) +{ + RETURN_IF_INPUT_VALID(netDevice, buff); + struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + eapol->regFlag = true; + eapol->context = buff->context; + eapol->notify = buff->notify; + return HDF_SUCCESS; +} + +static int32_t DisableEapol(const struct NetDevice *netDevice) +{ + if (netDevice == NULL || netDevice->specialProcPriv == NULL) { + HDF_LOGE("%s: netDevice = null or specialProcPriv = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + eapol->regFlag = false; + eapol->context = NULL; + eapol->notify = NULL; + return HDF_SUCCESS; +} + +static int32_t GetEapol(const struct NetDevice *netDevice, struct EapolRx *buff) +{ + RETURN_IF_INPUT_VALID(netDevice, buff); + struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + struct EapolRx *eapolRx = buff; + struct NetBuf *netBuff = NULL; + if (NetBufQueueIsEmpty(&eapol->eapolQueue)) { + HDF_LOGE("%s fail : eapolQueue empty!", __func__); + return HDF_FAILURE; + } + netBuff = NetBufQueueDequeue(&eapol->eapolQueue); + if (netBuff == NULL) { + HDF_LOGE("%s fail : dequeue netBuff = null!", __func__); + return HDF_FAILURE; + } + + uint8_t *p = NetBufGetAddress(netBuff, E_DATA_BUF); + uint32_t len = NetBufGetDataLen(netBuff); + if (len > eapolRx->len) { + HDF_LOGE("%s fail : eapolRx->len too small! netBuff->len(%d) > eapolRx->len(%d).", + __func__, netBuff->len, eapolRx->len); + NetBufFree(netBuff); + return HDF_FAILURE; + } + if (p != NULL) { + if (memcpy_s(eapolRx->buff, eapolRx->len, p, len) != EOK) { + HDF_LOGE("%s::mem safe function err!", __func__); + NetBufFree(netBuff); + return HDF_FAILURE; + } + } + eapolRx->len = len; + NetBufFree(netBuff); + return HDF_SUCCESS; +} + +static int32_t SendEapol(struct NetDevice *netDevice, struct EapolTx *buff) +{ + if (netDevice == NULL || buff == NULL) { + HDF_LOGE("%s : netdevice = null or buff = null.", __func__); + return HDF_ERR_INVALID_PARAM; + } + if ((netDevice->netDeviceIf == NULL) || (netDevice->netDeviceIf->xmit == NULL)) { + HDF_LOGE("%s : netDeviceIf NULL.", __func__); + return HDF_FAILURE; + } + + struct EapolTx *eapolTx = buff; + if (eapolTx->buff == NULL) { + HDF_LOGE("%s::eapolTx->buff = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + struct NetBuf *netBuff = NetBufDevAlloc(netDevice, eapolTx->len); + if (netBuff == NULL) { + HDF_LOGE("%s : netBuff alloc fail!", __func__); + return HDF_FAILURE; + } + NetBufPush(netBuff, E_DATA_BUF, eapolTx->len); + if (memcpy_s(NetBufGetAddress(netBuff, E_DATA_BUF), eapolTx->len, + eapolTx->buff, eapolTx->len) != EOK) { + NetBufFree(netBuff); + HDF_LOGE("%s::mem safe function err!", __func__); + return HDF_FAILURE; + } + return netDevice->netDeviceIf->xmit(netDevice, netBuff); +} + +static void HandleEapolQueue(struct EapolData *eapol) +{ + if (eapol == NULL) { + return; + } + int64_t currentTime = 0; + int64_t intervalTime = 0; + OsalTimespec timeSpec; + struct NetBuf *netBuf = NULL; + if (OsalGetTime(&timeSpec) == HDF_SUCCESS) { + currentTime = timeSpec.sec; + } + uint16_t maxCount = (eapol->maxCount != 0) ? eapol->maxCount : EAPOL_MAX_COUNT; + /* The queue is empty to update enqueueTime and count */ + if (NetBufQueueIsEmpty(&eapol->eapolQueue)) { + eapol->enqueueTime = currentTime; + eapol->count = 0; + return; + } + + /* prevent a large amount of netbuff resources being used when WPA is abnormal */ + if (currentTime > eapol->enqueueTime) { + intervalTime = currentTime - eapol->enqueueTime; + } + if (intervalTime > EAPOL_MAX_ENQUEUE_TIME || eapol->count >= maxCount) { + /* output log to solve problem */ + if (intervalTime > EAPOL_MAX_ENQUEUE_TIME) { + HDF_LOGE("%s discard pre netbuf : intervalTime(%lld) > EAPOL_MAX_ENQUEUE_TIME.", __func__, + intervalTime); + } else { + HDF_LOGE("%s discard pre netbuf : eapol->count(%d) = maxCount(%d).", __func__, eapol->count, maxCount); + } + eapol->count--; + eapol->enqueueTime = currentTime; + netBuf = NetBufQueueDequeue(&eapol->eapolQueue); + if (netBuf == NULL) { + HDF_LOGE("%s error : netbuff = null!", __func__); + return; + } + NetBufFree(netBuf); + } + return; +} + +static int32_t WriteEapolToQueue(const struct NetDevice *netDevice, struct NetBuf *buff) +{ + RETURN_IF_INPUT_VALID(netDevice, buff); + struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + if (eapol->regFlag && (eapol->notify != NULL)) { + HandleEapolQueue(eapol); + /* eapol data enqueue and notify wap processing */ + eapol->count++; + NetBufQueueEnqueue(&eapol->eapolQueue, buff); + eapol->notify(netDevice->name, eapol->context); + return HDF_SUCCESS; + } else { + /* free netbuff when not register notify. */ + NetBufFree(buff); + HDF_LOGE("%s fail : eapol process is not register.", __func__); + return HDF_SUCCESS; + } +} + +static struct EapolInterface g_eapolInterface = { + .enableEapol = EnableEapol, + .disableEapol = DisableEapol, + .getEapol = GetEapol, + .sendEapol = SendEapol, + .writeEapolToQueue = WriteEapolToQueue, +}; + +struct Eapol g_eapol = { + .eapolOp = &g_eapolInterface, +}; + +int32_t CreateEapolData(struct NetDevice *netDevice) +{ + if (netDevice == NULL) { + HDF_LOGE("%s fail : netdev = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (netDevice->specialProcPriv != NULL) { + HDF_LOGI("%s already create!", __func__); + return HDF_SUCCESS; + } + struct EapolData *eapolData = (struct EapolData *)OsalMemCalloc(sizeof(struct EapolData)); + if (eapolData == NULL) { + HDF_LOGE("%s fail : malloc fail!", __func__); + return HDF_FAILURE; + } + (void)memset_s(eapolData, sizeof(struct EapolData), 0, sizeof(struct EapolData)); + NetBufQueueInit(&eapolData->eapolQueue); + netDevice->specialProcPriv = eapolData; + HDF_LOGI("%s success!", __func__); + return HDF_SUCCESS; +} + +void DestroyEapolData(struct NetDevice *netDevice) +{ + if (netDevice == NULL || netDevice->specialProcPriv == NULL) { + HDF_LOGE("%s already free!", __func__); + return; + } + struct EapolData *eapolData = (struct EapolData *)netDevice->specialProcPriv; + NetBufQueueClear(&eapolData->eapolQueue); + OsalMemFree(eapolData); + netDevice->specialProcPriv = NULL; + HDF_LOGE("%s success!", __func__); + return; +} + +const struct Eapol *EapolGetInstance(void) +{ + return &g_eapol; +} diff --git a/model/network/wifi/compoments/eapol/eapol.h b/model/network/wifi/compoments/eapol/eapol.h new file mode 100755 index 00000000..b4454d86 --- /dev/null +++ b/model/network/wifi/compoments/eapol/eapol.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_EAPOL_H +#define HDF_EAPOL_H + +#include +#include +#include +#include "hdf_netbuf.h" +#include "net_device.h" + +#define EAPOL_MAX_COUNT 10 +#define EAPOL_MAX_ENQUEUE_TIME 300 /* 300 Second */ + +struct EapolData { + bool regFlag; /* is already regstered */ + uint16_t count; /* eapol frame count in NetBuffQueue. */ + uint16_t maxCount; + int64_t enqueueTime; /* record eapol frame time for dfx. */ + void (*notify)(const char *name, void *context); /* notify eapol frame enqueue message */ + void *context; + struct NetBufQueue eapolQueue; +}; + +struct Eapol { + struct EapolInterface *eapolOp; +}; + +struct EapolEnable { + void (*notify)(const char *name, void *context); + void *context; +}; + +struct EapolRx { + uint8_t *buff; + uint32_t len; +}; + +struct EapolTx { + uint8_t *buff; + uint32_t len; +}; + +struct EapolInterface { + int32_t (*enableEapol)(const struct NetDevice *netDevice, struct EapolEnable *buff); + int32_t (*disableEapol)(const struct NetDevice *netDevice); + int32_t (*getEapol)(const struct NetDevice *netDevice, struct EapolRx *buff); + int32_t (*sendEapol)(struct NetDevice *netDevice, struct EapolTx *buff); + int32_t (*writeEapolToQueue)(const struct NetDevice *netDevice, struct NetBuf *buff); +}; + +/* API */ +const struct Eapol *EapolGetInstance(void); +void DestroyEapolData(struct NetDevice *netDevice); +int32_t CreateEapolData(struct NetDevice *netDevice); + +#endif /* HDF_EAPOL_H */ \ No newline at end of file diff --git a/model/network/wifi/compoments/softap/ap.c b/model/network/wifi/compoments/softap/ap.c new file mode 100755 index 00000000..160693dd --- /dev/null +++ b/model/network/wifi/compoments/softap/ap.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "hdf_wifi_product.h" +#include "wifi_mac80211_ops.h" +#include "ap.h" + +#if __cplusplus +extern "C" { +#endif + +struct WifiApFeature g_apFeature; + +static int32_t ApInit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static int32_t ApDeinit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static int32_t SetupWireLessDev(struct NetDevice *netDev, WifiApSetting *apSettings) +{ + if (netDev->ieee80211Ptr == NULL) { + netDev->ieee80211Ptr = (struct WirelessDev *)OsalMemCalloc(sizeof(struct WirelessDev)); + if (netDev->ieee80211Ptr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + } + + if (netDev->ieee80211Ptr->presetChandef.chan == NULL) { + netDev->ieee80211Ptr->presetChandef.chan = + (struct Ieee80211Channel *)OsalMemCalloc(sizeof(struct Ieee80211Channel)); + if (netDev->ieee80211Ptr->presetChandef.chan == NULL) { + OsalMemFree(netDev->ieee80211Ptr); + netDev->ieee80211Ptr = NULL; + return HDF_ERR_INVALID_PARAM; + } + } + + netDev->ieee80211Ptr->presetChandef.width = (enum WifiChannelType)apSettings->freqParams.bandwidth; + netDev->ieee80211Ptr->presetChandef.centerFreq1 = apSettings->freqParams.centerFreq1; + netDev->ieee80211Ptr->presetChandef.chan->hwValue = (uint16_t)apSettings->freqParams.channel; + netDev->ieee80211Ptr->presetChandef.chan->band = IEEE80211_BAND_2GHZ; + return HDF_SUCCESS; +} + +static uint32_t StartAp(struct NetDevice *netDev, WifiApSetting *apSettings) +{ + int32_t ret = SetupWireLessDev(netDev, apSettings); + if (ret) { + HDF_LOGE("StartAp:failed to SetupWireLessDev, error[%d]", ret); + return ret; + } + + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + Mac80211beaconParam beaconParam = { 0 }; + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setChannel); + if (macOps->setChannel(netDev)) { + HDF_LOGE("StartAp:failed to setChannel, error[%d]", ret); + return HDF_FAILURE; + } + + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setSsid); + if (macOps->setSsid(netDev, (const uint8_t *)apSettings->ssid, apSettings->ssidLen)) { + HDF_LOGE("StartAp:failed to setSsid, error[%d]", ret); + return HDF_FAILURE; + } + + beaconParam.interval = apSettings->beaconInterval; + beaconParam.dtimPeriod = apSettings->dtimPeriod; + beaconParam.hiddenSsid = (apSettings->hiddenSsid == 1); + beaconParam.beaconData = &apSettings->beaconData; + beaconParam.operationType = MAC_BEACON_ADD; + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); + if (macOps->changeBeacon(netDev, &beaconParam)) { + return HDF_FAILURE; + } + + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, startAp); + ret = macOps->startAp(netDev); + if (ret) { + HDF_LOGE("StartAp:failed to start ap, error[%d]", ret); + return HDF_FAILURE; + } + return NetIfSetStatus(netDev, NETIF_UP); +} + +static uint32_t StopAp(struct NetDevice *netDev) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, stopAp); + uint32_t ret = macOps->stopAp(netDev); + if (ret) { + HDF_LOGE("StopAp:failed, error[%d]", ret); + return ret; + } + + return NetIfSetStatus(netDev, NETIF_DOWN); +} + +static uint32_t DelStation(struct NetDevice *netDev, struct StationDelParameters *params) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, delStation); + return macOps->delStation(netDev, params->mac); +} + +static uint32_t ChangeBeacon(struct NetDevice *netDev, WifiApSetting *apSettings) +{ + if (netDev == NULL || apSettings == NULL) { + HDF_LOGI("%s: parameter null", __func__); + return HDF_FAILURE; + } + + Mac80211beaconParam beaconParam = { 0 }; + struct WifiMac80211Ops *macOps = g_apFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); + beaconParam.interval = apSettings->beaconInterval; + beaconParam.dtimPeriod = apSettings->dtimPeriod; + beaconParam.hiddenSsid = (apSettings->hiddenSsid == 1); + beaconParam.beaconData = &apSettings->beaconData; + beaconParam.operationType = MAC_BEACON_SET; + + return macOps->changeBeacon(netDev, &beaconParam); +} + +struct WifiApFeature g_apFeature = { + .fe = { + .name = "ap", + .init = ApInit, + .deInit = ApDeinit, + }, + .ops = { + .startAp = StartAp, + .stopAp = StopAp, + .delStation = DelStation, + .changeBeacon = ChangeBeacon, + }, +}; + +struct WifiApFeature *WifiApGetFeature(const struct WifiModule *module) +{ + return (struct WifiApFeature *)GetFeature(module, HDF_WIFI_FEATURE_AP); +} + +struct WifiFeature *GetWifiApFeatureDelc(void) +{ + return (struct WifiFeature *)&g_apFeature; +} + +#if __cplusplus +extern "C" +} +#endif diff --git a/model/network/wifi/compoments/softap/ap.h b/model/network/wifi/compoments/softap/ap.h new file mode 100755 index 00000000..7d28e69b --- /dev/null +++ b/model/network/wifi/compoments/softap/ap.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDFLITE_AP_H +#define HDFLITE_AP_H + +#include "wifi_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +enum WifiAPFeatureType { + HDF_WIFI_AP_NOT_SUPPORT, + HDF_WIFI_AP_SOFTAP, + HDF_WIFI_AP_END, +}; + +struct WifiApFeatureOps { + uint32_t (*startAp)(struct NetDevice *dev, WifiApSetting *settings); + uint32_t (*stopAp)(struct NetDevice *dev); + uint32_t (*delStation)(struct NetDevice *dev, struct StationDelParameters *params); + uint32_t (*changeBeacon)(struct NetDevice *dev, WifiApSetting *apSettings); +}; + +struct WifiApFeature { + struct WifiFeature fe; + struct WifiApFeatureOps ops; +}; + +struct WifiApFeature *WifiApGetFeature(const struct WifiModule *module); + +struct WifiFeature *GetWifiApFeatureDelc(void); + +#ifdef __cplusplus +} +#endif +#endif // HDFLITE_AP_H diff --git a/model/network/wifi/compoments/sta/sta.c b/model/network/wifi/compoments/sta/sta.c new file mode 100755 index 00000000..9ba8b981 --- /dev/null +++ b/model/network/wifi/compoments/sta/sta.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "sta.h" +#include "hdf_wifi_product.h" + +#if __cplusplus +extern "C" { +#endif + +struct WifiStaFeature g_staFeature; + +static int32_t StaInit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static int32_t StaDeinit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static uint32_t Scan(struct NetDevice *netDev, struct WifiScanRequest *request) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, startScan); + return macOps->startScan(netDev, request); +} + +static void AbortScan(struct NetDevice *netDev) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; + if (macOps == NULL) { + HDF_LOGI("mac ops not registered"); + return; + } + + if (macOps->abortScan != NULL) { + macOps->abortScan(netDev); + } else { + HDF_LOGE("macOps abortScan not implement"); + } +} + +static uint32_t Connect(struct NetDevice *netDev, struct WifiConnectParams *param) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); + return macOps->connect(netDev, param); +} + +static uint32_t Disconnect(struct NetDevice *netDev, uint16_t reasonCode) +{ + struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, disconnect); + return macOps->disconnect(netDev, reasonCode); +} + +struct WifiStaFeature g_staFeature = { + .fe = { + .name = "sta", + .init = StaInit, + .deInit = StaDeinit, + }, + .ops = { + .scan = Scan, + .abortScan = AbortScan, + .connect = Connect, + .disconnect = Disconnect, + }, +}; + +struct WifiStaFeature *GetWifiStaFeature(const struct WifiModule *module) +{ + return (struct WifiStaFeature *)GetFeature(module, HDF_WIFI_FEATURE_STA); +} + +struct WifiFeature *GetWifiStaFeatureDelc(void) +{ + return (struct WifiFeature *)&g_staFeature; +} + +#ifdef __cplusplus +} +#endif diff --git a/model/network/wifi/compoments/sta/sta.h b/model/network/wifi/compoments/sta/sta.h new file mode 100755 index 00000000..2dd85021 --- /dev/null +++ b/model/network/wifi/compoments/sta/sta.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDFLITE_STA_H +#define HDFLITE_STA_H + +#include "wifi_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct WifiStaFeatureOps { + uint32_t (*scan)(struct NetDevice *dev, struct WifiScanRequest *request); + void (*abortScan)(struct NetDevice *dev); + uint32_t (*connect)(struct NetDevice *dev, struct WifiConnectParams *sme); + uint32_t (*disconnect)(struct NetDevice *dev, uint16_t reason_code); +}; + +struct WifiStaFeature { + struct WifiFeature fe; + struct WifiStaFeatureOps ops; +}; + +struct WifiStaFeature *GetWifiStaFeature(const struct WifiModule *module); +struct WifiFeature *GetWifiStaFeatureDelc(void); +#ifdef __cplusplus +} +#endif + +#endif // HDFLITE_STA_H diff --git a/model/network/wifi/include/hdf_wifi_cmd.h b/model/network/wifi/include/hdf_wifi_cmd.h new file mode 100755 index 00000000..11dddcfd --- /dev/null +++ b/model/network/wifi/include/hdf_wifi_cmd.h @@ -0,0 +1,489 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _WIFI_HAL_H_ +#define _WIFI_HAL_H_ + +#include +#include +#include +#include "hdf_device_desc.h" +#include "hdf_sbuf.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define SUCC 0 +#define EFAIL 1 +#define EINVAL 22 + +#define ETH_ADDR_LEN 6 +#define MAX_SSID_LEN 32 +#define MAX_NR_CIPHER_SUITES 5 +#define MAX_NR_AKM_SUITES 2 +#define WPAS_MAX_SCAN_SSIDS 16 +#define DRIVER_MAX_SCAN_SSIDS 2 + +#define SCAN_AP_LIMIT 64 +#define SCAN_TIME_OUT 5 + +#define NETDEV_UP 0x0001 +#define NETDEV_DOWN 0x0002 + +#define EAPOL_PKT_BUF_SIZE 800 +#define CHECK_DHCP_TIME 30 + +#define WPA_WEP40_KEY_LEN 5 +#define WPA_WEP104_KEY_LEN 13 + +typedef enum { + WPA_VERSION_1 = 1 << 0, + WPA_VERSION_2 = 1 << 1, +} WpaVersions; + +typedef enum { + WIFI_CHAN_WIDTH_20_NOHT, + WIFI_CHAN_WIDTH_20, + WIFI_CHAN_WIDTH_40, + WIFI_CHAN_WIDTH_BUTT +} WifiChannelWidth; + +typedef enum { + WIFI_DISCONNECT, + WIFI_CONNECT, +} WifiConnectStatus; + +typedef enum { + WIFI_KEYTYPE_GROUP, + WIFI_KEYTYPE_PAIRWISE, + WIFI_KEYTYPE_PEERKEY, + WIFI_KEYTYPE_BUTT +} WifiKeyType; + +typedef enum { + WIFI_KEY_DEFAULT_TYPE_INVALID, + WIFI_KEY_DEFAULT_TYPE_UNICAST, + WIFI_KEY_DEFAULT_TYPE_MULTICAST, + WIFI_KEY_DEFAULT_TYPES +} WifiKeyDefaultType; + +typedef enum { + WIFI_NO_SSID_HIDING, + WIFI_HIDDEN_SSID_ZERO_LEN, + WIFI_HIDDEN_SSID_ZERO_CONTENTS +} WifiHiddenSsid; + +typedef enum { + WIFI_WPA_CMD_SET_AP = 0, + WIFI_WPA_CMD_NEW_KEY, + WIFI_WPA_CMD_DEL_KEY, + WIFI_WPA_CMD_SET_KEY, + WIFI_WPA_CMD_SEND_MLME, + WIFI_WPA_CMD_SEND_EAPOL = 5, + WIFI_WPA_CMD_RECEIVE_EAPOL, + WIFI_WPA_CMD_ENALBE_EAPOL, + WIFI_WPA_CMD_DISABLE_EAPOL, + WIFI_WPA_CMD_GET_ADDR, + WIFI_WPA_CMD_SET_POWER = 10, + WIFI_WPA_CMD_SET_MODE, + WIFI_WPA_CMD_GET_HW_FEATURE, + WIFI_WPA_CMD_STOP_AP, + WIFI_WPA_CMD_DEL_VIRTUAL_INTF, + WIFI_WPA_CMD_SCAN = 15, + WIFI_WPA_CMD_DISCONNECT, + WIFI_WPA_CMD_ASSOC, + WIFI_WPA_CMD_SET_NETDEV, + WIFI_WPA_CMD_SET_AP_WPS_P2P_IE, + WIFI_WPA_CMD_CHANGE_BEACON = 20, + WIFI_WPA_CMD_DHCP_START, + WIFI_WPA_CMD_DHCP_STOP, + WIFI_WPA_CMD_DHCP_SUCC_CHECK, + WIFI_WPA_CMD_SET_REKEY_INFO, + WIFI_WPA_CMD_SET_PM_ON = 25, + WIFI_WPA_CMD_IP_NOTIFY_DRIVER, + WIFI_WPA_CMD_SET_MAX_STA, + WIFI_WPA_CMD_STA_REMOVE, + WIFI_WPA_CMD_SEND_ACTION, + WIFI_WPA_CMD_SET_MESH_USER = 30, + WIFI_WPA_CMD_SET_MESH_GTK, + WIFI_WPA_CMD_EN_AUTO_PEER, + WIFI_WPA_CMD_EN_ACCEPT_PEER, + WIFI_WPA_CMD_EN_ACCEPT_STA, + WIFI_WPA_CMD_ADD_IF = 35, + WIFI_WPA_CMD_PROBE_REQUEST_REPORT, + WIFI_WPA_CMD_REMAIN_ON_CHANNEL, + WIFI_WPA_CMD_CANCEL_REMAIN_ON_CHANNEL, + WIFI_WPA_CMD_SET_P2P_NOA, + WIFI_WPA_CMD_SET_P2P_POWERSAVE = 40, + WIFI_WPA_CMD_REMOVE_IF, + WIFI_WPA_CMD_GET_P2P_MAC_ADDR, + WIFI_WPA_CMD_GET_DRIVER_FLAGS, + WIFI_WPA_CMD_SET_USR_APP_IE, + WIFI_WPA_CMD_BUTT +} WifiWPACmdType; + +typedef enum { + WIFI_WPA_EVENT_NEW_STA = 0, + WIFI_WPA_EVENT_DEL_STA, + WIFI_WPA_EVENT_RX_MGMT, + WIFI_WPA_EVENT_TX_STATUS, + WIFI_WPA_EVENT_SCAN_DONE, + WIFI_WPA_EVENT_SCAN_RESULT = 5, + WIFI_WPA_EVENT_CONNECT_RESULT, + WIFI_WPA_EVENT_DISCONNECT, + WIFI_WPA_EVENT_MESH_CLOSE, + WIFI_WPA_EVENT_NEW_PEER_CANDIDATE, + WIFI_WPA_EVENT_REMAIN_ON_CHANNEL = 10, + WIFI_WPA_EVENT_CANCEL_REMAIN_ON_CHANNEL, + WIFI_WPA_EVENT_CHANNEL_SWITCH, + WIFI_WPA_EVENT_EAPOL_RECV, + WIFI_WPA_EVENT_TIMEOUT_DISCONN, + WIFI_WPA_EVENT_BUTT +} WifiWpaEventType; + +typedef enum { + WIFI_AUTHTYPE_OPEN_SYSTEM = 0, + WIFI_AUTHTYPE_SHARED_KEY, + WIFI_AUTHTYPE_FT, + WIFI_AUTHTYPE_EAP, + WIFI_AUTHTYPE_SAE, + WIFI_AUTHTYPE_AUTOMATIC, + WIFI_AUTHTYPE_BUTT +} WifiAuthType; + +typedef enum { + WIFI_SCAN_SUCCESS, + WIFI_SCAN_FAILED, + WIFI_SCAN_REFUSED, + WIFI_SCAN_TIMEOUT +} WifiScanStatus; + +typedef enum { + WIFI_MFP_NO, + WIFI_MFP_OPTIONAL, + WIFI_MFP_REQUIRED, +} WifiMfp; + +typedef enum { + WIFI_IFTYPE_ADHOC, + WIFI_IFTYPE_STATION, + WIFI_IFTYPE_AP, + WIFI_IFTYPE_AP_VLAN, + WIFI_IFTYPE_WDS, + WIFI_IFTYPE_MONITOR, + WIFI_IFTYPE_MESH_POINT, + WIFI_IFTYPE_P2P_CLIENT, + WIFI_IFTYPE_P2P_GO, + WIFI_IFTYPE_P2P_DEVICE, + WIFI_IFTYPE_MAX, +} WifiIfType; + +typedef enum { + WIFI_PHY_MODE_11N = 0, + WIFI_PHY_MODE_11G = 1, + WIFI_PHY_MODE_11B = 2, + WIFI_PHY_MODE_BUTT +} WifiPhyMode; + +typedef struct { + uint8_t status; + WifiIfType ifType; + WifiPhyMode mode; +} WifiSetNewDev; + +typedef struct { + int32_t numRates; + int32_t mode; +} WifiModes; + +typedef struct { + int32_t reassoc; + size_t ieLen; + uint8_t *ie; + uint8_t macAddr[ETH_ADDR_LEN]; + uint8_t resv[2]; +} WifiNewStaInfo; + +typedef struct { + uint8_t *buf; + uint32_t len; + int32_t sigMbm; + int32_t freq; +} WifiRxMgmt; + +typedef struct { + uint8_t *buf; + uint32_t len; + uint8_t ack; + uint8_t resv[3]; +} WifiTxStatus; + +typedef struct { + uint32_t freq; + size_t dataLen; + uint8_t *data; + uint64_t *cookie; +} WifiMlmeData; + +typedef struct { + size_t headLen; + size_t tailLen; + uint8_t *head; + uint8_t *tail; +} WifiBeaconData; + +typedef struct { + uint8_t *dst; + uint8_t *src; + uint8_t *bssid; + uint8_t *data; + size_t dataLen; +} WifiActionData; + +typedef struct { + int32_t mode; + int32_t freq; + int32_t channel; + + /* for HT */ + int32_t htEnabled; + + /* + * 0 = HT40 disabled, -1 = HT40 enabled, + * secondary channel below primary, 1 = HT40 + * enabled, secondary channel above primary + */ + int32_t secChannelOffset; + + /* for VHT */ + int32_t vhtEnabled; + + /* + * valid for both HT and VHT, center_freq2 is non-zero + * only for bandwidth 80 and an 80+80 channel + */ + int32_t centerFreq1; + int32_t centerFreq2; + int32_t bandwidth; +} WifiFreqParams; + +typedef struct { + int32_t type; + uint32_t keyIdx; + uint32_t keyLen; + uint32_t seqLen; + uint32_t cipher; + uint8_t *addr; + uint8_t *key; + uint8_t *seq; + uint8_t def; + uint8_t defMgmt; + uint8_t defaultTypes; + uint8_t resv; +} WifiKeyExt; + +typedef struct { + WifiFreqParams freqParams; + WifiBeaconData beaconData; + size_t ssidLen; + int32_t beaconInterval; + int32_t dtimPeriod; + uint8_t *ssid; + uint8_t hiddenSsid; + uint8_t authType; + size_t meshSsidLen; + uint8_t *meshSsid; +} WifiApSetting; + +typedef struct { + uint8_t bssid[ETH_ADDR_LEN]; + uint8_t iftype; + uint8_t resv; +} WifiSetMode; + +typedef struct { + uint8_t *buf; + uint32_t len; +} WifiTxEapol; + +typedef struct { + uint8_t *buf; + uint32_t len; +} WifiRxEapol; + +typedef struct { + void *callback; + void *contex; +} WifiEnableEapol; + +typedef struct { + uint16_t channel; + uint32_t freq; + uint32_t flags; +} WifiIeee80211Channel; + +typedef struct { + int32_t channelNum; + uint16_t bitrate[12]; + uint16_t htCapab; + uint8_t resv[2]; + WifiIeee80211Channel iee80211Channel[14]; +} WifiHwFeatureData; + +typedef struct { + uint8_t ssid[MAX_SSID_LEN]; + size_t ssidLen; +} WifiDriverScanSsid; + +typedef struct { + WifiDriverScanSsid *ssids; + int32_t *freqs; + uint8_t *extraIes; + uint8_t *bssid; + uint8_t numSsids; + uint8_t numFreqs; + uint8_t prefixSsidScanFlag; + uint8_t fastConnectFlag; + int32_t extraIesLen; +} WifiScan; + +typedef struct { + uint32_t freq; + uint32_t duration; +} WifiOnChannel; + + +typedef struct { + uint8_t ifname[IFNAMSIZ]; +} WifiIfRemove; + +typedef struct { + uint8_t type; + uint8_t macAddr[ETH_ADDR_LEN]; + uint8_t resv; +} WifiGetP2pAddr; + +typedef struct { + WifiIfType iftype; + uint8_t *macAddr; +} WifiIftypeMacAddr; + +typedef struct { + uint64_t drvFlags; +} WifiGetDrvFlags; + +typedef struct { + int32_t freq; +} WifiChannelSwitch; + +typedef struct { + uint32_t wpaVersions; + uint32_t cipherGroup; + int32_t nCiphersPairwise; + uint32_t ciphersPairwise[MAX_NR_CIPHER_SUITES]; + int32_t nAkmSuites; + uint32_t akmSuites[MAX_NR_AKM_SUITES]; +} WifiCryptoSetting; + +typedef struct { + uint8_t *bssid; + uint8_t *ssid; + uint8_t *ie; + uint8_t *key; + uint8_t authType; + uint8_t privacy; + uint8_t keyLen; + uint8_t keyIdx; + uint8_t mfp; + uint8_t rsv[3]; + uint32_t freq; + uint32_t ssidLen; + uint32_t ieLen; + WifiCryptoSetting *crypto; +} WifiAssociateParams; + +typedef struct { + uint8_t *reqIe; + size_t reqIeLen; + uint8_t *respIe; + size_t respIeLen; + uint8_t bssid[ETH_ADDR_LEN]; + uint8_t rsv[2]; + uint16_t status; + uint16_t freq; +} WifiConnectResult; + +typedef struct { + int32_t flags; + uint8_t bssid[ETH_ADDR_LEN]; + int16_t caps; + int32_t freq; + int16_t beaconInt; + int32_t qual; + uint32_t beaconIeLen; + int32_t level; + uint32_t age; + uint32_t ieLen; + uint8_t *variable; +} WifiScanResult; + +typedef struct { + uint8_t *ie; + uint16_t reason; + uint8_t rsv[2]; + uint32_t ieLen; +} WifiDisconnect; + +typedef enum { + WIFI_CHAN_DISABLED = 1 << 0, + WIFI_CHAN_PASSIVE_SCAN = 1 << 1, + WIFI_CHAN_NO_IBSS = 1 << 2, + WIFI_CHAN_RADAR = 1 << 3, + WIFI_CHAN_NO_HT40PLUS = 1 << 4, + WIFI_CHAN_NO_HT40MINUS = 1 << 5, + WIFI_CHAN_NO_OFDM = 1 << 6, + WIFI_CHAN_NO_80MHZ = 1 << 7, + WIFI_CHAN_NO_160MHZ = 1 << 8, +} WifiChannelFlags; + +int32_t WifiCmdProcess(struct HdfDeviceObject *device, int32_t cmd, struct HdfSBuf *reqData, struct HdfSBuf *rspData); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + + +#endif /* end of hdf_wifi_cmd.h */ diff --git a/model/network/wifi/include/hdf_wifi_config.h b/model/network/wifi/include/hdf_wifi_config.h new file mode 100755 index 00000000..89ffaf4e --- /dev/null +++ b/model/network/wifi/include/hdf_wifi_config.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_WIFI_CONFIG_HEADER_H +#define HDF_WIFI_CONFIG_HEADER_H + +#include +#include "device_resource_if.h" + +#define WIFI_CONFIG_NAME_MAX 20 +#define WIFI_CHIP_MAX 3 +#define GPIO_PRAM_COUNT 2 +#define BUS_REG_COUNT 2 +#define BUS_FUNC_MAX 1 +#define GPIO_ARGS_COUNT 3 + +struct HdfConfigWifiStation { + const char *name; + uint8_t mode; +}; + +struct HdfConfigWifiHostAp { + const char *name; + uint8_t mode; + uint8_t vapResNum; + uint8_t userResNum; +}; + +struct HdfConfigWifiP2P { + const char *name; + uint8_t mode; +}; + +struct HdfConfigWifiMac80211 { + uint8_t mode; +}; + +struct HdfConfigWifiPhy { + uint8_t mode; +}; + +struct HdfConfigWifiModuleConfig { + uint32_t featureMap; + const char *msgName; + struct HdfConfigWifiStation station; + struct HdfConfigWifiHostAp hostAp; + struct HdfConfigWifiP2P p2p; + struct HdfConfigWifiMac80211 mac80211; + struct HdfConfigWifiPhy Phy; +}; + +struct HdfConfigWifiBus { + uint8_t busType; + uint8_t funcNum[BUS_FUNC_MAX]; + uint32_t funcNumSize; + uint16_t vendorId; + uint16_t deviceId; + uint16_t timeout; + uint16_t blockSize; +}; + +struct HdfConfigWifiChip { + const char *chipName; + uint8_t chipId; + uint32_t featureMap; + uint8_t powerType; + uint8_t irqNo; + struct HdfConfigWifiBus bus; +}; + +struct HdfConfigWifiDeviceList { + struct HdfConfigWifiChip chip[WIFI_CHIP_MAX]; + uint16_t chipSize; +}; + +struct HdfConfigWifiBusRegs { + uint32_t cclkOut[BUS_REG_COUNT]; + uint32_t ccmd[BUS_REG_COUNT]; + uint32_t cdata0[BUS_REG_COUNT]; + uint32_t cdata1[BUS_REG_COUNT]; + uint32_t cdata2[BUS_REG_COUNT]; + uint32_t cdata3[BUS_REG_COUNT]; +}; + +struct HdfConfigWifiBoard { + const char *boardName; + uint8_t busType; + uint8_t busIdx; + uint8_t reset[GPIO_PRAM_COUNT]; + uint8_t gpioArgs[GPIO_ARGS_COUNT]; + struct HdfConfigWifiBusRegs busRegs; +}; + +struct HdfConfigWifiWifiConfig { + struct HdfConfigWifiModuleConfig moduleConfig; + struct HdfConfigWifiDeviceList deviceList; + struct HdfConfigWifiBoard board; +}; + +struct HdfConfigWifiRoot { + struct HdfConfigWifiWifiConfig wifiConfig; +}; + +struct HdfConfigWifiRoot* HdfWifiGetModuleConfigRoot(void); +int32_t HdfParseWifiConfig(const struct DeviceResourceNode *node); + +#endif // HDF_WIFI_CONFIG_HEADER_H \ No newline at end of file diff --git a/model/network/wifi/module/wifi_base.c b/model/network/wifi/module/wifi_base.c new file mode 100755 index 00000000..4b029e3a --- /dev/null +++ b/model/network/wifi/module/wifi_base.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "wifi_module.h" +#include "ap.h" +#include "eapol.h" +#include "sta.h" +#include "wifi_mac80211_ops.h" + + +struct WifiBaseFeature g_baseFeature; + +int32_t BaseInit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +int32_t BaseDeinit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static uint32_t EnableEapol(struct NetDevice *netdev, WifiEnableEapol *param) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->enableEapol(netdev, (struct EapolEnable *)param); +} +static uint32_t DisableEapol(struct NetDevice *netdev) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->disableEapol(netdev); +} +static uint32_t SendEapol(struct NetDevice *netdev, WifiTxEapol *txData) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->sendEapol(netdev, (struct EapolTx *)txData); +} +static uint32_t ReceiveEapol(struct NetDevice *netdev, WifiRxEapol *rxData) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->getEapol(netdev, (struct EapolRx *)rxData); +} + +static uint32_t ChangeVirtualIntf(struct NetDevice *netDev, uint8_t iftype, uint32_t *flags, + struct VifParams *params) +{ + struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeVirtualIntf); + return macOps->changeVirtualIntf(netDev, iftype, flags, params); +} + +static uint32_t AddKey(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, + struct KeyParams *params) +{ + struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, addKey); + return macOps->addKey(netdev, keyIndex, pairwise, macAddr, params); +} + +static uint32_t DelKey(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr) +{ + struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, delKey); + return macOps->delKey(netdev, keyIndex, pairwise, macAddr); +} + +static uint32_t SetDefaultKey(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicast) +{ + struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; + RETURN_IF_MACOPS_NOT_REGISTERED(macOps); + RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setDefaultKey); + return macOps->setDefaultKey(netdev, keyIndex, unicast, multicast); +} + +static uint32_t SetDefaultMgmtKey(struct NetDevice *netdev, uint8_t keyIndex) +{ + (void)netdev; + (void)keyIndex; + return HDF_SUCCESS; +} + +struct WifiBaseFeature g_baseFeature = { + .fe = { + .name = "base", + .init = BaseInit, + .deInit = BaseDeinit, + }, + .ops = { + .enableEapol = EnableEapol, + .disableEapol = DisableEapol, + .sendEapol = SendEapol, + .receiveEapol = ReceiveEapol, + .changeVirtualIntf = ChangeVirtualIntf, + .addKey = AddKey, + .delKey = DelKey, + .setDefaultKey = SetDefaultKey, + .setDefaultMgmtKey = SetDefaultMgmtKey, + } +}; + +struct WifiFeatureList g_featureList = { 0 }; + +int32_t InitFeatures(struct WifiModule *module) +{ + if (module == NULL) { + HDF_LOGE("%s: error, no module", __func__); + return HDF_FAILURE; + } + + g_featureList.fe[HDF_WIFI_FEATURE_BASE] = (struct WifiFeature *)&g_baseFeature; + g_featureList.fe[HDF_WIFI_FEATURE_AP] = GetWifiApFeatureDelc(); + g_featureList.fe[HDF_WIFI_FEATURE_STA] = GetWifiStaFeatureDelc(); + + module->feList = &g_featureList; + + for (uint32_t i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { + if ((module->moduleConfig.hslConfig->featureMap & (1 << i)) && module->feList->fe[i] != NULL) { + module->feList->fe[i]->init(module->feList->fe[i]); + } + } + return HDF_SUCCESS; +} + +struct WifiBaseFeature *WifiBaseGetFeature(const struct WifiModule *module) +{ + return (struct WifiBaseFeature *)GetFeature(module, HDF_WIFI_FEATURE_BASE); +} diff --git a/model/network/wifi/module/wifi_base.h b/model/network/wifi/module/wifi_base.h new file mode 100755 index 00000000..fb7c443c --- /dev/null +++ b/model/network/wifi/module/wifi_base.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _HDF_WIFI_FEATURE_H_ +#define _HDF_WIFI_FEATURE_H_ + +#include "wifi_module.h" +#include "hdf_wifi_cmd.h" +#include "net_device.h" +#include "wifi_mac80211_ops.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct WiFiBaseFeatureOps { + uint32_t (*enableEapol)(struct NetDevice *netdev, WifiEnableEapol *param); + uint32_t (*disableEapol)(struct NetDevice *netdev); + uint32_t (*sendEapol)(struct NetDevice *netdev, WifiTxEapol *txData); + uint32_t (*receiveEapol)(struct NetDevice *netdev, WifiRxEapol *rxData); + uint32_t (*changeVirtualIntf)(struct NetDevice *netdev, uint8_t iftype, uint32_t *flags, + struct VifParams *params); + uint32_t (*addKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *mac_addr, + struct KeyParams *params); + uint32_t (*delKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr); + uint32_t (*setDefaultKey)(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicast); + uint32_t (*setDefaultMgmtKey)(struct NetDevice *netdev, uint8_t keyIndex); +} WiFiBaseFeatureOps; + +struct WifiBaseFeature { + struct WifiFeature fe; + WiFiBaseFeatureOps ops; +}; + + +struct WifiModule *HdfGetWifiModule(void); +struct WifiBaseFeature *WifiBaseGetFeature(const struct WifiModule *module); +struct WifiFeature *GetFeature(const struct WifiModule *module, uint16_t featureType); +int32_t DeInitFeatures(struct WifiModule *module); +int32_t InitFeatures(struct WifiModule *module); + +#define RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, opsName) do { \ + if (macOps->opsName == NULL) { \ + HDF_LOGE("macOps" #opsName "not implement"); \ + return HDF_ERR_INVALID_OBJECT; \ + } \ + } while (0) + +#define RETURN_IF_MACOPS_NOT_REGISTERED(macOps) do { \ + if (macOps == NULL) { \ + HDF_LOGE("macOps not registered"); \ + return HDF_ERR_INVALID_OBJECT; \ + } \ + } while (0) + +#ifdef __cplusplus +} +#endif +#endif // #ifndef _HDF_WIFI_FEATURE_H_ \ No newline at end of file diff --git a/model/network/wifi/module/wifi_feature.c b/model/network/wifi/module/wifi_feature.c new file mode 100755 index 00000000..706527bd --- /dev/null +++ b/model/network/wifi/module/wifi_feature.c @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "wifi_module.h" + +#if __cplusplus +extern "C" { +#endif + +struct WifiFeature *GetFeature(const struct WifiModule *module, uint16_t featureType) +{ + if ((module == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) || (module->feList == NULL)) { + return NULL; + } + return module->feList->fe[featureType]; +} + +int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData) +{ + if ((module == NULL) || (featureData == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) + || (module->feList == NULL)) { + HDF_LOGE("%s: para error", __func__); + return HDF_FAILURE; + } + module->feList->fe[featureType] = (struct WifiFeature *)featureData; + if (featureData->init != NULL) { + return featureData->init(featureData); + } + + HDF_LOGE("%s: featureData null", __func__); + return HDF_FAILURE; +} + +int32_t DelFeature(struct WifiModule *module, uint16_t featureType) +{ + struct WifiFeature *featureData = NULL; + if ((module == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) || (module->feList == NULL)) { + HDF_LOGE("%s: para error", __func__); + return HDF_FAILURE; + } + + featureData = module->feList->fe[featureType]; + if ((featureData != NULL) && (featureData->deInit != NULL)) { + featureData->deInit(module->feList->fe[featureType]); + featureData = NULL; + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +int32_t DeInitFeatures(struct WifiModule *module) +{ + if ((module == NULL) || (module->feList == NULL)) { + HDF_LOGE("%s: no module", __func__); + return HDF_FAILURE; + } + // make sure the features should be free firstly + for (int32_t i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { + if ((module->feList->fe[i] != NULL) && (module->feList->fe[i]->deInit != NULL)) { + module->feList->fe[i]->deInit(module->feList->fe[i]); + } + } + + return HDF_SUCCESS; +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/model/network/wifi/module/wifi_module.c b/model/network/wifi/module/wifi_module.c new file mode 100755 index 00000000..60dff60a --- /dev/null +++ b/model/network/wifi/module/wifi_module.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "wifi_module.h" +#include "wifi_base.h" +#include "hdf_wifi_product.h" +#include "securec.h" +#if __cplusplus +extern "C" { +#endif + +struct WifiModule *HdfGetWifiModule(void) +{ + struct HdfWifiProductData *productData = HdfWifiGetProduct(); + + if (productData == NULL) { + return NULL; + } + return productData->module; +} + +int32_t UpdateWiFiModule(struct WifiModule *module) +{ + (void)module; + return HDF_SUCCESS; +} + +void WifiModuleDelete(struct WifiModule *module) +{ + if (module == NULL) { + return; + } + if ((module->iface != NULL) && (module->iface->deInit != NULL)) { + module->iface->deInit(module); + OsalMemFree(module->iface); + } + + OsalMemFree(module); + return; +} + +struct WifiModule *WifiModuleCreate(const struct HdfConfigWifiModuleConfig *config) +{ + int32_t ret; + struct WifiModuleIface *iface = NULL; + struct WifiModule *module = OsalMemAlloc(sizeof(*module)); + if (module == NULL) { + HDF_LOGE("%s: no memory for module", __func__); + goto error; + } + (void)memset_s(module, sizeof(*module), 0, sizeof(*module)); + + iface = OsalMemAlloc(sizeof(*iface)); + if (iface == NULL) { + HDF_LOGE("%s: no memory for module iface", __func__); + goto error; + } + + iface->init = InitFeatures; + iface->deInit = DeInitFeatures; + iface->updateModule = UpdateWiFiModule; + iface->addFeature = AddFeature; + iface->delFeature = DelFeature; + module->modulePrivate = NULL; + module->iface = iface; + module->moduleConfig.hslConfig = config; + + ret = module->iface->init(module); + if (ret != 0) { + HDF_LOGE("%s: module int error ret=%d", __func__, ret); + goto error; + } + return module; +error: + WifiModuleDelete(module); + return NULL; +} + +#ifdef __cplusplus +} +#endif + diff --git a/model/network/wifi/netdevice/net_device.c b/model/network/wifi/netdevice/net_device.c new file mode 100755 index 00000000..a72bf630 --- /dev/null +++ b/model/network/wifi/netdevice/net_device.c @@ -0,0 +1,469 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "net_device.h" + +#include +#include +#include "securec.h" + +#include "osal_mem.h" +#include "net_device_impl.h" +#include "net_device_adapter.h" + +#define HDF_LOG_TAG "NetDevice" + +static struct NetDeviceImpl *g_netDeviceImplTable[MAX_NETDEVICE_COUNT] = {NULL}; + +static bool FindAvailableTable(int32_t *index) +{ + if (index == NULL) { + HDF_LOGE("Find Available table index error!"); + return false; + } + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] == NULL) { + *index = i; + return true; + } + } + return false; +} + +static bool AddNetDeviceImplToTable(int32_t index, struct NetDeviceImpl *netDeviceImpl) +{ + if (index >= MAX_NETDEVICE_COUNT) { + HDF_LOGE("%s error because of not enough space!", __func__); + return false; + } + g_netDeviceImplTable[index] = netDeviceImpl; + return true; +} + +static void DeleteNetDeviceImplFromTable(const struct NetDeviceImpl *netDeviceImpl) +{ + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] == netDeviceImpl) { + g_netDeviceImplTable[i] = NULL; + return; + } + } + return; +} + +static struct NetDeviceImpl *InitNetDeviceImpl(NetDevice *nd, NetIfCategory ifCategory) +{ + struct NetDeviceImpl *ndImpl = NULL; + if (nd == NULL) { + return NULL; + } + ndImpl = (struct NetDeviceImpl *)OsalMemCalloc(sizeof(struct NetDeviceImpl)); + if (ndImpl == NULL) { + HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); + return NULL; + } + (void)memset_s(ndImpl, sizeof(struct NetDeviceImpl), 0, sizeof(struct NetDeviceImpl)); + + ndImpl->netDevice = nd; + if (ifCategory == LITE_OS) { + if (RegisterLiteNetDeviceImpl(ndImpl) != HDF_SUCCESS) { + HDF_LOGE("%s fail: resiter lite impl fail!", __func__); + OsalMemFree(ndImpl); + ndImpl = NULL; + } + } else { + HDF_LOGE("%s fail: resister not support!", __func__); + OsalMemFree(ndImpl); + ndImpl = NULL; + } + return ndImpl; +} + +static void DeInitNetDeviceImpl(struct NetDeviceImpl *netDeviceImpl) +{ + if (netDeviceImpl == NULL) { + HDF_LOGE("%s success : already free!", __func__); + return; + } + + /* release osPrivate */ + if (netDeviceImpl->interFace != NULL && netDeviceImpl->interFace->deInit != NULL) { + netDeviceImpl->interFace->deInit(netDeviceImpl); + } + + /* step 1 : release interFace. step 2 : release netdevice */ + if (netDeviceImpl->netDevice != NULL) { + if (netDeviceImpl->netDevice->netifCateg == LITE_OS) { + UnRegisterLiteNetDeviceImpl(netDeviceImpl); + } else { + HDF_LOGE("%s fail: unregister not support!", __func__); + } + OsalMemFree(netDeviceImpl->netDevice); + netDeviceImpl->netDevice = NULL; + } + + /* last release netDeviceImpl */ + OsalMemFree(netDeviceImpl); + HDF_LOGI("%s success!", __func__); + return; +} + +static struct NetDeviceImpl *GetImplByNetDevice(const struct NetDevice *netDevice) +{ + struct NetDeviceImpl *ndImpl = NULL; + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { + if (netDevice == g_netDeviceImplTable[i]->netDevice) { + ndImpl = g_netDeviceImplTable[i]; + return ndImpl; + } + } + } + HDF_LOGE("Don't Get Impl by netdevice"); + return ndImpl; +} + +struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory ifCategory) +{ + NetDevice *netDevice = NULL; + int32_t index = 0; + if ((ifName == NULL) || (strlen(ifName) != len) || (strlen(ifName) > IFNAMSIZ - 1)) { + HDF_LOGE("%s fail: ifName = null or len not right!", __func__); + return NULL; + } + netDevice = (NetDevice *)OsalMemCalloc(sizeof(NetDevice)); + if (netDevice == NULL) { + HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); + return NULL; + } + (void)memset_s(netDevice, sizeof(NetDevice), 0, sizeof(NetDevice)); + if (memcpy_s(netDevice->name, IFNAMSIZ, ifName, len + 1) != EOK) { + HDF_LOGE("%s fail: memcpy_s fail!", __func__); + OsalMemFree(netDevice); + return NULL; + } + netDevice->netifCateg = ifCategory; + struct NetDeviceImpl *ndImpl = InitNetDeviceImpl(netDevice, ifCategory); + if (ndImpl == NULL) { + HDF_LOGE("%s fail: InitNetDeviceImpl fail!", __func__); + OsalMemFree(netDevice); + return NULL; + } + if (FindAvailableTable(&index)) { + AddNetDeviceImplToTable(index, ndImpl); + } else { + DeInitNetDeviceImpl(ndImpl); + HDF_LOGE("%s fail: Not extra table.", __func__); + return NULL; + } + /* INIT OSPrivate */ + int32_t ret = HDF_FAILURE; + if (ndImpl->interFace != NULL && ndImpl->interFace->init != NULL) { + ret = ndImpl->interFace->init(ndImpl); + } + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s fail : interface->init fail!", __func__); + DeleteNetDeviceImplFromTable(ndImpl); + DeInitNetDeviceImpl(ndImpl); + return NULL; + } + HDF_LOGI("Init Net Device suncess!"); + return netDevice; +} + +int32_t NetDeviceDeInit(struct NetDevice *netDevice) +{ + if (netDevice == NULL) { + HDF_LOGI("%s success: already deinit!", __func__); + return HDF_SUCCESS; + } + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL) { + HDF_LOGI("%s success: already free.", __func__); + OsalMemFree(netDevice); + return HDF_SUCCESS; + } + DeleteNetDeviceImplFromTable(ndImpl); + DeInitNetDeviceImpl(ndImpl); + return HDF_SUCCESS; +} + +int32_t NetDeviceAdd(struct NetDevice *netDevice, Protocol80211IfType ifType) +{ + struct NetDeviceImplOp *op = NULL; + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL) { + HDF_LOGE("%s fail: netDevice not exist!", __func__); + return HDF_ERR_INVALID_PARAM; + } + op = ndImpl->interFace; + if (op == NULL || op->add == NULL) { + HDF_LOGE("%s fail: Impl Add not exist.", __func__); + return HDF_ERR_INVALID_PARAM; + } + return op->add(ndImpl, ifType); +} + +int32_t NetDeviceDelete(struct NetDevice *netDevice) +{ + struct NetDeviceImplOp *op = NULL; + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL) { + HDF_LOGE("%s fail: netDevice not exist!", __func__); + return HDF_ERR_INVALID_PARAM; + } + op = ndImpl->interFace; + if (op == NULL || op->delete == NULL) { + HDF_LOGE("%s fail: Impl op Delete exist.", __func__); + return HDF_ERR_INVALID_PARAM; + } + return op->delete(ndImpl); +} + +struct NetDevice *NetDeviceGetInstByName(const char *name) +{ + if (name == NULL) { + HDF_LOGE("%s fail: name = NULL.", __func__); + return NULL; + } + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { + if (strcmp(g_netDeviceImplTable[i]->netDevice->name, name) == 0) { + return g_netDeviceImplTable[i]->netDevice; + } + } + } + HDF_LOGE("%s fail: name not exist.", __func__); + return NULL; +} + +bool NetDeviceIsAnyInstRunning(void) +{ + struct NetDevice *netDev = NULL; + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { + netDev = g_netDeviceImplTable[i]->netDevice; + if ((GET_NET_DEV_FLAGS(netDev) & NET_DEVICE_IFF_RUNNING) != 0) { + return true; + } + } + } + return false; +} + +bool NetDeviceIsInstRunning(const struct NetDevice *netDevice) +{ + if (netDevice == NULL) { + return false; + } + if ((GET_NET_DEV_FLAGS(netDevice) & NET_DEVICE_IFF_RUNNING) != 0) { + return true; + } + return false; +} + +uint32_t NetDevGetRegisterCount(void) +{ + uint32_t count = 0; + for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { + count++; + } + } + return count; +} + +uint32_t NetDeviceGetCap(void) +{ + return MAX_NETDEVICE_COUNT; +} + +struct NetDevice *NetDeviceGetInstByIndex(uint32_t index) +{ + if (index < MAX_NETDEVICE_COUNT) { + if (g_netDeviceImplTable[index] != NULL) { + return g_netDeviceImplTable[index]->netDevice; + } else { + return NULL; + } + } + return NULL; +} + +int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, const IpV4Addr *netMask, + const IpV4Addr *gw) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->setIpAddr != NULL) { + return ndImpl->interFace->setIpAddr(ndImpl, ipAddr, netMask, gw); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +static int32_t NetIfRxImpl(const struct NetDevice *netDevice, struct NetBuf *buff, ReceiveFlage flage) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL || ndImpl->interFace == NULL || ndImpl->interFace->receive == NULL) { + HDF_LOGE("NetIfRxImpl fail : netdevice not exist!"); + return HDF_ERR_INVALID_PARAM; + } + ProcessingResult ret = PROCESSING_CONTINUE; + + /* to do driver special process */ +#if LOSCFG_NET_LWIP_SACK + if (netDevice->netDeviceIf != NULL && netDevice->netDeviceIf->specialEtherTypeProcess != NULL) { + ret = netDevice->netDeviceIf->specialEtherTypeProcess(netDevice, buff); + } +#endif + /* Sent to TCP/IP Stack. */ + if (ret == PROCESSING_CONTINUE) { + return ndImpl->interFace->receive(ndImpl, buff, flage); + } else if (ret == PROCESSING_COMPLETE) { + HDF_LOGI("NetIfRxImpl specialEtherType Process not need TCP/IP stack!"); + return HDF_SUCCESS; + } else { + HDF_LOGE("NetIfRxImpl specialEtherType Process error"); + return HDF_FAILURE; + } +} + +int32_t NetIfRx(const struct NetDevice *netDevice, struct NetBuf *buff) +{ + return NetIfRxImpl(netDevice, buff, NO_IN_INTERRUPT); +} + +int32_t NetIfRxNi(const struct NetDevice *netDevice, struct NetBuf *buff) +{ + return NetIfRxImpl(netDevice, buff, IN_INTERRUPT); +} + +int32_t NetIfSetStatus(const struct NetDevice *netDevice, NetIfStatus status) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->setStatus != NULL) { + return ndImpl->interFace->setStatus(ndImpl, status); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfSetLinkStatus(const struct NetDevice *netDevice, NetIfLinkStatus status) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->setLinkStatus != NULL) { + return ndImpl->interFace->setLinkStatus(ndImpl, status); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfDhcpsStart(const struct NetDevice *netDevice, char *ip, uint16_t ipNum) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->dhcpsStart != NULL) { + return ndImpl->interFace->dhcpsStart(ndImpl, ip, ipNum); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfDhcpsStop(const struct NetDevice *netDevice) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->dhcpsStop != NULL) { + return ndImpl->interFace->dhcpsStop(ndImpl); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfDhcpStart(const struct NetDevice *netDevice) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->dhcpStart != NULL) { + return ndImpl->interFace->dhcpStart(ndImpl); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfDhcpStop(const struct NetDevice *netDevice) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->dhcpStop != NULL) { + return ndImpl->interFace->dhcpStop(ndImpl); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +int32_t NetIfDhcpIsBound(const struct NetDevice *netDevice) +{ + struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->dhcpIsBound != NULL) { + return ndImpl->interFace->dhcpIsBound(ndImpl); + } + HDF_LOGE("%s: netDevice not init or already free.", __func__); + return HDF_ERR_INVALID_PARAM; +} + +/* + * Alloc a net buffer for the net device and reserve headroom depended on net device setting + * + * @param : dev The net device + * size The net buffer size + * @return : A new net buffer on success or NULL on fail + */ +struct NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size) +{ + uint32_t reserve = 0; + struct NetBuf *nb = NULL; + + if (dev != NULL) { + reserve = dev->neededHeadRoom + dev->neededTailRoom; + } + + size += reserve; + + nb = NetBufAlloc(size); + if (nb == NULL) { + return NULL; + } + + if (dev != NULL) { + nb->dev = (void *)dev; + NetBufPop(nb, E_TAIL_BUF, dev->neededHeadRoom); + NetBufPop(nb, E_DATA_BUF, dev->neededHeadRoom); + } + + return nb; +} diff --git a/model/network/wifi/netdevice/net_device_impl.h b/model/network/wifi/netdevice/net_device_impl.h new file mode 100755 index 00000000..ec5080e4 --- /dev/null +++ b/model/network/wifi/netdevice/net_device_impl.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_NET_DEVICE_IMPL_MODULE_H +#define HDF_NET_DEVICE_IMPL_MODULE_H + +#include +#include +#include +#include "net_device.h" + +#define MAX_NETDEVICE_COUNT 20 + +struct NetDeviceImpl { + struct NetDevice *netDevice; + struct NetDeviceImplOp *interFace; + void *osPrivate; +}; +typedef enum { + NO_IN_INTERRUPT, + IN_INTERRUPT, + MAX_RECEIVE_FLAGE +} ReceiveFlage; + +struct NetDeviceImplOp { + int32_t (*init)(struct NetDeviceImpl *netDevice); + int32_t (*deInit)(struct NetDeviceImpl *netDevice); + int32_t (*add)(struct NetDeviceImpl *netDevice, Protocol80211IfType ifType); + int32_t (*delete)(struct NetDeviceImpl *netDevice); + int32_t (*setStatus)(struct NetDeviceImpl *netDevice, NetIfStatus status); + int32_t (*setLinkStatus)(struct NetDeviceImpl *netDevice, NetIfLinkStatus status); + int32_t (*receive)(struct NetDeviceImpl *netDevice, struct NetBuf *buff, ReceiveFlage flage); + int32_t (*setIpAddr)(struct NetDeviceImpl *netDevice, const IpV4Addr *ipAddr, const IpV4Addr *netMask, + const IpV4Addr *gw); + int32_t (*dhcpsStart)(struct NetDeviceImpl *netDevice, char *ip, uint16_t ipNum); + int32_t (*dhcpsStop)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpStart)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpStop)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpIsBound)(struct NetDeviceImpl *netDevice); +}; + +#endif /* HDF_NET_DEVICE_IMPL_MODULE_H */ \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100755 index 00000000..008d5e15 --- /dev/null +++ b/readme.md @@ -0,0 +1 @@ +详见:https://gitee.com/openharmony/docs/blob/master/readme/驱动子系统README.md diff --git a/support/platform/include/gpio_core.h b/support/platform/include/gpio_core.h new file mode 100755 index 00000000..62439e99 --- /dev/null +++ b/support/platform/include/gpio_core.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef GPIO_CORE_H +#define GPIO_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "gpio_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct GpioCntlr; +struct GpioMethod; + +struct GpioCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + void *priv; + struct GpioMethod *ops; +}; + +struct GpioMethod { + int32_t (*request)(struct GpioCntlr *cntlr, uint16_t gpio); + int32_t (*release)(struct GpioCntlr *cntlr, uint16_t gpio); + int32_t (*write)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val); + int32_t (*read)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val); + int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir); + int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir); + int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq); + int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); + int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t gpio); + int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t gpio); + int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t gpio); +}; + +/** + * @brief Add the Gpio Controller to HDF, and do some checking. + * + * @param cntlr Indicates the GPIO controller device. + * + * @return Returns 0 on success; returns a negative value otherwise. + * @since 1.0 + */ +int32_t GpioCntlrAdd(struct GpioCntlr *cntlr); + +/** + * @brief Remove the Gpio Controller from HDF. + * + * @param cntlr Indicates the I2C controller device. + * + * @since 1.0 + */ +void GpioCntlrRemove(struct GpioCntlr *cntlr); + +/** + * @brief Turn HdfDeviceObject to an GpioCntlr. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the GpioCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct GpioCntlr *GpioCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct GpioCntlr *)device->service; +} + +int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val); + +int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val); + +int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir); + +int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir); + +int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq); + +int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); + +int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t gpio); + +int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t gpio); + +int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t gpio); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* GPIO_CORE_H */ diff --git a/support/platform/include/i2c_core.h b/support/platform/include/i2c_core.h new file mode 100755 index 00000000..a881b1c1 --- /dev/null +++ b/support/platform/include/i2c_core.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef I2C_CORE_H +#define I2C_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "i2c_if.h" +#include "osal_mutex.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct I2cCntlr; +struct I2cMethod; + +struct I2cCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct OsalMutex lock; + int16_t busId; + void *priv; + struct I2cMethod *ops; +}; + +struct I2cMethod { + /** + * @brief Execute one or more I2C messages. + * + * @param cntlr Indicates the I2C controller device. + * @param msgs Indicates the {@link I2cMsg} message array. + * @param count Indicates the length of the message array. + * + * @return Returns the number of transferred message structures if the operation is successful; + * returns a negative value otherwise. + * @see I2cMsg + * @since 1.0 + */ + int32_t (*transfer)(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); +}; + +/** + * @brief Bind to a HdfDeviceObject, and do some necessary check + * + * @param cntlr Indicates the I2C controller device. + * @param device The HdfDeviceObject of this I2cCntlr. + * + * @return Returns 0 on success; returns a negative value otherwise. + * @since 1.0 + */ +int32_t I2cCntlrAdd(struct I2cCntlr *cntlr); + +/** + * @brief Create a new I2cCntlr struct, and bind it to a HdfDeviceObject. + * + * @param cntlr Indicates the I2C controller device. + * + * @since 1.0 + */ +void I2cCntlrRemove(struct I2cCntlr *cntlr); + +/** + * @brief Turn I2cCntlr to a HdfDeviceObject. + * + * @param cntlr Indicates the I2C controller device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *I2cCntlrToDevice(struct I2cCntlr *cntlr) +{ + return (cntlr == NULL) ? NULL : cntlr->device; +} + +/** + * @brief Turn HdfDeviceObject to an I2cCntlr. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the I2cCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct I2cCntlr *I2cCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct I2cCntlr *)device->service; +} + +int32_t I2cCntlrTransfer(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* I2C_CORE_H */ diff --git a/support/platform/include/rtc_base.h b/support/platform/include/rtc_base.h new file mode 100755 index 00000000..6b720efd --- /dev/null +++ b/support/platform/include/rtc_base.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_RTC_BASE_H +#define HDF_RTC_BASE_H + +#include "rtc_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define IS_LEAP_YEAR(year) (((((year) % 4) == 0) && (((year) % 100) != 0)) || (((year) % 400) == 0)) +#define RTC_YEAR_DAYS(year) (IS_LEAP_YEAR(year) ? 366 : 365) + +#define RTC_DAY_SECONDS 86400ULL /* 24 hours * 60 minutes * 60 seconds */ +#define RTC_DAY_HOURS 24 /* 24 hours */ +#define RTC_HOUR_SECONDS 3600UL /* 60 minutes * 60 seconds */ +#define RTC_MAX_MONTH 12 +#define RTC_MAX_WEEKDAY 7 +#define RTC_GREAT_MONTH_DAY 31 +#define RTC_SMALL_MONTH_DAY 30 +#define RTC_TWO_MONTH_DAY 28 +#define RTC_MAX_HOUR 24 +#define RTC_MAX_MINUTE 60UL +#define RTC_MAX_SECOND 60UL +#define RTC_MAX_MS 1000 +#define RTC_UNIT_DIFF 1 +#define RTC_ODD_MONTH_MASK 0x1 +#define RTC_TIME_UNIT 60 +#define RTC_FALSE 0 +#define RTC_TRUE 1 + +#define RTC_BEGIN_YEAR 1970 /* UTC started at 00:00:00 January 1, 1970 */ +#define RTC_BEGIN_WEEKDAY 0x04 /* Thursday January 1, 1970 */ + +#define IS_INVALID_YEAR(year) ((year) < RTC_BEGIN_YEAR) +#define IS_INVALID_MONTH(m) (((m) < RTC_JANUARY) || ((m) > RTC_MAX_MONTH)) +#define IS_INVALID_WEEKDAY(wd) (((wd) < 1) || ((wd) > RTC_MAX_WEEKDAY)) +#define IS_INVALID_HOUR(hour) (((hour) < 0) || ((hour) >= RTC_MAX_HOUR)) +#define IS_INVALID_MIN(min) (((min) < 0) || ((min) >= RTC_MAX_MINUTE)) +#define IS_INVALID_SECOND(s) (((s) < 0) || ((s) >= RTC_MAX_SECOND)) +#define IS_INVALID_MS(ms) (((ms) < 0) || ((ms) >= RTC_MAX_MS)) + +enum RtcMonth { + RTC_JANUARY = 1, + RTC_FEBRUARY, + RTC_MARCH, + RTC_APRIL, + RTC_MAY, + RTC_JUNE, + RTC_JULY, + RTC_AUGUST, + RTC_SEPTEMBER, + RTC_OCTOBER, + RTC_NOVEMBER, + RTC_DECEMBER, +}; + +uint8_t RtcGetMonthDays(const uint8_t isLeapYear, const uint8_t month); +uint8_t RtcIsInvalidDay(const uint8_t day, const uint8_t month, const uint16_t year); +uint8_t RtcIsInvalid(const struct RtcTime *time); +uint8_t RtcGetWeekDay(const struct RtcTime *time); +uint64_t RtcTimeToTimestamp(const struct RtcTime *time); +void TimestampToRtcTime(struct RtcTime *time, const uint64_t seconds); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* HDF_RTC_BASE_H */ diff --git a/support/platform/include/rtc_core.h b/support/platform/include/rtc_core.h new file mode 100755 index 00000000..7545a22e --- /dev/null +++ b/support/platform/include/rtc_core.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RTC_CORE_H +#define RTC_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_mutex.h" +#include "rtc_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct RtcHost; +struct RtcMethod; + +struct RtcHost { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct RtcMethod *method; + void *data; +}; + +struct RtcMethod { + int32_t (*ReadTime)(struct RtcHost *host, struct RtcTime *time); + int32_t (*WriteTime)(struct RtcHost *host, const struct RtcTime *time); + int32_t (*ReadAlarm)(struct RtcHost *host, enum RtcAlarmIndex alarmIndex, struct RtcTime *time); + int32_t (*WriteAlarm)(struct RtcHost *host, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time); + int32_t (*RegisterAlarmCallback)(struct RtcHost *host, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb); + int32_t (*AlarmInterruptEnable)(struct RtcHost *host, enum RtcAlarmIndex alarmIndex, uint8_t enable); + int32_t (*GetFreq)(struct RtcHost *host, uint32_t *freq); + int32_t (*SetFreq)(struct RtcHost *host, uint32_t freq); + int32_t (*Reset)(struct RtcHost *host); + int32_t (*ReadReg)(struct RtcHost *host, uint8_t usrDefIndex, uint8_t *value); + int32_t (*WriteReg)(struct RtcHost *host, uint8_t usrDefIndex, uint8_t value); +}; + +int RtcSetHostMethod(struct RtcHost *host, struct RtcMethod *method); +struct RtcHost *RtcHostCreate(struct HdfDeviceObject *device); +void RtcHostDestroy(struct RtcHost *host); + +static inline struct RtcHost *RtcHostFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct RtcHost *)device->service; +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* RTC_CORE_H */ diff --git a/support/platform/include/sdio_core.h b/support/platform/include/sdio_core.h new file mode 100755 index 00000000..d5039892 --- /dev/null +++ b/support/platform/include/sdio_core.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef SDIO_CORE_H +#define SDIO_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "sdio_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct SdioCntlr; +struct SdioMethod; + +struct SdioConfigData { + uint32_t funcNum; + uint32_t vendorId; + uint32_t deviceId; +}; + +struct SdioCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct SdioConfigData configData; + void *priv; + struct SdioMethod *method; +}; + +/** + * @brief sdio host device operations. + * These methods need to be filled up by specific paltform. + */ +struct SdioMethod { + int32_t (*incrAddrReadBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*incrAddrWriteBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*fixedAddrReadBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*fixedAddrWriteBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*func0ReadBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*func0WriteBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*setBlockSize)(struct SdioCntlr *, uint32_t); + int32_t (*getCommonInfo)(struct SdioCntlr *, SdioCommonInfo *, uint32_t); + int32_t (*setCommonInfo)(struct SdioCntlr *, SdioCommonInfo *, uint32_t); + int32_t (*flushData)(struct SdioCntlr *); + void (*claimHost)(struct SdioCntlr *); + void (*releaseHost)(struct SdioCntlr *); + int32_t (*enableFunc)(struct SdioCntlr *); + int32_t (*disableFunc)(struct SdioCntlr *); + int32_t (*claimIrq)(struct SdioCntlr *, SdioIrqHandler *); + int32_t (*releaseIrq)(struct SdioCntlr *); + int32_t (*findFunc)(struct SdioCntlr *, struct SdioConfigData *); +}; + +/** + * @brief Create a new SdioCntlr struct, and bind it to a HdfDeviceObject. + * + * @param device The HdfDeviceObject of this SdioCntlr. + * + * @return Retrns the pointer of the SdioCntlr struct on success; returns NULL otherwise. + * @since 1.0 + */ +struct SdioCntlr *SdioCntlrCreateAndBind(struct HdfDeviceObject *device); + +/** + * @brief Destroy a SdioCntlr struct, you should always destroy it with this function. + * + * @param cntlr Indicates the SDIO cntlr device. + * + * @since 1.0 + */ +void SdioCntlrDestroy(struct SdioCntlr *cntlr); + +/** + * @brief Fill config data for an SdioCntlr. + * + * @param device The HdfDeviceObject of this SdioCntlr. + * @param configData The config data of this SdioCntlr. + * + * @return Retrns zero on success; returns negative errno otherwise. + * @since 1.0 + */ +int32_t SdioFillConfigData(struct HdfDeviceObject *device, struct SdioConfigData *configData); + +/** + * @brief Turn SdioCntlr to a HdfDeviceObject. + * + * @param cntlr Indicates the SDIO cntlr device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *SdioCntlrToDevice(struct SdioCntlr *cntlr) +{ + return (cntlr == NULL) ? NULL : cntlr->device; +} + +/** + * @brief Turn HdfDeviceObject to an SdioCntlr. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the SdioCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct SdioCntlr *SdioCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct SdioCntlr *)device->service; +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* SDIO_CORE_H */ diff --git a/support/platform/include/spi_core.h b/support/platform/include/spi_core.h new file mode 100755 index 00000000..a3051809 --- /dev/null +++ b/support/platform/include/spi_core.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef SPI_CORE_H +#define SPI_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_dlist.h" +#include "spi_if.h" +#include "osal_mutex.h" + +struct SpiCntlr; +struct SpiCntlrMethod; + +struct SpiCntlrMethod { + int32_t (*GetCfg)(struct SpiCntlr *, struct SpiCfg *); + int32_t (*SetCfg)(struct SpiCntlr *, struct SpiCfg *); + int32_t (*Transfer)(struct SpiCntlr *, struct SpiMsg *, uint32_t); +}; + +struct SpiCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + uint32_t busNum; + uint32_t curCs; + struct OsalMutex lock; + struct SpiCntlrMethod *method; + void *priv; +}; + +struct SpiDev { + struct SpiCntlr *cntlr; + struct DListHead list; + uint32_t csNum; + uint32_t maxSpeedHz; + uint16_t mode; + uint8_t bitsPerWord; + uint8_t transferMode; +}; + +struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device); +void SpiCntlrDestroy(struct SpiCntlr *cntlr); + +/** + * @brief Turn SpiCntlr to a HdfDeviceObject. + * + * @param cntlr Indicates the SPI cntlr device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *SpiCntlrToDevice(struct SpiCntlr *cntlr) +{ + return (cntlr == NULL) ? NULL : cntlr->device; +} + +/** + * @brief Turn HdfDeviceObject to an SpiCntlr. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the SpiCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct SpiCntlr *SpiCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct SpiCntlr *)device->service; +} + +int32_t SpiCntlrTransfer(struct SpiCntlr *, uint32_t, struct SpiMsg *, uint32_t); +int32_t SpiCntlrSetCfg(struct SpiCntlr *, uint32_t, struct SpiCfg *); +int32_t SpiCntlrGetCfg(struct SpiCntlr *, uint32_t, struct SpiCfg *); + +#endif /* SPI_CORE_H */ diff --git a/support/platform/include/uart_core.h b/support/platform/include/uart_core.h new file mode 100755 index 00000000..10246b32 --- /dev/null +++ b/support/platform/include/uart_core.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UART_CORE_H +#define UART_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "uart_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief uart device operations. + */ +struct UartHost { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + uint32_t num; + void *priv; + struct UartHostMethod *method; +}; + +struct UartHostMethod { + int32_t (*Init)(struct UartHost *host); + int32_t (*Deinit)(struct UartHost *host); + int32_t (*Read)(struct UartHost *host, uint8_t *data, uint32_t size); + int32_t (*Write)(struct UartHost *host, uint8_t *data, uint32_t size); + int32_t (*GetBaud)(struct UartHost *host, uint32_t *baudRate); + int32_t (*SetBaud)(struct UartHost *host, uint32_t baudRate); + int32_t (*GetAttribute)(struct UartHost *host, struct UartAttribute *attribute); + int32_t (*SetAttribute)(struct UartHost *host, struct UartAttribute *attribute); + int32_t (*SetTransMode)(struct UartHost *handle, enum UartTransMode mode); +}; + +struct UartHost *UartHostCreate(struct HdfDeviceObject *device); +void UartHostDestroy(struct UartHost *host); + +/** + * @brief Turn UartHost to a HdfDeviceObject. + * + * @param host Indicates the Uart host device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *UartHostToDevice(struct UartHost *host) +{ + return (host == NULL) ? NULL : host->device; +} + +/** + * @brief Turn HdfDeviceObject to an UartHost. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the UartHost on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct UartHost *UartHostFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct UartHost *)device->service; +} + +static inline int32_t UartHostInit(struct UartHost *host) +{ + if (host == NULL || host->method == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (host->method->Init != NULL) { + return host->method->Init(host); + } + return HDF_SUCCESS; +} + +static inline int32_t UartHostDeinit(struct UartHost *host) +{ + if (host == NULL || host->method == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (host->method->Deinit != NULL) { + return host->method->Deinit(host); + } + return HDF_SUCCESS; +} + +static inline int32_t UartHostRead(struct UartHost *host, uint8_t *data, uint32_t size) +{ + if (host == NULL || host->method == NULL || host->method->Read == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->Read(host, data, size); +} + +static inline int32_t UartHostWrite(struct UartHost *host, uint8_t *data, uint32_t size) +{ + if (host == NULL || host->method == NULL || host->method->Write == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->Write(host, data, size); +} + +static inline int32_t UartHostGetBaud(struct UartHost *host, uint32_t *baudRate) +{ + if (host == NULL || host->method == NULL || host->method->GetBaud == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->GetBaud(host, baudRate); +} + +static inline int32_t UartHostSetBaud(struct UartHost *host, uint32_t baudRate) +{ + if (host == NULL || host->method == NULL || host->method->SetBaud == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->SetBaud(host, baudRate); +} + +static inline int32_t UartHostGetAttribute(struct UartHost *host, struct UartAttribute *attribute) +{ + if (host == NULL || host->method == NULL || host->method->GetAttribute == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->GetAttribute(host, attribute); +} + +static inline int32_t UartHostSetAttribute(struct UartHost *host, struct UartAttribute *attribute) +{ + if (host == NULL || host->method == NULL || host->method->SetAttribute == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->SetAttribute(host, attribute); +} + +static inline int32_t UartHostSetTransMode(struct UartHost *host, enum UartTransMode mode) +{ + if (host == NULL || host->method == NULL || host->method->SetTransMode == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->SetTransMode(host, mode); +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* UART_CORE_H */ diff --git a/support/platform/include/watchdog_core.h b/support/platform/include/watchdog_core.h new file mode 100755 index 00000000..2450acca --- /dev/null +++ b/support/platform/include/watchdog_core.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WATCHDOG_CORE_H +#define WATCHDOG_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_spinlock.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct WatchdogCntlr; +struct WatchdogMethod; + +struct WatchdogCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + OsalSpinlock lock; + struct WatchdogMethod *ops; + int16_t wdtId; + void *priv; +}; + +struct WatchdogMethod { + int32_t (*getStatus)(struct WatchdogCntlr *wdt, int32_t *status); + int32_t (*setTimeout)(struct WatchdogCntlr *wdt, uint32_t seconds); + int32_t (*getTimeout)(struct WatchdogCntlr *wdt, uint32_t *seconds); + int32_t (*start)(struct WatchdogCntlr *wdt); + int32_t (*stop)(struct WatchdogCntlr *wdt); + int32_t (*feed)(struct WatchdogCntlr *wdt); +}; + +/** + * @brief Add a new WatchdogCntlr to HDF. + * + * @param cntlr The watchdog conroller to be added. + * + * @return Returns 0 on success; returns a negative value otherwise. + * @since 1.0 + */ +int32_t WatchdogCntlrAdd(struct WatchdogCntlr *cntlr); + +/** + * @brief Remove the watchdog controller from HDF. + * + * @param cntlr The watchdog controller to be removed. + * + * @since 1.0 + */ +void WatchdogCntlrRemove(struct WatchdogCntlr *cntlr); + + +/** + * @brief Turn HdfDeviceObject to an Watchdog. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the WatchdogCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct WatchdogCntlr *WatchdogCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct WatchdogCntlr *)device->service; +} + +/** + * @brief Turn WatchdogCntlr to a HdfDeviceObject. + * + * @param wdt Indicates the WATCHDOG wdt device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *WatchdogCntlrToDevice(struct WatchdogCntlr *wdt) +{ + return (wdt == NULL) ? NULL : wdt->device; +} + +int32_t WatchdogCntlrGetStatus(struct WatchdogCntlr *cntlr, int32_t *status); + +int32_t WatchdogCntlrStart(struct WatchdogCntlr *cntlr); + +int32_t WatchdogCntlrStop(struct WatchdogCntlr *cntlr); + +int32_t WatchdogCntlrSetTimeout(struct WatchdogCntlr *cntlr, uint32_t seconds); + +int32_t WatchdogCntlrGetTimeout(struct WatchdogCntlr *cntlr, uint32_t *seconds); + +int32_t WatchdogCntlrFeed(struct WatchdogCntlr *cntlr); + + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* WATCHDOG_CORE_H */ diff --git a/support/platform/src/gpio_core.c b/support/platform/src/gpio_core.c new file mode 100755 index 00000000..c139fa9f --- /dev/null +++ b/support/platform/src/gpio_core.c @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "gpio_core.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG gpio_core + +static struct GpioCntlr *g_cntlr; + +int32_t GpioCntlrAdd(struct GpioCntlr *cntlr) +{ + if (g_cntlr != NULL) { + HDF_LOGE("GpioCntlrAdd: already has a gpio controller!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->device == NULL) { + HDF_LOGE("GpioCntlrAdd: no device associated!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->ops == NULL) { + HDF_LOGE("GpioCntlrAdd: no ops supplied!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr->device->service = &cntlr->service; + g_cntlr = cntlr; + return HDF_SUCCESS; +} + +void GpioCntlrRemove(struct GpioCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + + if (cntlr->device == NULL) { + HDF_LOGE("GpioCntlrRemove: no device associated!\n"); + return; + } + + cntlr->device->service = NULL; + g_cntlr = NULL; +} + +int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->write == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->write(cntlr, gpio, val); +} + +int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->read == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + if (val == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return cntlr->ops->read(cntlr, gpio, val); +} + +int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->setDir == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->setDir(cntlr, gpio, dir); +} + +int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->getDir == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + if (dir == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return cntlr->ops->getDir(cntlr, gpio, dir); +} + +int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->toIrq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->toIrq(cntlr, gpio, irq); +} + +int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->setIrq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->setIrq(cntlr, gpio, mode, func, arg); +} + +int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t gpio) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->unsetIrq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->unsetIrq(cntlr, gpio); +} + +int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t gpio) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->enableIrq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->enableIrq(cntlr, gpio); +} + +int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t gpio) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->disableIrq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->disableIrq(cntlr, gpio); +} diff --git a/support/platform/src/gpio_if.c b/support/platform/src/gpio_if.c new file mode 100755 index 00000000..173ecb2f --- /dev/null +++ b/support/platform/src/gpio_if.c @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "gpio_if.h" +#include "devsvc_manager_clnt.h" +#include "gpio_core.h" +#include "hdf_base.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG gpio_if + +static struct GpioCntlr *GpioGetCntlr(void) +{ + static struct GpioCntlr *service = NULL; + + if (service != NULL) { + return service; + } + service = (struct GpioCntlr*)DevSvcManagerClntGetService("HDF_PLATFORM_GPIO"); + if (service == NULL) { + HDF_LOGE("GpioGetCntlr: get service fail!\n"); + } + return service; +} + + +int32_t GpioRead(uint16_t gpio, uint16_t *val) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + return GpioCntlrRead(cntlr, gpio, val); +} + +int32_t GpioWrite(uint16_t gpio, uint16_t val) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrWrite(cntlr, gpio, val); +} + +int32_t GpioSetDir(uint16_t gpio, uint16_t dir) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrSetDir(cntlr, gpio, dir); +} + +int32_t GpioGetDir(uint16_t gpio, uint16_t *dir) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrGetDir(cntlr, gpio, dir); +} + +int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrSetIrq(cntlr, gpio, mode, func, arg); +} + +int32_t GpioUnSetIrq(uint16_t gpio) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrUnsetIrq(cntlr, gpio); +} + +int32_t GpioEnableIrq(uint16_t gpio) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrEnableIrq(cntlr, gpio); +} + +int32_t GpioDisableIrq(uint16_t gpio) +{ + struct GpioCntlr *cntlr = GpioGetCntlr(); + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return GpioCntlrDisableIrq(cntlr, gpio); +} diff --git a/support/platform/src/i2c_core.c b/support/platform/src/i2c_core.c new file mode 100755 index 00000000..8f92858b --- /dev/null +++ b/support/platform/src/i2c_core.c @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "i2c_core.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG i2c_core + +int32_t I2cCntlrTransfer(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("I2cCntlrTransfer: cntlr is null\n"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->ops == NULL || cntlr->ops->transfer == NULL) { + HDF_LOGE("I2cCntlrTransfer: ops or transfer is null\n"); + return HDF_ERR_NOT_SUPPORT; + } + + ret = cntlr->ops->transfer(cntlr, msgs, count); + return ret; +} + +int32_t I2cCntlrAdd(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->device == NULL) { + HDF_LOGE("I2cCntlrAdd: no device associated!\n"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->ops == NULL) { + HDF_LOGE("I2cCntlrAdd: no ops supplied!\n"); + return HDF_ERR_INVALID_OBJECT; + } + if (OsalMutexInit(&cntlr->lock) != HDF_SUCCESS) { + HDF_LOGE("I2cCntlrAdd: init lock fail!\n"); + return HDF_FAILURE; + } + cntlr->device->service = &cntlr->service; + return HDF_SUCCESS; +} + +void I2cCntlrRemove(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + + if (cntlr->device == NULL) { + HDF_LOGE("I2cCntlrBind: no device associated!\n"); + return; + } + + cntlr->device->service = NULL; + (void)OsalMutexDestroy(&cntlr->lock); +} diff --git a/support/platform/src/i2c_if.c b/support/platform/src/i2c_if.c new file mode 100755 index 00000000..fdc8ad12 --- /dev/null +++ b/support/platform/src/i2c_if.c @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "i2c_if.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "i2c_core.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_LOG_TAG i2c_if + +#define SERVICE_NAME_LEN 32 +#define I2C_BUS_MAX 8 + +static struct I2cCntlr *I2cCntlrGetByNumber(int16_t num) +{ + struct I2cCntlr *cntlr = NULL; + char *cntlrName = NULL; + + if (num < 0 || num >= I2C_BUS_MAX) { + HDF_LOGE("I2cCntlrGetByNumber: invalid num:%d\n", num); + return NULL; + } + cntlrName = OsalMemCalloc(SERVICE_NAME_LEN + 1); + if (cntlrName == NULL) { + return NULL; + } + if (snprintf_s(cntlrName, SERVICE_NAME_LEN + 1, SERVICE_NAME_LEN, + "HDF_PLATFORM_I2C_%d", num) < 0) { + HDF_LOGE("I2cCntlrGetByNumber: format cntlr name fail!\n"); + OsalMemFree(cntlrName); + return NULL; + } + cntlr = (struct I2cCntlr *)DevSvcManagerClntGetService(cntlrName); + if (cntlr == NULL) { + HDF_LOGE("I2cCntlrGetByNumber: get cntlr fail!\n"); + } + OsalMemFree(cntlrName); + return cntlr; +} + +struct DevHandle *I2cOpen(int16_t number) +{ + struct DevHandle *handle = NULL; + struct I2cCntlr *cntlr = NULL; + + cntlr = I2cCntlrGetByNumber(number); + if (cntlr == NULL) { + return NULL; + } + handle = OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + return NULL; + } + handle->object = cntlr; + return handle; +} + +void I2cClose(struct DevHandle *handle) +{ + if (handle != NULL) { + handle->object = NULL; + OsalMemFree(handle); + } +} + +int32_t I2cTransfer(struct DevHandle *handle, struct I2cMsg *msgs, int16_t count) +{ + if (handle == NULL || handle->object == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + return I2cCntlrTransfer((struct I2cCntlr *)handle->object, msgs, count); +} diff --git a/support/platform/src/rtc_base.c b/support/platform/src/rtc_base.c new file mode 100755 index 00000000..00084299 --- /dev/null +++ b/support/platform/src/rtc_base.c @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_log.h" +#include "rtc_base.h" + +#define HDF_LOG_TAG rtc_base + +uint8_t RtcGetMonthDays(const uint8_t isLeapYear, const uint8_t month) +{ + uint8_t days; + uint8_t oddMonth; + + if (IS_INVALID_MONTH(month) || (isLeapYear > RTC_TRUE)) { + return 0; + } + + if (RTC_FEBRUARY == month) { + days = RTC_TWO_MONTH_DAY + isLeapYear; + } else { + oddMonth = (month > RTC_AUGUST) ? (month - RTC_UNIT_DIFF) : month; + days = (oddMonth & RTC_ODD_MONTH_MASK) ? RTC_GREAT_MONTH_DAY : RTC_SMALL_MONTH_DAY; + } + return days; +} + +uint8_t RtcIsInvalidDay(const uint8_t day, const uint8_t month, const uint16_t year) +{ + uint8_t MaxDay; + MaxDay = RtcGetMonthDays(IS_LEAP_YEAR(year), month); + + return ((day == 0) || (day > MaxDay)) ? RTC_TRUE : RTC_FALSE; +} + +uint8_t RtcIsInvalid(const struct RtcTime *time) +{ + if (time == NULL) { + HDF_LOGE("RtcIsInvalid: time null"); + return RTC_FALSE; + } + + return (IS_INVALID_YEAR(time->year) || IS_INVALID_MONTH(time->month) || + (RtcIsInvalidDay(time->day, time->month, time->year) == RTC_TRUE) || + IS_INVALID_HOUR(time->hour) || IS_INVALID_MIN(time->minute) || + IS_INVALID_SECOND(time->second) || IS_INVALID_MS(time->millisecond)); +} + +uint8_t RtcGetWeekDay(const struct RtcTime *time) +{ + uint32_t days; + int8_t month; + uint16_t year; + + if ((time == NULL) || IS_INVALID_MONTH(time->month) || IS_INVALID_YEAR(time->year) || + (RtcIsInvalidDay(time->day, time->month, time->year) == RTC_TRUE)) { + HDF_LOGE("RtcGetWeekDay: time invalid"); + return RTC_FALSE; + } + + days = time->day - RTC_UNIT_DIFF; + month = time->month; + while (--month >= RTC_JANUARY) { + days += RtcGetMonthDays(IS_LEAP_YEAR(time->year), month); + } + + year = time->year; + while (--year >= RTC_BEGIN_YEAR) { + days += RTC_YEAR_DAYS(year); + } + + return ((RTC_BEGIN_WEEKDAY + days - RTC_UNIT_DIFF) % RTC_MAX_WEEKDAY + RTC_UNIT_DIFF); +} + +uint64_t RtcTimeToTimestamp(const struct RtcTime *time) +{ + uint64_t seconds; + uint32_t days; + uint16_t year; + int8_t month; + + if (time == NULL) { + HDF_LOGE("RtcTimeToTimestamp: time null"); + return RTC_FALSE; + } + HDF_LOGD("RtcToTimestamp:year-month-day hour:min:second ms %04u-%02u-%02u %02u:%02u:%02u .%03u", + time->year, time->month, time->day, time->hour, time->minute, time->second, time->millisecond); + if (RtcIsInvalid(time) == RTC_TRUE) { + HDF_LOGE("RtcTimeToTimestamp: time invalid"); + return 0; + } + + seconds = ((uint64_t)time->hour * RTC_MAX_MINUTE + time->minute) * RTC_MAX_SECOND + time->second; + days = time->day - RTC_UNIT_DIFF; + month = time->month - RTC_UNIT_DIFF; + year = time->year; + + while (--month >= 0) { + days += RtcGetMonthDays(IS_LEAP_YEAR(time->year), month); + } + + while (--year >= RTC_BEGIN_YEAR) { + days += RTC_YEAR_DAYS(year); + } + + seconds += days * RTC_DAY_SECONDS; + return seconds; +} + +void TimestampToRtcTime(struct RtcTime *time, const uint64_t seconds) +{ + uint32_t daySeconds = (uint32_t)(seconds % RTC_DAY_SECONDS); + uint32_t days = (uint32_t)(seconds / RTC_DAY_SECONDS); + + if (time == NULL) { + HDF_LOGE("TimestampToRtcTime: rtc null!"); + return; + } + + time->year = RTC_BEGIN_YEAR; + while (days >= RTC_YEAR_DAYS(time->year)) { + days -= RTC_YEAR_DAYS(time->year); + time->year++; + } + + time->month = 0; + while (days >= RtcGetMonthDays(IS_LEAP_YEAR(time->year), time->month)) { + days -= RtcGetMonthDays(IS_LEAP_YEAR(time->year), time->month); + time->month++; + } + + time->day = days; + time->second = daySeconds % RTC_MAX_SECOND; + time->minute = (daySeconds % RTC_HOUR_SECONDS) / RTC_MAX_MINUTE; + time->hour = daySeconds / RTC_HOUR_SECONDS; + + time->month += RTC_UNIT_DIFF; + time->day += RTC_UNIT_DIFF; + time->weekday = RtcGetWeekDay(time); + HDF_LOGD("TimestampToRtc:year-month-day weekday hour:min:second ms %04u-%02u-%02u %u %02u:%02u:%02u .%03u", + time->year, time->month, time->day, time->weekday, time->hour, time->minute, time->second, time->millisecond); +} diff --git a/support/platform/src/rtc_core.c b/support/platform/src/rtc_core.c new file mode 100755 index 00000000..c1865e56 --- /dev/null +++ b/support/platform/src/rtc_core.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_log.h" +#include "osal_mem.h" +#include "rtc_core.h" + +#define HDF_LOG_TAG rtc_core + +int RtcSetHostMethod(struct RtcHost *host, struct RtcMethod *method) +{ + if (host == NULL || method == NULL) { + HDF_LOGE("RtcSetHostMethod: Invalid parameter"); + return HDF_ERR_INVALID_PARAM; + } + host->method = method; + return HDF_SUCCESS; +} + +struct RtcHost *RtcHostCreate(struct HdfDeviceObject *device) +{ + struct RtcHost *host = NULL; + + if (device == NULL) { + HDF_LOGE("RtcHostCreate: device NULL!"); + return NULL; + } + + host = (struct RtcHost *)OsalMemCalloc(sizeof(*host)); + if (host == NULL) { + HDF_LOGE("RtcHostCreate: malloc host fail!"); + return NULL; + } + host->device = device; + return host; +} + +void RtcHostDestroy(struct RtcHost *host) +{ + if (host != NULL) { + host->device = NULL; + host->method = NULL; + host->data = NULL; + OsalMemFree(host); + } +} diff --git a/support/platform/src/rtc_if.c b/support/platform/src/rtc_if.c new file mode 100755 index 00000000..82a47662 --- /dev/null +++ b/support/platform/src/rtc_if.c @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_base.h" +#include "hdf_log.h" +#include "devsvc_manager_clnt.h" +#include "osal_mem.h" +#include "rtc_base.h" +#include "rtc_core.h" +#include "rtc_if.h" + +#define HDF_LOG_TAG rtc_if + +static char *g_rtcServiceName = "HDF_PLATFORM_RTC"; + +struct DevHandle *RtcOpen() +{ + struct DevHandle *handle = NULL; + struct RtcHost *host = NULL; + + host = (struct RtcHost *)DevSvcManagerClntGetService(g_rtcServiceName); + if (host == NULL) { + HDF_LOGE("rtc get service name failed"); + return NULL; + } + handle = OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + return NULL; + } + handle->object = host; + return handle; +} + +void RtcClose(struct DevHandle *handle) +{ + if (handle != NULL) { + handle->object = NULL; + OsalMemFree(handle); + } +} + +int32_t RtcReadTime(struct DevHandle *handle, struct RtcTime *time) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcReadTime: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->ReadTime == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->ReadTime(host, time); +} + +int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcWriteTime: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + + if (RtcIsInvalid(time) == RTC_TRUE) { + HDF_LOGE("RtcWriteTime: time invalid"); + return HDF_ERR_INVALID_PARAM; + } + + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->WriteTime == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->WriteTime(host, time); +} + +int32_t RtcReadAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcReadAlarm: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->ReadAlarm == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->ReadAlarm(host, alarmIndex, time); +} + +int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcWriteAlarm: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + + if (RtcIsInvalid(time) == RTC_TRUE) { + HDF_LOGE("RtcWriteAlarm: time invalid"); + return HDF_ERR_INVALID_PARAM; + } + + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->WriteAlarm == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->WriteAlarm(host, alarmIndex, time); +} + +int32_t RtcRegisterAlarmCallback(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcRegisterAlarmCallback: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->RegisterAlarmCallback == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->RegisterAlarmCallback(host, alarmIndex, cb); +} + +int32_t RtcAlarmInterruptEnable(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, uint8_t enable) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcAlarmInterruptEnable: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->AlarmInterruptEnable == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->AlarmInterruptEnable(host, alarmIndex, enable); +} + +int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcGetFreq: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->GetFreq == NULL) { + HDF_LOGE("RtcGetFreq: pointer null"); + return HDF_ERR_NOT_SUPPORT; + } + return host->method->GetFreq(host, freq); +} + +int32_t RtcSetFreq(struct DevHandle *handle, uint32_t freq) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcSetFreq: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->SetFreq == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->SetFreq(host, freq); +} + +int32_t RtcReset(struct DevHandle *handle) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcReset: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->Reset == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->Reset(host); +} + +int32_t RtcReadReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t *value) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcReadReg: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->ReadReg == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->ReadReg(host, usrDefIndex, value); +} + +int32_t RtcWriteReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t value) +{ + struct RtcHost *host = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("RtcReadReg: handle is null"); + return HDF_ERR_INVALID_OBJECT; + } + host = (struct RtcHost *)handle->object; + if (host->method == NULL || host->method->WriteReg == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return host->method->WriteReg(host, usrDefIndex, value); +} diff --git a/support/platform/src/sdio_core.c b/support/platform/src/sdio_core.c new file mode 100755 index 00000000..904b4a85 --- /dev/null +++ b/support/platform/src/sdio_core.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "device_resource_if.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "sdio_core.h" + +#define HDF_LOG_TAG sdio_core + +struct SdioCntlr *SdioCntlrCreateAndBind(struct HdfDeviceObject *device) +{ + struct SdioCntlr *cntlr = NULL; + + if (device == NULL) { + HDF_LOGE("SdioCntlrCreateAndBind: device is NULL!"); + return NULL; + } + + cntlr = (struct SdioCntlr *)OsalMemCalloc(sizeof(*cntlr)); + if (cntlr == NULL) { + HDF_LOGE("SdioCntlrCreateAndBind: malloc host fail!"); + return NULL; + } + cntlr->device = device; + device->service = &cntlr->service; + return cntlr; +} + +void SdioCntlrDestroy(struct SdioCntlr *cntlr) +{ + if (cntlr != NULL) { + cntlr->device = NULL; + cntlr->priv = NULL; + cntlr->method = NULL; + OsalMemFree(cntlr); + } +} + +int32_t SdioFillConfigData(struct HdfDeviceObject *device, struct SdioConfigData *configData) +{ + const struct DeviceResourceNode *node = NULL; + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (device == NULL || configData == NULL) { + HDF_LOGE("SdioFillConfigData: input para is NULL."); + return HDF_FAILURE; + } + + node = device->property; + if (node == NULL) { + HDF_LOGE("SdioFillConfigData: drs node is NULL."); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("SdioFillConfigData: invalid drs ops fail!"); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "funcNum", &(configData->funcNum), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioFillConfigData: read funcNum fail!"); + return ret; + } + ret = drsOps->GetUint32(node, "vendorId", &(configData->vendorId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioFillConfigData: read vendorId fail!"); + return ret; + } + ret = drsOps->GetUint32(node, "deviceId", &(configData->deviceId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioFillConfigData: read deviceId fail!"); + return ret; + } + + HDF_LOGD("SdioFillConfigData: Success! funcNum = %d, vendorId = 0x%x, deviceId = 0x%x.", + configData->funcNum, configData->vendorId, configData->deviceId); + return HDF_SUCCESS; +} diff --git a/support/platform/src/sdio_if.c b/support/platform/src/sdio_if.c new file mode 100755 index 00000000..d0af50b7 --- /dev/null +++ b/support/platform/src/sdio_if.c @@ -0,0 +1,443 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#include "sdio_core.h" + +#define HDF_LOG_TAG sdio_if_c + +#define SDIO_NAME_LEN 32 +#define SDIO_BUS_MAX 2 + +static struct SdioCntlr *SdioGetCntlrByBusNum(int16_t busNum) +{ + struct SdioCntlr *cntlr = NULL; + char *serviceName = NULL; + + if (busNum < 0 || busNum >= SDIO_BUS_MAX) { + HDF_LOGE("SdioGetCntlrByBusNum: invalid bus:%d", busNum); + return NULL; + } + serviceName = OsalMemCalloc(SDIO_NAME_LEN + 1); + if (serviceName == NULL) { + return NULL; + } + if (snprintf_s(serviceName, SDIO_NAME_LEN + 1, SDIO_NAME_LEN, + "HDF_PLATFORM_SDIO_%d", busNum) < 0) { + HDF_LOGE("SdioGetCntlrByBusNum: format service name fail!"); + OsalMemFree(serviceName); + return NULL; + } + cntlr = (struct SdioCntlr*)DevSvcManagerClntGetService(serviceName); + if (cntlr == NULL) { + HDF_LOGE("SdioGetCntlrByBusNum: get service fail!"); + } + OsalMemFree(serviceName); + return cntlr; +} + +struct DevHandle *SdioOpen(int16_t busNum) +{ + struct DevHandle *handle = NULL; + struct SdioCntlr *cntlr = NULL; + int32_t ret; + + cntlr = SdioGetCntlrByBusNum(busNum); + if (cntlr == NULL) { + HDF_LOGE("SdioOpen: SdioGetCntlrByBusNum fail!"); + return NULL; + } + if (cntlr->method == NULL) { + HDF_LOGE("SdioOpen: method is NULL!"); + return NULL; + } + if (cntlr->method->findFunc == NULL) { + HDF_LOGE("SdioOpen: findFunc is NULL!"); + return NULL; + } + + ret = cntlr->method->findFunc(cntlr, &(cntlr->configData)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioOpen: findFunc fail!"); + return NULL; + } + + handle = OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + HDF_LOGE("SdioOpen: OsalMemCalloc fail!"); + return NULL; + } + handle->object = cntlr; + HDF_LOGD("SdioOpen: Success!"); + return handle; +} + +void SdioClose(struct DevHandle *handle) +{ + if (handle != NULL) { + handle->object = NULL; + OsalMemFree(handle); + } +} + +int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, + uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioReadBytes: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioReadBytes: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->incrAddrReadBytes == NULL) { + HDF_LOGE("SdioReadBytes: method or incrAddrReadBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioReadBytes: Success!"); + return cntlr->method->incrAddrReadBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, + uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioWriteBytes: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioWriteBytes: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->incrAddrWriteBytes == NULL) { + HDF_LOGE("SdioWriteBytes: method or incrAddrWriteBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioWriteBytes: Success!"); + return cntlr->method->incrAddrWriteBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioReadBytesFromFixedAddr: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioReadBytesFromFixedAddr: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->fixedAddrReadBytes == NULL) { + HDF_LOGE("SdioReadBytesFromFixedAddr: method or incrAddrWriteBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioReadBytesFromFixedAddr: Success!"); + return cntlr->method->fixedAddrReadBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioWriteBytesToFixedAddr: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioWriteBytesToFixedAddr: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->fixedAddrWriteBytes == NULL) { + HDF_LOGE("SdioWriteBytesToFixedAddr: method or fixedAddrWriteBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioWriteBytesToFixedAddr: Success!"); + return cntlr->method->fixedAddrWriteBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioReadBytesFromFunc0: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioReadBytesFromFunc0: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->func0ReadBytes == NULL) { + HDF_LOGE("SdioReadBytesFromFunc0: method or func0ReadBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioReadBytesFromFunc0: Success!"); + return cntlr->method->func0ReadBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t timeOut) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioWriteBytesToFunc0: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioWriteBytesToFunc0: data is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->func0WriteBytes == NULL) { + HDF_LOGE("SdioWriteBytesToFunc0: method or func0WriteBytes is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioWriteBytesToFunc0: Success!"); + return cntlr->method->func0WriteBytes(cntlr, data, addr, size, timeOut); +} + +int32_t SdioSetBlockSize(struct DevHandle *handle, uint32_t blockSize) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioSetBlockSize: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->setBlockSize == NULL) { + HDF_LOGE("SdioSetBlockSize: method or setBlockSize is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioSetBlockSize: Success!"); + return cntlr->method->setBlockSize(cntlr, blockSize); +} + +int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioGetCommonInfo: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (info == NULL) { + HDF_LOGE("SdioGetCommonInfo: info is NULL!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->getCommonInfo == NULL) { + HDF_LOGE("SdioGetCommonInfo: method or getCommonInfo is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioGetCommonInfo: Success! infoType is %d.", infoType); + return cntlr->method->getCommonInfo(cntlr, info, infoType); +} + +int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioSetCommonInfo: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (info == NULL) { + HDF_LOGE("SdioSetCommonInfo: info is NULL!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->setCommonInfo == NULL) { + HDF_LOGE("SdioSetCommonInfo: method or setCommonInfo is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioSetCommonInfo: Success! infoType is %d.", infoType); + return cntlr->method->setCommonInfo(cntlr, info, infoType); +} + +int32_t SdioFlushData(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioFlushData: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->flushData == NULL) { + HDF_LOGE("SdioFlushData: method or flushData is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioFlushData: Success!"); + return cntlr->method->flushData(cntlr); +} + +void SdioClaimHost(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioClaimHost: handle or object is null!"); + return; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->claimHost == NULL) { + HDF_LOGE("SdioClaimHost: method or claimHost is null!"); + return; + } + HDF_LOGD("SdioClaimHost: Success!"); + cntlr->method->claimHost(cntlr); +} + +void SdioReleaseHost(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioReleaseHost: handle or object is null!"); + return; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->releaseHost == NULL) { + HDF_LOGE("SdioReleaseHost: method or releaseHost is null!"); + return; + } + HDF_LOGD("SdioReleaseHost: Success!"); + cntlr->method->releaseHost(cntlr); +} + +int32_t SdioEnableFunc(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioEnableFunc: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->enableFunc == NULL) { + HDF_LOGE("SdioEnableFunc: method or enableFunc is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioEnableFunc: Success!"); + return cntlr->method->enableFunc(cntlr); +} + +int32_t SdioDisableFunc(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioDisableFunc: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->disableFunc == NULL) { + HDF_LOGE("SdioDisableFunc: method or disableFunc is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioDisableFunc: Success!"); + return cntlr->method->disableFunc(cntlr); +} + +int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioClaimIrq: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (irqHandler == NULL) { + HDF_LOGE("SdioClaimIrq: irqHandler is null!"); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->claimIrq == NULL) { + HDF_LOGE("SdioClaimIrq: method or claimIrq is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioClaimIrq: Success!"); + return cntlr->method->claimIrq(cntlr, irqHandler); +} + +int32_t SdioReleaseIrq(struct DevHandle *handle) +{ + struct SdioCntlr *cntlr = NULL; + + if (handle == NULL || handle->object == NULL) { + HDF_LOGE("SdioReleaseIrq: handle or object is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct SdioCntlr *)handle->object; + if (cntlr->method == NULL || cntlr->method->releaseIrq == NULL) { + HDF_LOGE("SdioReleaseIrq: method or releaseIrq is null!"); + return HDF_ERR_NOT_SUPPORT; + } + HDF_LOGD("SdioReleaseIrq: Success!"); + return cntlr->method->releaseIrq(cntlr); +} diff --git a/support/platform/src/spi_core.c b/support/platform/src/spi_core.c new file mode 100755 index 00000000..b9339c89 --- /dev/null +++ b/support/platform/src/spi_core.c @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "spi_core.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" +#include "spi_if.h" + +#define HDF_LOG_TAG spi_core + +int32_t SpiCntlrTransfer(struct SpiCntlr *cntlr, uint32_t csNum, struct SpiMsg *msg, uint32_t count) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("%s: invalid parameter\n", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->method == NULL || cntlr->method->Transfer == NULL) { + HDF_LOGE("%s: transfer not support\n", __func__); + return HDF_ERR_NOT_SUPPORT; + } + + (void)OsalMutexLock(&(cntlr->lock)); + cntlr->curCs = csNum; + ret = cntlr->method->Transfer(cntlr, msg, count); + (void)OsalMutexUnlock(&(cntlr->lock)); + return ret; +} + +int32_t SpiCntlrSetCfg(struct SpiCntlr *cntlr, uint32_t csNum, struct SpiCfg *cfg) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("%s: invalid parameter\n", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (cntlr->method == NULL || cntlr->method->SetCfg == NULL) { + HDF_LOGE("%s: not support\n", __func__); + return HDF_ERR_NOT_SUPPORT; + } + + (void)OsalMutexLock(&(cntlr->lock)); + cntlr->curCs = csNum; + ret = cntlr->method->SetCfg(cntlr, cfg); + (void)OsalMutexUnlock(&(cntlr->lock)); + return ret; +} + +int32_t SpiCntlrGetCfg(struct SpiCntlr *cntlr, uint32_t csNum, struct SpiCfg *cfg) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("%s: invalid parameter\n", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (cntlr->method == NULL || cntlr->method->GetCfg == NULL) { + HDF_LOGE("%s: not support\n", __func__); + return HDF_ERR_NOT_SUPPORT; + } + + (void)OsalMutexLock(&(cntlr->lock)); + cntlr->curCs = csNum; + ret = cntlr->method->GetCfg(cntlr, cfg); + (void)OsalMutexUnlock(&(cntlr->lock)); + return ret; +} + +void SpiCntlrDestroy(struct SpiCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + (void)OsalMutexDestroy(&(cntlr->lock)); + OsalMemFree(cntlr); +} + +struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device) +{ + struct SpiCntlr *cntlr = NULL; + + if (device == NULL) { + HDF_LOGE("%s: invalid parameter\n", __func__); + return NULL; + } + + cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr)); + if (cntlr == NULL) { + HDF_LOGE("%s: OsalMemCalloc error\n", __func__); + return NULL; + } + cntlr->device = device; + device->service = &(cntlr->service); + (void)OsalMutexInit(&cntlr->lock); + cntlr->priv = NULL; + return cntlr; +} diff --git a/support/platform/src/spi_if.c b/support/platform/src/spi_if.c new file mode 100755 index 00000000..7c20d5e9 --- /dev/null +++ b/support/platform/src/spi_if.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "securec.h" +#include "devsvc_manager_clnt.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "spi_core.h" +#include "spi_if.h" + +#define HDF_LOG_TAG spi_if +#define HOST_NAME_LEN 32 + +struct SpiObject { + struct SpiCntlr *cntlr; + uint32_t csNum; +}; + +static struct SpiCntlr *SpiGetCntlrByBusNum(uint32_t num) +{ + int ret; + char *name = NULL; + struct SpiCntlr *cntlr = NULL; + + name = (char *)OsalMemCalloc(HOST_NAME_LEN + 1); + if (name == NULL) { + return NULL; + } + ret = snprintf_s(name, HOST_NAME_LEN + 1, HOST_NAME_LEN, "HDF_PLATFORM_SPI_%u", num); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed\n", __func__); + OsalMemFree(name); + return NULL; + } + cntlr = (struct SpiCntlr *)DevSvcManagerClntGetService(name); + OsalMemFree(name); + return cntlr; +} + +int32_t SpiTransfer(struct DevHandle *handle, struct SpiMsg *msgs, uint32_t count) +{ + struct SpiObject *obj = NULL; + + if (handle == NULL || handle->object == NULL) { + return HDF_ERR_INVALID_PARAM; + } + obj = (struct SpiObject *)handle->object; + return SpiCntlrTransfer(obj->cntlr, obj->csNum, msgs, count); +} + +int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len) +{ + struct SpiMsg msg = {0}; + + msg.wbuf = NULL; + msg.rbuf = buf; + msg.len = len; + return SpiTransfer(handle, &msg, 1); +} + +int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len) +{ + struct SpiMsg msg = {0}; + + msg.wbuf = buf; + msg.rbuf = NULL; + msg.len = len; + return SpiTransfer(handle, &msg, 1); +} + +int32_t SpiSetCfg(struct DevHandle *handle, struct SpiCfg *cfg) +{ + struct SpiObject *obj = NULL; + + if (handle == NULL || handle->object == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + obj = (struct SpiObject *)handle->object; + return SpiCntlrSetCfg(obj->cntlr, obj->csNum, cfg); +} + +int32_t SpiGetCfg(struct DevHandle *handle, struct SpiCfg *cfg) +{ + struct SpiObject *obj = NULL; + + if (handle == NULL || handle->object == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + obj = (struct SpiObject *)handle->object; + return SpiCntlrGetCfg(obj->cntlr, obj->csNum, cfg); +} + +void SpiClose(struct DevHandle *handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: handle is NULL\n", __func__); + return; + } + if (handle->object != NULL) { + OsalMemFree(handle->object); + handle->object = NULL; + } + OsalMemFree(handle); +} + +struct DevHandle *SpiOpen(const struct SpiDevInfo *info) +{ + struct DevHandle *handle = NULL; + struct SpiObject *object = NULL; + struct SpiCntlr *cntlr = NULL; + + if (info == NULL) { + return NULL; + } + cntlr = SpiGetCntlrByBusNum(info->busNum); + if (cntlr == NULL) { + HDF_LOGE("%s: cntlr is null", __func__); + return NULL; + } + handle = (struct DevHandle *)OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + HDF_LOGE("%s: handle malloc error\n", __func__); + return NULL; + } + object = (struct SpiObject *)OsalMemCalloc(sizeof(*object)); + if (object == NULL) { + HDF_LOGE("%s: object malloc error\n", __func__); + OsalMemFree(handle); + return NULL; + } + object->cntlr = cntlr; + object->csNum = info->csNum; + handle->object = object; + return handle; +} diff --git a/support/platform/src/uart_core.c b/support/platform/src/uart_core.c new file mode 100755 index 00000000..0831580b --- /dev/null +++ b/support/platform/src/uart_core.c @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "uart_core.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" +#include "uart_if.h" + +#define HDF_LOG_TAG uart_core + +void UartHostDestroy(struct UartHost *host) +{ + if (host == NULL) { + return; + } + OsalMemFree(host); +} + +struct UartHost *UartHostCreate(struct HdfDeviceObject *device) +{ + struct UartHost *host = NULL; + + if (device == NULL) { + HDF_LOGE("%s: invalid parameter\n", __func__); + return NULL; + } + host = (struct UartHost *)OsalMemCalloc(sizeof(*host)); + if (host == NULL) { + HDF_LOGE("%s: OsalMemCalloc error\n", __func__); + return NULL; + } + host->device = device; + device->service = &(host->service); + host->priv = NULL; + host->method = NULL; + return host; +} diff --git a/support/platform/src/uart_if.c b/support/platform/src/uart_if.c new file mode 100755 index 00000000..bc767e96 --- /dev/null +++ b/support/platform/src/uart_if.c @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "securec.h" +#include "devsvc_manager_clnt.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "uart_core.h" +#include "uart_if.h" + +#define HDF_LOG_TAG uart_if_c +#define UART_HOST_NAME_LEN 32 + +static struct UartHost *UartGetHostByBusNum(uint32_t num) +{ + int ret; + char *name = NULL; + struct UartHost *host = NULL; + + name = (char *)OsalMemCalloc(UART_HOST_NAME_LEN + 1); + if (name == NULL) { + return NULL; + } + ret = snprintf_s(name, UART_HOST_NAME_LEN + 1, UART_HOST_NAME_LEN, + "HDF_PLATFORM_UART_%u", num); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed\n", __func__); + OsalMemFree(name); + return NULL; + } + host = (struct UartHost *)DevSvcManagerClntGetService(name); + OsalMemFree(name); + return host; +} + +struct DevHandle *UartOpen(uint32_t port) +{ + struct DevHandle *handle = NULL; + struct UartHost *host = NULL; + + host = UartGetHostByBusNum(port); + if (host == NULL) { + HDF_LOGE("%s: get host error\n", __func__); + return NULL; + } + handle = (struct DevHandle *)OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + HDF_LOGE("%s: handle malloc error\n", __func__); + return NULL; + } + if (UartHostInit(host) != HDF_SUCCESS) { + HDF_LOGE("%s: UartHostInit error\n", __func__); + OsalMemFree(handle); + return NULL; + } + handle->object = host; + return handle; +} + +void UartClose(struct DevHandle *handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: handle is NULL\n", __func__); + return; + } + if (UartHostDeinit((struct UartHost *)handle->object) != HDF_SUCCESS) { + HDF_LOGE("%s: UartHostDeinit error\n", __func__); + } + OsalMemFree(handle); +} + +int32_t UartRead(struct DevHandle *handle, uint8_t *data, uint32_t size) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostRead((struct UartHost *)handle->object, data, size); +} + +int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostWrite((struct UartHost *)handle->object, data, size); +} + +int32_t UartGetBaud(struct DevHandle *handle, uint32_t *baudRate) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostGetBaud((struct UartHost *)handle->object, baudRate); +} + +int32_t UartSetBaud(struct DevHandle *handle, uint32_t baudRate) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostSetBaud((struct UartHost *)handle->object, baudRate); +} + +int32_t UartGetAttribute(struct DevHandle *handle, struct UartAttribute *attribute) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostGetAttribute((struct UartHost *)handle->object, attribute); +} + +int32_t UartSetAttribute(struct DevHandle *handle, struct UartAttribute *attribute) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostSetAttribute((struct UartHost *)handle->object, attribute); +} + +int32_t UartSetTransMode(struct DevHandle *handle, enum UartTransMode mode) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return UartHostSetTransMode((struct UartHost *)handle->object, mode); +} diff --git a/support/platform/src/watchdog_core.c b/support/platform/src/watchdog_core.c new file mode 100755 index 00000000..93e873ba --- /dev/null +++ b/support/platform/src/watchdog_core.c @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "watchdog_core.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG watchdog_core + +int32_t WatchdogCntlrAdd(struct WatchdogCntlr *cntlr) +{ + int32_t ret; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->device == NULL) { + HDF_LOGE("WatchdogCntlrAdd: no device associated!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->ops == NULL) { + HDF_LOGE("WatchdogCntlrAdd: no ops supplied!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = OsalSpinInit(&cntlr->lock); + if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogCntlrAdd: spinlock init fail!"); + return ret; + } + + cntlr->device->service = &cntlr->service; + return HDF_SUCCESS; +} + +void WatchdogCntlrRemove(struct WatchdogCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + + if (cntlr->device == NULL) { + HDF_LOGE("WatchdogCntlrRemove: no device associated!"); + return; + } + + cntlr->device->service = NULL; + (void)OsalSpinDestroy(&cntlr->lock); +} + +int32_t WatchdogCntlrGetStatus(struct WatchdogCntlr *cntlr, int32_t *status) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->getStatus == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + if (status == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->getStatus(cntlr, status); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} + +int32_t WatchdogCntlrStart(struct WatchdogCntlr *cntlr) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->start == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->start(cntlr); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} + +int32_t WatchdogCntlrStop(struct WatchdogCntlr *cntlr) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->stop == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->stop(cntlr); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} + +int32_t WatchdogCntlrSetTimeout(struct WatchdogCntlr *cntlr, uint32_t seconds) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->setTimeout == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->setTimeout(cntlr, seconds); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} + +int32_t WatchdogCntlrGetTimeout(struct WatchdogCntlr *cntlr, uint32_t *seconds) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->getTimeout == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + if (seconds == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->getTimeout(cntlr, seconds); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} + +int32_t WatchdogCntlrFeed(struct WatchdogCntlr *cntlr) +{ + int32_t ret; + uint32_t flags; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->feed == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrqSave(&cntlr->lock, &flags) != HDF_SUCCESS) { + return HDF_ERR_DEVICE_BUSY; + } + ret = cntlr->ops->feed(cntlr); + (void)OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return ret; +} diff --git a/support/platform/src/watchdog_if.c b/support/platform/src/watchdog_if.c new file mode 100755 index 00000000..4118b272 --- /dev/null +++ b/support/platform/src/watchdog_if.c @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "watchdog_if.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#include "watchdog_core.h" + +#define HDF_LOG_TAG watchdog_if + +#define WATCHDOG_ID_MAX 8 +#define WATCHDOG_NAME_LEN 32 + +static struct Watchdog *WatchdogGetById(int16_t wdtId) +{ + char *serviceName = NULL; + struct Watchdog *service = NULL; + + if (wdtId < 0 || wdtId >= WATCHDOG_ID_MAX) { + HDF_LOGE("WatchdogGetById: invalid id:%d\n", wdtId); + return NULL; + } + serviceName = OsalMemCalloc(WATCHDOG_NAME_LEN + 1); + if (serviceName == NULL) { + return NULL; + } + if (snprintf_s(serviceName, WATCHDOG_NAME_LEN + 1, WATCHDOG_NAME_LEN, + "HDF_PLATFORM_WATCHDOG_%d", wdtId) < 0) { + HDF_LOGE("WatchdogGetById: format service name fail!\n"); + OsalMemFree(serviceName); + return NULL; + } + service = (struct Watchdog *)DevSvcManagerClntGetService(serviceName); + if (service == NULL) { + HDF_LOGE("WatchdogGetById: get service fail!\n"); + } + OsalMemFree(serviceName); + return service; +} + + +struct DevHandle *WatchdogOpen(int16_t wdtId) +{ + struct DevHandle *handle = NULL; + struct Watchdog *service = NULL; + + service = WatchdogGetById(wdtId); + if (service == NULL) { + return NULL; + } + handle = OsalMemCalloc(sizeof(*handle)); + if (handle == NULL) { + return NULL; + } + handle->object = service; + return handle; +} + +void WatchdogClose(struct DevHandle *handle) +{ + if (handle != NULL) { + handle->object = NULL; + OsalMemFree(handle); + } +} + +int32_t WatchdogGetStatus(struct DevHandle *handle, int32_t *status) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrGetStatus((struct WatchdogCntlr *)handle->object, status); +} + +int32_t WatchdogStart(struct DevHandle *handle) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrStart((struct WatchdogCntlr *)handle->object); +} + +int32_t WatchdogStop(struct DevHandle *handle) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrStop((struct WatchdogCntlr *)handle->object); +} + +int32_t WatchdogSetTimeout(struct DevHandle *handle, uint32_t seconds) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrSetTimeout((struct WatchdogCntlr *)handle->object, seconds); +} + +int32_t WatchdogGetTimeout(struct DevHandle *handle, uint32_t *seconds) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrGetTimeout((struct WatchdogCntlr *)handle->object, seconds); +} + +int32_t WatchdogFeed(struct DevHandle *handle) +{ + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return WatchdogCntlrFeed((struct WatchdogCntlr *)handle->object); +} diff --git a/tools/hc-gen/README.md b/tools/hc-gen/README.md new file mode 100755 index 00000000..7a56a9e8 --- /dev/null +++ b/tools/hc-gen/README.md @@ -0,0 +1 @@ +hc-gen compilation requires flex and bison, make sure that they are installed before compiling. diff --git a/tools/hc-gen/include/hcs_ast.h b/tools/hc-gen/include/hcs_ast.h new file mode 100755 index 00000000..c9ed848e --- /dev/null +++ b/tools/hc-gen/include/hcs_ast.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_AST_H +#define HCS_COMPILER_AST_H + +#include "hcs_parser.h" + +typedef int32_t (*AstWalkCallBack)(ParserObject *current, int32_t walkDepth); + +ParserObject *HcsGetParserRoot(void); + +void HcsSetParserRoot(ParserObject *newRoot); + +ParserObject *HcsNewConfigNode(const char *nodeName, uint32_t nodeType, const char *refName); + +ParserObject *HcsNewConfigTerm(const char *name, ParserObject *value); + +ParserObject *HcsNewParserObject(const char *name, uint32_t type, uint64_t value); + +ParserObject *HcsAstAddChild(ParserObject *parent, ParserObject *child); + +void HcsAstRemoveChildLink(ParserObjectBase *parent, ParserObjectBase *child); + +ParserObject *HcsAstAddPeer(ParserObject *forward, ParserObject *peer); + +int32_t HcsWalkAst(ParserObject *start, uint32_t walkDirection, AstWalkCallBack forwardCallback, + AstWalkCallBack backwardCallback); + +void HcsDumpAst(const char *label); + +ParserObject *HcsAstLookupObjectInPeers(const ParserObject *current, const char *name); + +ParserObject *HcsAstLookupObjectInChildren(const ParserObject *current, const char *name); + +int32_t HcsAstCopySubTree(ParserObject *src, ParserObject *dst, uint32_t overWriteFlag); + +int32_t HcsAstCopyArray(const ParserObject *src, ParserObject *dst); + +void HcsDeleteParserObjectTree(ParserObject *object); + +uint16_t HcsCountArraySize(const ParserObject *arrayObj); + +uint16_t HcsGetTermType(ParserObject *object); + +const char *HcsGetModuleName(void); + +#endif // HCS_COMPILER_AST_H diff --git a/tools/hc-gen/include/hcs_compiler.h b/tools/hc-gen/include/hcs_compiler.h new file mode 100755 index 00000000..efefbda5 --- /dev/null +++ b/tools/hc-gen/include/hcs_compiler.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_H +#define HCS_COMPILER_H + +#include +#include "hcs_types.h" +#include "hcs_log.h" +#include "hcs_parser.h" +#include "hcs_ast.h" +#include "hcs_mem.h" + +#define HBC_MAGIC_NUM 0xA00AA00A +#define HCS_COMPILER_VERSION_MAJOR 00 +#define HCS_COMPILER_VERSION_MINOR 65 + +typedef struct HbcHeader { + uint32_t magicNumber; + uint32_t versionMajor; + uint32_t versionMinor; + uint32_t checkSum; + int32_t totalSize; +} HbcHeader; + +/* Parse compiler options */ +int32_t DoOption(int32_t argc, char *argv[]); + +int32_t HcsDoCompile(); + +int32_t HcsDoOptimize(); + +#endif // HCS_COMPILER_H diff --git a/tools/hc-gen/include/hcs_decompiler.h b/tools/hc-gen/include/hcs_decompiler.h new file mode 100755 index 00000000..aa164e0b --- /dev/null +++ b/tools/hc-gen/include/hcs_decompiler.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_DECOMPILE_H +#define HCS_DECOMPILE_H + +#include "hcs_compiler.h" + +int32_t HcsDoDecompile(); + +int32_t HcsDecompileOutput(); + +#endif // HCS_DECOMPILE_H diff --git a/tools/hc-gen/include/hcs_file.h b/tools/hc-gen/include/hcs_file.h new file mode 100755 index 00000000..375cf8a3 --- /dev/null +++ b/tools/hc-gen/include/hcs_file.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_FILE_H +#define HCS_COMPILER_FILE_H + +#include +#include "hcs_types.h" + +#define HCS_SOURCE_FILE_SUFFIX ".hcs" +#define HCS_OUTPUT_FILE_SUFFIX ".hcb" +#define HCS_DECOMPILE_OUTPUT_FILE_SUFFIX ".d.hcs" + +struct HcsFile { + const char *name; + const char *fullPath; + FILE *file; + uint64_t pos; + struct HcsFile *next; +}; + +struct HcsFileQueue { + struct HcsFile *head; + uint32_t count; +}; + +struct HcsSourceName { + const char *name; + struct HcsSourceName *next; +}; + +const char *HcsGetInputFileName(); + +void HcsSetInputFileName(const char *name); + +int32_t HcsOpenSourceFile(const char *path, struct HcsFile **file, const char *flag); + +void HcsCloseFile(struct HcsFile *file); + +int32_t HcsSetOutPutName(const char *name); + +int32_t HcsSetOutPutNameWithCurrentWorkPath(const char *name); + +const char *HcsGetOutPutFileName(); + +const char *HcsGetStripedOutputFileName(); + +struct HcsFile *HcsOpenOutputFile(const char *suffix); + +void HcsCloseOutput(struct HcsFile *output); + +int32_t HcsOutputWrite(const void *buffer, uint32_t length); + +int32_t HcsOutputWriteAlign(const void *buffer, uint32_t length); + +void HcsMockOutPut(bool dummyOutput); + +uint32_t HcsGetOutputCurrentCount(void); + +void HcsResetOutputCurrentCount(void); + +void HcsSourceQueuePush(struct HcsFile *sourceFile); + +void HcsSourceQueuePop(); + +struct HcsFile *HcsSourceQueueTop(); + +uint32_t HcsSourceQueueSize(); + +const char *HcsGetCurrentSourceName(); + +int32_t HcsSourceNameSetPush(const char *name); + +void HcsSourceNameSetClean(void); + +bool HcsFileCopyDir(char *dst, uint32_t dstBufferSize, const char *fullPath); + +uint64_t HcsSourceFileGetSize(struct HcsFile *file); + +int32_t HcsSourceFileRead(struct HcsFile *file, uint8_t *out, uint32_t readSize); + +uint32_t HcsGetSourceFilePos(struct HcsFile *file); + +#endif // HCS_COMPILER_FILE_H diff --git a/tools/hc-gen/include/hcs_gener.h b/tools/hc-gen/include/hcs_gener.h new file mode 100755 index 00000000..8d00a029 --- /dev/null +++ b/tools/hc-gen/include/hcs_gener.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_GENER_H +#define HCS_COMPILER_GENER_H + +#include + +int32_t HcsBytecodeOutput(); +int32_t HcsTextCodeOutput(); +int32_t HcsBinaryToHexdump(const char *inputFileName); + +#endif // HCS_COMPILER_GENER_H diff --git a/tools/hc-gen/include/hcs_log.h b/tools/hc-gen/include/hcs_log.h new file mode 100755 index 00000000..70defdca --- /dev/null +++ b/tools/hc-gen/include/hcs_log.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_LOG_H +#define HCS_COMPILER_LOG_H + +#include +#include +#include "hcs_types.h" + +#ifdef DEBUG +#define HCS_DEBUG(fmt, args...) fprintf(stdout, fmt"\n", ##args) +#else +#define HCS_DEBUG(fmt, args...) do {} while (0) +#endif + +#ifdef OS_LINUX +#define ERROR_COLOR_PREFIX "\033[31m" +#define ERROR_COLOR_END "\033[0m" +#else +#define ERROR_COLOR_PREFIX +#define ERROR_COLOR_END +#endif + +#define HCS_LOG_PRINT(fmt, args...) fprintf(stdout, ERROR_COLOR_PREFIX fmt ERROR_COLOR_END"\n", ##args) + +#define HCS_PRINT(fmt, args...) fprintf(stdout, fmt, ##args) + +#define HCS_INFO(fmt, args...) fprintf(stdout, fmt"\n", ##args) + +#define HCS_ERROR(fmt, args...) HCS_LOG_PRINT("Error: " fmt, ##args) + +#define HCS_WARNING(fmt, args...) HCS_LOG_PRINT("Warning: " fmt, ##args) + +#define HCS_OBJECT_PR(prefix, object, fmt, args...) \ + do { \ + HCS_LOG_PRINT (prefix": %s:%u\n\t" fmt"\n", \ + object ? ((ParserObjectBase*)object)->src : "unknown", \ + object ? ((ParserObjectBase*)object)->lineno : 0, \ + ##args); \ + } while (0) + +#define HCS_OBJECT_ERROR(object, fmt, args...) HCS_OBJECT_PR("Error", object, fmt, ##args) + +#define HCS_OBJECT_WARNING(object, fmt, args...) HCS_OBJECT_PR("Warning", object, fmt, ##args) + +#define PRINTF_CHECK_AND_RETURN(printRes) \ + do { \ + if ((printRes) < 0) { \ + HCS_ERROR("Error:%s(%d), sprintf_s fail", \ + __FUNCTION__, __LINE__); \ + return EOUTPUT; \ + } \ + } while (0) + +#define SPRINTF_ERROR_INFO "sprintf fail" + +#endif // HCS_COMPILER_LOG_H diff --git a/tools/hc-gen/include/hcs_mem.h b/tools/hc-gen/include/hcs_mem.h new file mode 100755 index 00000000..7b3a4be0 --- /dev/null +++ b/tools/hc-gen/include/hcs_mem.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_MEM_H +#define HCS_COMPILER_MEM_H + +#include + +void *HcsMemAlloc(uint32_t size); + +void *HcsMemZalloc(uint32_t size); + +void HcsMemFree(void *ptr); + +#endif // HCS_COMPILER_MEM_H diff --git a/tools/hc-gen/include/hcs_opcode.h b/tools/hc-gen/include/hcs_opcode.h new file mode 100755 index 00000000..cb29fc57 --- /dev/null +++ b/tools/hc-gen/include/hcs_opcode.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_OPCODE_H +#define HCS_COMPILER_OPCODE_H + +#include "hcs_parser.h" + +#define HCS_NODE_OP 0x01 +#define HCS_TERM_OP 0x02 +#define HCS_NODEREF_OP 0x03 +#define HCS_ARRAY_OP 0x04 +#define HCS_BYTE_OP 0x10 +#define HCS_WORD_OP 0x11 +#define HCS_DWORD_OP 0x12 +#define HCS_QWORD_OP 0x13 +#define HCS_STRING_OP 0x14 + +typedef struct { + uint8_t opCode; + uint32_t size; + const char *opStr; +} OpCodeMapEntry; + +const OpCodeMapEntry *HcsGetOpCodeMap(); + +const OpCodeMapEntry *HcsParserObjectTypeToByteCode(uint32_t objectType); + +void HcsCalculateOpcodeSize(ParserObject *object); + +const char *HcsOpcodeToStr(uint16_t opCode); + +#endif // HCS_COMPILER_OPCODE_H diff --git a/tools/hc-gen/include/hcs_option.h b/tools/hc-gen/include/hcs_option.h new file mode 100755 index 00000000..5dd642c7 --- /dev/null +++ b/tools/hc-gen/include/hcs_option.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_OPTION_H +#define HCS_COMPILER_OPTION_H +#include + +bool HcsOptShouldAlign(); + +void HcsOptSetAlign(bool align); + +bool HcsOptShouldGenTextConfig(); + +bool HcsOptShouldGenByteCodeConfig(); + +bool HcsOptDecompile(); + +bool HcsOptShouldGenHexdump(); + +const char *HcsOptGetSymbolNamePrefix(); + +bool HcsVerbosePrint(); + +#endif // HCS_COMPILER_OPTION_H diff --git a/tools/hc-gen/include/hcs_parser.h b/tools/hc-gen/include/hcs_parser.h new file mode 100755 index 00000000..dc01f9e3 --- /dev/null +++ b/tools/hc-gen/include/hcs_parser.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_PARSER_H +#define HCS_COMPILER_PARSER_H + +#include +#include "hcs_types.h" + +#define OBJECT_NAME_MAX_LEN 100 + +enum ParserObjectType { + PARSEROP_UINT8 = 0x01, + PARSEROP_UINT16, + PARSEROP_UINT32, + PARSEROP_UINT64, + PARSEROP_STRING, + PARSEROP_CONFNODE, + PARSEROP_CONFTERM, + PARSEROP_ARRAY, + PARSEROP_NODEREF, + PARSEROP_DELETE, + PARSEROP_COUNT, +}; + +enum NodeRefType { + CONFIG_NODE_NOREF = 0, + CONFIG_NODE_COPY, + CONFIG_NODE_REF, + CONFIG_NODE_DELETE, + CONFIG_NODE_TEMPLATE, + CONFIG_NODE_INHERIT, + CONFIG_NODE_TYPE_COUNT +}; +enum ParserObjectStatus { + PARSER_OBJ_IDLE = 0, + PARSER_OBJ_PROCESSING, +}; +struct ParserObjectBase; +typedef struct ParserObjectBase ParserObjectBase; + +#define PARSER_OBJECT_COMMON \ + uint32_t type; \ + uint32_t status; \ + const char *name; \ + ParserObjectBase *parent; \ + ParserObjectBase *next; \ + ParserObjectBase *child; \ + uint32_t lineno; \ + const char *src; \ + uint8_t opCode; \ + uint32_t size; \ + uint32_t subSize; \ + uint32_t hash; \ + union { \ + uint64_t value; \ + uint64_t integerValue; \ + char *stringValue; \ + }; + +struct ParserObjectBase { + PARSER_OBJECT_COMMON; +}; + +typedef struct TemplateNodeInstance { + struct ConfigNode *nodeObject; + struct TemplateNodeInstance *next; +} TemplateNodeInstance; + +typedef struct ConfigNode { + PARSER_OBJECT_COMMON; + const char *refNodePath; + uint32_t nodeType; + struct ConfigNode *inheritNode; + uint32_t inheritIndex; + uint32_t inheritCount; + uint32_t templateSignNum; + TemplateNodeInstance *subClasses; +} ConfigNode; + +typedef struct { + PARSER_OBJECT_COMMON; + uint32_t flag; // for array or other assembly type + uint32_t signNum; +} ConfigTerm; + +typedef union { + ParserObjectBase objectBase; + ConfigNode configNode; + ConfigTerm configTerm; +} ParserObject; + +enum AstWalkDirection { + AST_WALK_FORWARD = 0x01, + AST_WALK_BACKEND, + AST_WALK_ROUND, +}; + +enum AstCopyOverWriteFlag { + AST_COPY_SRC_OVER_DST = 0, // source term overwrite destination terms + AST_COPY_DST_OVER_SRC, // destination term overwrite source terms +}; + +/* lexer and parser auto-gen api start */ +void HcsParserRestart(FILE *inputFile); + +int32_t HcsCompilerparse(void); + +/* lexer and parser auto-gen api end */ +bool HcsIsAnonymousObject(const ParserObject *obj); + +int32_t HcsProcessInclude(char *includePath, uint32_t lineNumber); + +bool HcsIsSameTypeObject(const ParserObject *cs, const ParserObject *ct); + +bool HcsIsNumberObject(const ParserObject *obj); + +bool HcsIsStringObject(const ParserObject *obj); + +const char *HcsParserNodeTypeToStr(uint32_t nodeType); + +void HcsAstFreeObject(ParserObject *object); + +int32_t HcsGetCurrentSourceLine(void); + +void HcsSetCurrentSourceLine(int32_t lineNumber); + +uint32_t HcsAlign(uint32_t size); + +#endif // HCS_COMPILER_PARSER_H diff --git a/tools/hc-gen/include/hcs_types.h b/tools/hc-gen/include/hcs_types.h new file mode 100755 index 00000000..f1c3e633 --- /dev/null +++ b/tools/hc-gen/include/hcs_types.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HCS_COMPILER_TYPES_H +#define HCS_COMPILER_TYPES_H + +#include +#include +#include + +#define HCS_OPTION_END (-1) +#define ALIGN_SIZE 4 + +#define OPCODE_BYTE_WIDTH 1 + +#define BYTE_SIZE 1 +#define WORD_SIZE 2 +#define DWORD_SIZE 4 +#define QWORD_SIZE 8 + +#define UNIX_SEPARATOR '/' +#define WIN_SEPARATOR '\\' + +#ifdef OS_WIN +#define OS_SEPARATOR WIN_SEPARATOR +#else +#define OS_SEPARATOR UNIX_SEPARATOR +#endif + +enum HcsErrorNo { + NOERR = 0, /* No error */ + EFAIL, /* Process fail */ + EOOM, /* Out of memory */ + EOPTION, /* Option error */ + EREOPENF, /* Reopen argument */ + EINVALF, /* Invalid file */ + EINVALARG, /* Invalid argument */ + EDECOMP, /* Decompile error */ + EOUTPUT, /* Output error */ + EASTWALKBREAK, /* Break ast walk */ +}; + +#endif // HCS_COMPILER_TYPES_H diff --git a/tools/hc-gen/src/hcs_ast.c b/tools/hc-gen/src/hcs_ast.c new file mode 100755 index 00000000..3273e2b3 --- /dev/null +++ b/tools/hc-gen/src/hcs_ast.c @@ -0,0 +1,758 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "hcs_file.h" +#include "hcs_mem.h" +#include "hcs_log.h" +#include "hcs_option.h" +#include "hcs_ast.h" + +#define ANONYMOUS_OBJECT_NAME "|_" +static ParserObject *g_parserRoot = NULL; + +bool HcsIsAnonymousObject(const ParserObject *obj) +{ + return strcmp(obj->objectBase.name, ANONYMOUS_OBJECT_NAME) == 0; +} + +ParserObject *HcsAllocParserObject(void) +{ + ParserObject *new = (ParserObject *)HcsMemZalloc(sizeof(ParserObject)); + if (new == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return NULL; + } + new->objectBase.src = HcsGetCurrentSourceName(); + new->objectBase.lineno = HcsGetCurrentSourceLine(); + return new; +} + +void HcsAstFreeObject(ParserObject *object) +{ + if (object == NULL) { + return; + } + if (object->objectBase.type == PARSEROP_CONFNODE) { + TemplateNodeInstance *subClass = object->configNode.subClasses; + while (subClass != NULL) { + TemplateNodeInstance *temp = subClass; + subClass = subClass->next; + HcsMemFree(temp); + } + HcsMemFree((char *)object->configNode.refNodePath); + } + + HcsAstRemoveChildLink(object->objectBase.parent, (ParserObjectBase *)object); + if (object->objectBase.type == PARSEROP_STRING) { + HcsMemFree(object->objectBase.stringValue); + } + + HcsMemFree((char*)object->objectBase.name); + HcsMemFree(object); +} + +static int32_t HcsAstWalkFreeObjectCallback(ParserObject *object, int32_t walkDepth) +{ + (void)walkDepth; + HcsAstFreeObject(object); + return NOERR; +} + +static void HcsAstFreeObjectAndSubtree(ParserObject *object) +{ + if (HcsWalkAst(object, AST_WALK_BACKEND, NULL, HcsAstWalkFreeObjectCallback)) { + HCS_WARNING("%s may failed", __func__); + } +} + +void HcsDeleteParserObjectTree(ParserObject *object) +{ + if (object == NULL) { + return; + } + /* delete current and subtree */ + HcsAstFreeObjectAndSubtree(object); +} + +ParserObject *HcsGetParserRoot(void) +{ + if (g_parserRoot != NULL) { + return g_parserRoot; + } + HCS_DEBUG("instance root node"); + char *rootNodeName = strdup("root"); + if (rootNodeName == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return NULL; + } + g_parserRoot = HcsNewConfigNode(rootNodeName, CONFIG_NODE_NOREF, NULL); + if (g_parserRoot == NULL) { + HcsMemFree(rootNodeName); + } + return g_parserRoot; +} + +void HcsSetParserRoot(ParserObject *newRoot) +{ + g_parserRoot = newRoot; +} + +ParserObject *HcsNewConfigNode(const char *nodeName, uint32_t nodeType, const char *refName) +{ + HCS_DEBUG("create node: %s", nodeName ? nodeName : "nil"); + ParserObject *object = HcsAllocParserObject(); + if (object == NULL) { + return NULL; + } + object->configNode.name = nodeName; + object->objectBase.type = PARSEROP_CONFNODE; + if (nodeType) { + object->configNode.nodeType = nodeType; + object->configNode.refNodePath = refName; + } + + return object; +} + +uint32_t HcsFitIntegerValueType(uint64_t value) +{ + if (value <= UINT8_MAX) { + return PARSEROP_UINT8; + } else if (value <= UINT16_MAX) { + return PARSEROP_UINT16; + } else if (value <= UINT32_MAX) { + return PARSEROP_UINT32; + } else { + return PARSEROP_UINT64; + } +} + +ParserObject *HcsNewConfigTerm(const char *name, ParserObject *value) +{ + if (name == NULL || value == NULL) { + return NULL; + } + ParserObject *object = HcsAllocParserObject(); + if (object == NULL) { + return NULL; + } + object->objectBase.name = name; + object->objectBase.type = PARSEROP_CONFTERM; + object->objectBase.child = (ParserObjectBase *)value; + ParserObjectBase *child = &value->objectBase; + while (child != NULL) { + child->parent = (ParserObjectBase *)object; + child = child->next; + } + + return object; +} + +ParserObject *HcsNewParserObject(const char *name, uint32_t type, uint64_t value) +{ + if (type >= PARSEROP_COUNT) { + HCS_ERROR("unknown object type"); + return NULL; + } + + ParserObject *object = HcsAllocParserObject(); + if (object == NULL) { + return NULL; + } + + if (name == NULL) { + name = strdup(ANONYMOUS_OBJECT_NAME); + if (name == NULL) { + HcsMemFree(object); + return NULL; + } + } + + object->objectBase.name = name; + object->objectBase.type = type; + object->objectBase.value = value; + + switch (type) { + case PARSEROP_UINT8: /* fall-through */ + case PARSEROP_UINT16: /* fall-through */ + case PARSEROP_UINT32: /* fall-through */ + case PARSEROP_UINT64: + object->objectBase.type = HcsFitIntegerValueType(value); + break; + default: + break; + } + + return object; +} + +ParserObject *HcsAstAddChild(ParserObject *parent, ParserObject *child) +{ + if (child == NULL) { + return parent; + } + + if (parent->objectBase.child == NULL) { + parent->objectBase.child = (ParserObjectBase *)child; + ParserObjectBase *childNext = &child->objectBase; + while (childNext != NULL) { + childNext->parent = (ParserObjectBase *)parent; + childNext = childNext->next; + } + } else { + HcsAstAddPeer((ParserObject *)parent->configNode.child, child); + } + + return parent; +} + +void HcsAstRemoveChildLink(ParserObjectBase *parent, ParserObjectBase *child) +{ + if (parent == NULL || child == NULL || child->parent != parent) { + return; + } + child->parent = NULL; + if (parent->child == child) { + parent->child = child->next; + child->next = NULL; + return; + } + + ParserObjectBase *pre = parent->child; + while (pre != NULL) { + if (pre->next == child) { + pre->next = pre->next->next; + } + + pre = pre->next; + } + child->next = NULL; +} + +ParserObject *HcsAstAddPeer(ParserObject *forward, ParserObject *peer) +{ + if (forward == NULL && peer == NULL) { + return forward; + } + + if (forward == NULL) { + return peer; + } + + if (peer == NULL) { + return forward; + } + + if (forward == peer) { + HCS_ERROR("add self as peer"); + return NULL; + } + + ParserObjectBase *lastNode = &forward->objectBase; + while (lastNode->next) { + lastNode = lastNode->next; + } + + lastNode->next = (ParserObjectBase *)peer; + peer->objectBase.parent = forward->objectBase.parent; + + ParserObjectBase *peerNext = peer->objectBase.next; + while (peerNext != NULL) { + peerNext->parent = forward->objectBase.parent; + peerNext = peerNext->next; + } + + return forward; +} + +ParserObject *HcsAstLookupObjectInPeers(const ParserObject *current, const char *name) +{ + ParserObject *peer = (ParserObject *)current->objectBase.parent->child; + while (peer != NULL) { + if (peer->objectBase.type == PARSEROP_CONFNODE && !strcmp(peer->objectBase.name, name)) { + return peer; + } + + peer = (ParserObject *)peer->objectBase.next; + } + + return NULL; +} + +ParserObject *HcsAstLookupObjectInChildren(const ParserObject *current, const char *name) +{ + if (current == NULL) { + return NULL; + } + ParserObject *peer = (ParserObject *)current->objectBase.child; + while (peer != NULL) { + if (!strcmp(peer->objectBase.name, name)) { + return peer; + } + + peer = (ParserObject *)peer->objectBase.next; + } + + return NULL; +} + +static ParserObject *HcsParserObjectClone(const ParserObject *object) +{ + if (object == NULL) { + return NULL; + } + ParserObject *clone = HcsAllocParserObject(); + if (clone == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return NULL; + } + + (void)memcpy_s(clone, sizeof(*clone), object, sizeof(*object)); + clone->configNode.refNodePath = NULL; + clone->objectBase.name = NULL; + clone->objectBase.child = NULL; + clone->objectBase.next = NULL; + clone->objectBase.parent = NULL; + if (object->objectBase.type == PARSEROP_STRING) { + clone->objectBase.stringValue = strdup(object->objectBase.stringValue); + if (clone->objectBase.stringValue == NULL) { + HcsAstFreeObject(clone); + return NULL; + } + } + if (object->configNode.refNodePath != NULL) { + clone->configNode.refNodePath = strdup(object->configNode.refNodePath); + if (clone->configNode.refNodePath == NULL) { + HcsAstFreeObject(clone); + return NULL; + } + } + clone->objectBase.name = strdup(object->objectBase.name); + if (clone->objectBase.name == NULL) { + HcsAstFreeObject(clone); + return NULL; + } + + return clone; +} + +void HcsAstFreeSubTree(ParserObject *object) +{ + ParserObjectBase *child = object->objectBase.child; + while (child != NULL) { + ParserObjectBase *tmp = child->next; + HcsAstRemoveChildLink((ParserObjectBase *)object, child); + HcsAstFreeObjectAndSubtree((ParserObject *)child); + child = tmp; + } +} + +bool HcsIsEmptyArray(const ParserObject *src) +{ + return src->objectBase.child == NULL; +} + +int32_t HcsAstCopyArray(const ParserObject *src, ParserObject *dst) +{ + if (src == NULL || dst == NULL) { + return NOERR; + } + + if (HcsIsEmptyArray(src)) { + return NOERR; + } + + if (!HcsIsEmptyArray(dst) && + !HcsIsSameTypeObject((ParserObject *)src->objectBase.child, (ParserObject *)dst->objectBase.child)) { + HCS_OBJECT_ERROR(dst, "overwrite different type"); + return EINVALARG; + } + + /* Children of array is anonymous object, can not use name to index them, delete first */ + HcsAstFreeSubTree(dst); + dst->objectBase.child = NULL; + + ParserObject *arrayElement = (ParserObject *)src->objectBase.child; + while (arrayElement != NULL) { + ParserObject *copy = HcsParserObjectClone(arrayElement); + if (copy == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return EOOM; + } + HcsAstAddChild(dst, copy); + arrayElement = (ParserObject *)arrayElement->objectBase.next; + } + + return NOERR; +} + +static int32_t HcsCopyObject(const ParserObject *src, ParserObject *dst) +{ + if (!HcsIsSameTypeObject(src, dst)) { + HCS_OBJECT_ERROR(src, "overwrite different type"); + return EINVALARG; + } + + if (HcsIsNumberObject(src)) { + dst->objectBase.integerValue = src->objectBase.integerValue; + } else if (HcsIsStringObject(src)) { + HcsMemFree(dst->objectBase.stringValue); + dst->objectBase.stringValue = strdup(src->objectBase.stringValue); + if (dst->objectBase.stringValue == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return EOOM; + } + } else if (src->objectBase.type == PARSEROP_ARRAY) { + return HcsAstCopyArray(src, dst); + } + + return NOERR; +} + +/* + * Copy src tree as dstTree's child + */ +static int32_t HcsAstCopyTree(ParserObject *src, ParserObject *dstTree, uint32_t overWriteFlag) +{ + if (src == NULL || dstTree == NULL) { + return NOERR; + } + + int32_t ret; + ParserObject *dstExistObject = HcsAstLookupObjectInChildren(dstTree, src->objectBase.name); + if (dstExistObject == NULL) { + ParserObject *copy = HcsParserObjectClone(src); + HcsAstAddChild(dstTree, copy); + dstExistObject = copy; + if (src->objectBase.type == PARSEROP_ARRAY) { + return HcsAstCopyArray(src, dstExistObject); + } + } else if (overWriteFlag == AST_COPY_SRC_OVER_DST) { + ret = HcsCopyObject(src, dstExistObject); + if (ret || src->objectBase.type == PARSEROP_ARRAY) { + return ret; + } + } else if (HcsOptShouldGenTextConfig() && HcsIsNumberObject(src) && + dstExistObject->objectBase.type > src->objectBase.type) { + /* At template case, should do type upward transformation to template */ + src->objectBase.type = dstExistObject->objectBase.type; + } + + ParserObjectBase *srcChild = src->objectBase.child; + while (srcChild != NULL) { + ret = HcsAstCopyTree((ParserObject *)srcChild, dstExistObject, overWriteFlag); + if (ret) { + return ret; + } + srcChild = srcChild->next; + } + + return NOERR; +} + +int32_t HcsAstCopySubTree(ParserObject *src, ParserObject *dst, uint32_t overWriteFlag) +{ + if (src == NULL || dst == NULL) { + return NOERR; + } + + if (!HcsIsSameTypeObject(src, dst)) { + HCS_OBJECT_ERROR(src, "overwrite different type"); + return EINVALARG; + } + + ParserObjectBase *srcChild = src->objectBase.child; + while (srcChild != NULL) { + int32_t ret = HcsAstCopyTree((ParserObject *)srcChild, dst, overWriteFlag); + if (ret) { + return ret; + } + srcChild = srcChild->next; + } + + return NOERR; +} + +static int32_t inline AstWalkCallBackDefault(ParserObject *current, int32_t walkDepth) +{ + (void)current; + (void)walkDepth; + return NOERR; +} + +static int32_t HcsForwardWalkAst(ParserObject *start, AstWalkCallBack callback) +{ + ParserObjectBase *startObj = (ParserObjectBase *)start; + ParserObjectBase *forwardWalkObj = startObj; + int32_t walkDepth = 0; + bool preVisited = false; + + while (forwardWalkObj != NULL) { + if (!preVisited) { + int32_t ret = callback((ParserObject *)forwardWalkObj, walkDepth); + if (ret && ret != EASTWALKBREAK) { + return EINVALARG; + } else if (!ret && forwardWalkObj->child) { + /* when callback return EASTWALKBREAK, not walk current's child */ + walkDepth++; + forwardWalkObj = forwardWalkObj->child; + continue; + } + } + if (forwardWalkObj == startObj) { + break; + } + + if (forwardWalkObj->next) { + forwardWalkObj = forwardWalkObj->next; + preVisited = false; + } else { + forwardWalkObj = forwardWalkObj->parent; + preVisited = true; + walkDepth--; + } + } + + return NOERR; +} + +static int32_t HcsBackwardWalkAst(ParserObject *start, AstWalkCallBack callback) +{ + ParserObjectBase *startObj = (ParserObjectBase *)start; + ParserObjectBase *backWalkObj = startObj; + ParserObjectBase *next = NULL; + ParserObjectBase *parent = NULL; + int32_t walkDepth = 0; + bool preVisited = false; + + while (backWalkObj != NULL) { + if (backWalkObj->child == NULL || preVisited) { + next = backWalkObj->next; + parent = backWalkObj->parent; + /* can safe delete current in callback */ + if (callback((ParserObject *)backWalkObj, walkDepth)) { + return EINVALARG; + } + } else { + if (backWalkObj->child) { + walkDepth++; + backWalkObj = backWalkObj->child; + continue; + } + } + if (backWalkObj == startObj) { + break; + } + + if (next != NULL) { + backWalkObj = next; + preVisited = false; + } else { + backWalkObj = parent; + preVisited = true; + walkDepth--; + } + } + + return NOERR; +} + +static int32_t HcsRoundWalkAst(ParserObject *start, AstWalkCallBack forwardCallback, AstWalkCallBack backwardCallback) +{ + ParserObjectBase *startObj = (ParserObjectBase *)start; + ParserObjectBase *roundWalkObj = startObj; + int32_t walkDepth = 0; + bool preVisited = false; + + while (roundWalkObj != NULL) { + if (preVisited) { + if (backwardCallback((ParserObject *)roundWalkObj, walkDepth)) { + return EFAIL; + } + } else { + int32_t ret = forwardCallback((ParserObject *)roundWalkObj, walkDepth); + /* when callback return EASTWALKBREAK, not walk current's child */ + if (ret && ret != EASTWALKBREAK) { + return EFAIL; + } else if (!ret && roundWalkObj->child) { + walkDepth++; + roundWalkObj = roundWalkObj->child; + continue; + } + } + if (roundWalkObj == startObj) { + break; + } + + if (roundWalkObj->next) { + roundWalkObj = roundWalkObj->next; + preVisited = false; + } else { + roundWalkObj = roundWalkObj->parent; + preVisited = true; + walkDepth--; + } + } + + return NOERR; +} + +uint16_t HcsGetTermType(ParserObject *object) +{ + if (object->objectBase.type != PARSEROP_CONFTERM || object->objectBase.child == NULL) { + return 0; + } + return object->objectBase.child->type; +} + +int32_t HcsWalkAst(ParserObject *start, uint32_t walkDirection, AstWalkCallBack forwardCallback, + AstWalkCallBack backwardCallback) +{ + forwardCallback = forwardCallback ? forwardCallback : AstWalkCallBackDefault; + backwardCallback = backwardCallback ? backwardCallback : AstWalkCallBackDefault; + ParserObject *startObj = start ? start : g_parserRoot; + + int32_t ret; + switch (walkDirection) { + case AST_WALK_FORWARD: + ret = HcsForwardWalkAst(startObj, forwardCallback); + break; + case AST_WALK_BACKEND: + ret = HcsBackwardWalkAst(startObj, backwardCallback); + break; + case AST_WALK_ROUND: + ret = HcsRoundWalkAst(startObj, forwardCallback, backwardCallback); + break; + default: + HCS_ERROR("unknown ast walk type(%u)", walkDirection); + return EINVALARG; + } + + return ret; +} + +static const char *g_parserOpTypeStr[PARSEROP_COUNT] = { + [PARSEROP_UINT8] = "UINT8", + [PARSEROP_UINT16] = "UINT16", + [PARSEROP_UINT32] = "UINT32", + [PARSEROP_UINT64] = "UINT64", + [PARSEROP_STRING] = "STRING", + [PARSEROP_CONFNODE] = "CONFNODE", + [PARSEROP_CONFTERM] = "CONFTERM", + [PARSEROP_ARRAY] = "ARRAY", + [PARSEROP_NODEREF] = "NODEREF", +}; + +static const char *ParserOpTypeToStr(uint32_t type) +{ + if (type >= PARSEROP_COUNT) { + return "unknown_type"; + } + + return g_parserOpTypeStr[type]; +} + +#define AST_PRINT_TAB_SIZE 2 + +static int32_t AstDumpWalkCallback(ParserObject *current, int32_t walkDepth) +{ + int32_t printTab = walkDepth * AST_PRINT_TAB_SIZE; + + HCS_PRINT("%-15s%*c%-10s", ParserOpTypeToStr(current->objectBase.type), printTab, ' ', current->configNode.name); + switch (current->objectBase.type) { + case PARSEROP_UINT8: + case PARSEROP_UINT16: + case PARSEROP_UINT32: + case PARSEROP_UINT64: + HCS_PRINT(" %"PRIx64, current->configTerm.integerValue); + break; + case PARSEROP_STRING: + HCS_PRINT(" %s", current->configTerm.stringValue); + break; + case PARSEROP_CONFNODE: { + if (current->configNode.nodeType != CONFIG_NODE_NOREF) { + HCS_PRINT("%-10s %-10s", HcsParserNodeTypeToStr(current->configNode.nodeType), + current->configNode.refNodePath ? current->configNode.refNodePath : ""); + } + } break; + case PARSEROP_NODEREF: + HCS_PRINT("%-10s %"PRIx64, "NodeReference", current->objectBase.value); + break; + default: + break; + } + + HCS_PRINT("\n"); + + return NOERR; +} + +uint16_t HcsCountArraySize(const ParserObject *arrayObj) +{ + if (arrayObj == NULL) { + return 0; + } + + ParserObjectBase *child = arrayObj->objectBase.child; + uint16_t size = 0; + while (child != NULL) { + size++; + child = child->next; + } + + return size; +} + +const char *HcsGetModuleName(void) +{ + ParserObject *root = HcsGetParserRoot(); + if (root == NULL) { + return NULL; + } + + ParserObject *moduleAttr = HcsAstLookupObjectInChildren(root, "module"); + if (moduleAttr == NULL) { + HCS_OBJECT_ERROR(root, "miss 'module' attribute under root node"); + return NULL; + } + + return moduleAttr->configTerm.child->stringValue; +} + +void HcsDumpAst(const char *label) +{ + HCS_PRINT("\nDump %s AST tree:\n", label); + if (HcsWalkAst(g_parserRoot, AST_WALK_FORWARD, AstDumpWalkCallback, NULL)) { + HCS_WARNING("%s failed", __func__); + } +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_bytecode_gen.c b/tools/hc-gen/src/hcs_bytecode_gen.c new file mode 100755 index 00000000..1a5e70e7 --- /dev/null +++ b/tools/hc-gen/src/hcs_bytecode_gen.c @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "hcs_compiler.h" +#include "hcs_file.h" +#include "hcs_opcode.h" +#include "hcs_log.h" +#include "hcs_option.h" + +#define DEBUG_PRINT_TAB_SIZE 2 + +static int32_t ByteCodeConvert(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + /* template should not output */ + if (current->objectBase.type == PARSEROP_CONFNODE && current->configNode.nodeType == CONFIG_NODE_TEMPLATE) { + HcsAstRemoveChildLink(current->objectBase.parent, ¤t->objectBase); + HcsDeleteParserObjectTree(current); + return NOERR; + } + const OpCodeMapEntry *opcodeEntry = HcsParserObjectTypeToByteCode(current->objectBase.type); + if (opcodeEntry == NULL) { + return EFAIL; + } + current->objectBase.opCode = opcodeEntry->opCode; + + /* calculate leaf size when forward walk */ + HcsCalculateOpcodeSize(current); + + return NOERR; +} + +static void DumpParserObjectValue(const ParserObject *obj) +{ + switch (obj->objectBase.opCode) { + case HCS_BYTE_OP: + case HCS_WORD_OP: + case HCS_DWORD_OP: + case HCS_QWORD_OP: + HCS_PRINT("%"PRIu64, obj->objectBase.integerValue); + break; + case HCS_STRING_OP: + HCS_PRINT("%s", obj->objectBase.stringValue); + break; + default: + break; + } +} + +static int32_t OpCodeDumpPrint(ParserObject *current, int32_t walkDepth) +{ + int32_t printTab = walkDepth * DEBUG_PRINT_TAB_SIZE; + uint8_t opCode = current->objectBase.opCode; + uint32_t size = current->objectBase.size; + HCS_PRINT("%-10x%-15s%-10u%-10u%*c%-10s", opCode, HcsOpcodeToStr(current->objectBase.type), size, + current->objectBase.subSize, printTab, ' ', current->configNode.name); + + DumpParserObjectValue(current); + HCS_PRINT("\n"); + return NOERR; +} + +static void DumpFinalAstWithOpCode() +{ + HCS_PRINT("\nDump final AST with OpCode\n"); + HCS_PRINT("%-10s%-15s%-10s%-10s%*c%-20s\n", "OpCode", "OpCodeName", "Size", "SubSize", 1, ' ', "ObjectName"); + HcsWalkAst(NULL, AST_WALK_FORWARD, OpCodeDumpPrint, NULL); +} + +static int32_t ByteCodeWriteWalk(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + current->objectBase.hash = HcsGetOutputCurrentCount(); + if (HcsOutputWriteAlign(¤t->objectBase.opCode, sizeof(current->objectBase.opCode))) { + return EOUTPUT; + } + int32_t ret = NOERR; + switch (current->objectBase.opCode) { + case HCS_BYTE_OP: + case HCS_WORD_OP: + case HCS_DWORD_OP: + case HCS_QWORD_OP: { + const OpCodeMapEntry *byteCodeMap = HcsGetOpCodeMap(); + ret = HcsOutputWriteAlign(¤t->objectBase.integerValue, byteCodeMap[current->objectBase.type].size); + break; + } + case HCS_STRING_OP: + ret = HcsOutputWriteAlign(current->objectBase.stringValue, strlen(current->objectBase.stringValue) + 1); + break; + case HCS_TERM_OP: + ret = HcsOutputWriteAlign((void *)current->objectBase.name, strlen(current->objectBase.name) + 1); + break; + case HCS_NODE_OP: + if (HcsOutputWriteAlign((void *)current->objectBase.name, strlen(current->objectBase.name) + 1)) { + return EOUTPUT; + } + ret = HcsOutputWriteAlign(¤t->objectBase.subSize, sizeof(current->objectBase.subSize)); + break; + /* fall-through */ + case HCS_ARRAY_OP: { + uint16_t size = HcsCountArraySize(current); + ret = HcsOutputWriteAlign(&size, sizeof(size)); + } + break; + case HCS_NODEREF_OP: { + ParserObject *ref = (ParserObject *)current->objectBase.value; + uint32_t hashCode = ref->objectBase.hash; + ret = HcsOutputWriteAlign(&hashCode, sizeof(hashCode)); + } + break; + default: + break; + } + + return ret; +} + +int32_t HcsBytecodeOutput() +{ + ParserObject *astRoot = HcsGetParserRoot(); + if (astRoot == NULL) { + return EFAIL; + } + + /* generate OpCode for every object on AST and calculate size for each */ + int32_t ret = HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, ByteCodeConvert); + if (ret) { + return ret; + } + + /* ast data is ready, do binder output */ + struct HcsFile *outputFIle = HcsOpenOutputFile(HCS_OUTPUT_FILE_SUFFIX); + + HbcHeader header = { + .magicNumber = HBC_MAGIC_NUM, + .checkSum = 0, + .totalSize = HcsOptShouldAlign() ? -astRoot->objectBase.size : astRoot->objectBase.size, + .versionMajor = HCS_COMPILER_VERSION_MAJOR, + .versionMinor = HCS_COMPILER_VERSION_MINOR, + }; + + HcsMockOutPut(true); + /* Generate hashcode for each object */ + if (HcsOutputWriteAlign(&header, sizeof(header))) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + ret = HcsWalkAst(astRoot, AST_WALK_FORWARD, ByteCodeWriteWalk, NULL); + if (ret) { + HcsCloseOutput(outputFIle); + return ret; + } + HcsResetOutputCurrentCount(); + HcsMockOutPut(false); + + if (HcsVerbosePrint()) { + DumpFinalAstWithOpCode(); + } + + /* write bytecode to output file */ + if (HcsOutputWriteAlign(&header, sizeof(header))) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + ret = HcsWalkAst(astRoot, AST_WALK_FORWARD, ByteCodeWriteWalk, NULL); + + /* verify file size */ + uint64_t fileSize = HcsSourceFileGetSize(outputFIle); + if (fileSize != (sizeof(header) + abs(header.totalSize))) { + HCS_ERROR("output file size mismatch"); + ret = EOUTPUT; + } + + HcsCloseOutput(outputFIle); + HCS_INFO("Total size: %u ", astRoot->objectBase.size); + if (ret == NOERR && HcsOptShouldGenHexdump()) { + ret = HcsBinaryToHexdump(HcsGetOutPutFileName()); + } + return ret; +} diff --git a/tools/hc-gen/src/hcs_compiler.l b/tools/hc-gen/src/hcs_compiler.l new file mode 100755 index 00000000..ff1a4931 --- /dev/null +++ b/tools/hc-gen/src/hcs_compiler.l @@ -0,0 +1,116 @@ +%option noyywrap +%option nodefault +%option yylineno +%option nounput +%option noinput +%x CMT + +%{ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_parser.h" +#include "hcs_gen_parser.h" + +#ifdef LEXER_DEBUG_ENABLE +#define LEXER_DEBUG(...) printf(__VA_ARGS__) +#else +#define LEXER_DEBUG(...) +#endif + +extern void HcsCompilererror (char *s); +%} + +%% +"/*" {BEGIN(CMT);} +"*/" {BEGIN(INITIAL); } +([^*]|\n)+|. +<> {LEXER_DEBUG("%d:unterminated coment\n", HcsCompilerlineno); return 0;} +"//".*\n +"{" { LEXER_DEBUG("{\n"); return HcsCompilertext[0]; }; +"}" { LEXER_DEBUG("}\n"); return HcsCompilertext[0]; }; +":" { LEXER_DEBUG(":\n"); return HcsCompilertext[0]; }; +"[" { LEXER_DEBUG("[\n"); return HcsCompilertext[0]; }; +"]" { LEXER_DEBUG("]\n"); return HcsCompilertext[0]; }; +";" { LEXER_DEBUG(";\n"); return HcsCompilertext[0]; }; +"&" { LEXER_DEBUG("REF\n"); return HcsCompilertext[0]; } +"=" { LEXER_DEBUG("=\n"); return HcsCompilertext[0]; } +"," { LEXER_DEBUG("=\n"); return HcsCompilertext[0]; } +"root" { LEXER_DEBUG("root\n"); return ROOT; } +"true" { HcsCompilerlval.i = 1; return NUMBER; } +"false" { HcsCompilerlval.i = 0; return NUMBER; } +"#include" { LEXER_DEBUG("INCLUDE\n"); return INCLUDE; } +"delete" { return DELETE; } +"template" { return TEMPLATE; } + +0x[0-9A-Fa-f]+ { HcsCompilerlval.i = strtoll(HcsCompilertext, NULL, 16); + LEXER_DEBUG("NUMBER : %u\n", HcsCompilerlval.i); + return NUMBER; + } +0[0-9]+ { HcsCompilerlval.i = strtoll(HcsCompilertext, NULL, 8); + LEXER_DEBUG("NUMBER : %u\n", HcsCompilerlval.i); + return NUMBER; + } +[-+]?[0-9]+ { HcsCompilerlval.i = atoll(HcsCompilertext); + LEXER_DEBUG("NUMBER : %u\n", HcsCompilerlval.i); + return NUMBER; + } +0b[01]+ { + HcsCompilerlval.i = strtoll(HcsCompilertext + 2, NULL, 2); + LEXER_DEBUG("NUMBER : %u\n", HcsCompilerlval.i); + return NUMBER; + } +[a-zA-Z0-9_]+ { HcsCompilerlval.s = strdup(HcsCompilertext); + LEXER_DEBUG("STRING : %s \n", HcsCompilertext); + return LITERAL; + } +[a-zA-Z0-9_\.?]+ { HcsCompilerlval.s = strdup(HcsCompilertext); + LEXER_DEBUG("REF_PATH : %s \n", HcsCompilertext); + return REF_PATH; + } +\"[^\"\n]*\" { LEXER_DEBUG("CONST_STRING : %s\n", HcsCompilertext); + char *constString = strdup(HcsCompilertext + 1); + constString[strlen(constString) - 1] = '\0'; + HcsCompilerlval.s = constString; + return STRING; + } +\"[^\"\n]*$ { HcsCompilererror("Unterminated string"); } +"\n" +[ \t] { } /* ignore */ +[\r] { } /* ignore */ +. { HcsCompilererror("bad input character"); } + +%% +extern FILE *HcsCompilerin; +void HcsSetCompilerIn(FILE *in) +{ + HcsCompilerin = in; +} diff --git a/tools/hc-gen/src/hcs_compiler.y b/tools/hc-gen/src/hcs_compiler.y new file mode 100755 index 00000000..ebb9cb59 --- /dev/null +++ b/tools/hc-gen/src/hcs_compiler.y @@ -0,0 +1,191 @@ +%{ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "hcs_compiler.h" + +#define YYDEBUG 1 +#define YYERROR_VERBOSE 1 +#define OBJPTR ParserObject* + +void HcsCompilererror (const char *s); +int yylex (void); +extern int HcsCompilerlineno; +%} + + +%union { + uint64_t i; + char *s; + ParserObject *o; +} + +%token NUMBER +%token TEMPLATE +%token LITERAL +%token STRING +%token REF_PATH +%token FILE_PATH + +%token EOL +%token ROOT +%token INCLUDE +%token DELETE + + +%type ConfigTermList ConfigNode ConfigTerm NumberList ConstStringList ConfigBlock NodeTemplate +%type NodePath + + +%% +ConfigTable + : + | IncludeList + | IncludeList + RootNode + | RootNode + ; + +RootNode + : ROOT + '{' { $$ = HcsGetParserRoot(); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { HcsAstAddChild($3, $4); } + ; + +IncludeList + : INCLUDE STRING { if (HcsProcessInclude($2, HcsCompilerlineno)) YYABORT; } + | INCLUDE STRING IncludeList { if (HcsProcessInclude($2, HcsCompilerlineno)) YYABORT; } + ; + +ConfigTermList + : { $$ = NULL; } + | ConfigTerm + ';' + ConfigTermList { $$ = HcsAstAddPeer($1, $3); } + | ConfigBlock + ConfigTermList { $$ = HcsAstAddPeer($1, $2); } + ; + +ConfigBlock + : ConfigNode + | NodeTemplate + +ConfigNode + : LITERAL + '{' { $$ = HcsNewConfigNode($1, CONFIG_NODE_NOREF, NULL); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($3, $4); } + | LITERAL ':' NodePath '{' { $$ = HcsNewConfigNode($1, CONFIG_NODE_COPY, $3); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($5, $6); } + | LITERAL ':' '&' NodePath '{' { $$ = HcsNewConfigNode($1, CONFIG_NODE_REF, $4); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($6, $7); } + | LITERAL ':' DELETE '{' { $$ = HcsNewConfigNode($1, CONFIG_NODE_DELETE, NULL); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($5, $6); } + | LITERAL ':' ':' + NodePath + '{' { $$ = HcsNewConfigNode($1, CONFIG_NODE_INHERIT, $4); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($6, $7); } + ; + +NodeTemplate : TEMPLATE LITERAL + '{' { $$ = HcsNewConfigNode($2, CONFIG_NODE_TEMPLATE, NULL); if ($$ == NULL) YYABORT; } + ConfigTermList + '}' { $$ = HcsAstAddChild($4, $5); } + +NodePath + : REF_PATH { $$ = $1; } + | LITERAL { $$ = $1; } + ; + +ConfigTerm + : LITERAL '=' STRING { $$ = HcsNewConfigTerm($1, HcsNewParserObject(NULL, PARSEROP_STRING, (uint64_t)$3)); + if ($$ == NULL) YYABORT; } + | LITERAL '=' NUMBER { $$ = HcsNewConfigTerm($1, HcsNewParserObject(NULL, PARSEROP_UINT64, (uint64_t)$3)); + if ($$ == NULL) YYABORT; } + | LITERAL '=' '[' ']' { HcsCompilererror("Not allow empty array"); YYABORT;} + | LITERAL '=' '[' NumberList ']' { OBJPTR obj = HcsNewParserObject(NULL, PARSEROP_ARRAY, (uint64_t)NULL); + if (obj == NULL) YYABORT; + $$ = HcsNewConfigTerm($1, HcsAstAddChild(obj, $4)); + if ($$ == NULL) YYABORT; } + | LITERAL '=' '[' ConstStringList ']' { OBJPTR obj = HcsNewParserObject(NULL, PARSEROP_ARRAY, (uint64_t)NULL); + if (obj == NULL) YYABORT; + $$ = HcsNewConfigTerm($1, HcsAstAddChild(obj, $4)); + if ($$ == NULL) YYABORT; } + | LITERAL '=' '&' NodePath { OBJPTR obj = HcsNewParserObject(NULL, PARSEROP_NODEREF, (uint64_t)$4); + if (obj == NULL) YYABORT; + $$ = HcsNewConfigTerm($1, obj); + if ($$ == NULL) YYABORT; } + | LITERAL '=' DELETE { $$ = HcsNewConfigTerm($1, + HcsNewParserObject(NULL, PARSEROP_DELETE, (uint64_t)NULL)); } + ; + +NumberList + : NUMBER { $$ = HcsNewParserObject(NULL, PARSEROP_UINT64, $1); if ($$ == NULL) YYABORT; } + | NUMBER ',' NumberList { OBJPTR obj = HcsNewParserObject(NULL, PARSEROP_UINT64, $1); if (obj == NULL) YYABORT; + $$ = HcsAstAddPeer(obj, $3); } + ; + +ConstStringList + : STRING { $$ = HcsNewParserObject(NULL, PARSEROP_STRING, (uint64_t)$1); if ($$ == NULL) YYABORT;} + | STRING ',' ConstStringList { OBJPTR obj = HcsNewParserObject(NULL, PARSEROP_STRING, (uint64_t)$1); if (obj == NULL) YYABORT; + $$ = HcsAstAddPeer(obj, $3); } + ; + +%% +extern char *HcsCompilertext; +extern int HcsCompilerlineno; + +const char*HcsGetCurrentSourceName(); + +int32_t HcsGetCurrentSourceLine(void) { + return HcsCompilerlineno; +} + +void HcsSetCurrentSourceLine(int32_t lineNumber) { + HcsCompilerlineno = lineNumber; +} + +void HcsCompilererror (const char *s) { + fprintf(stderr, "Error: %s:%d\n\t%s\n", HcsGetCurrentSourceName(), HcsCompilerlineno, s); +} + +void HcsCompilerrestart(FILE *input_file); + +void HcsParserRestart(FILE *inputFile) { + HcsCompilerrestart(inputFile); +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_decompile_gen.c b/tools/hc-gen/src/hcs_decompile_gen.c new file mode 100755 index 00000000..38935730 --- /dev/null +++ b/tools/hc-gen/src/hcs_decompile_gen.c @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "hcs_file.h" +#include "hcs_ast.h" +#include "hcs_mem.h" +#include "hcs_log.h" + +#define WRITE_BUFFER_LEN 256 +#define HCS_TAB_SIZE 4 + +#define HCS_DECOMPILE_FILE_HEADER \ + "/*\n" \ + " * HDF decompile hcs file\n" \ + " */\n\n" + +static char *HcsAssembleNodeRefName(char *buff, uint32_t buffSize, const char *name) +{ + int32_t res = strcat_s(buff, buffSize, name); + if (res) { + HCS_ERROR("%s:%d: string cat fail", __func__, __LINE__); + return NULL; + } + char *str = strdup(buff); + if (str == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return NULL; + } + return str; +} + +static char *HcsGetNodeRefPath(uint64_t hash) +{ + char pathBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char *path = pathBuffer; + ParserObjectBase *it = (ParserObjectBase *)HcsGetParserRoot(); + if (it == NULL) { + return NULL; + } + + while (it->child) { + int32_t res = strcat_s(path, WRITE_BUFFER_LEN, it->name); + if (res) { + HCS_ERROR("%s:%d: strcat fail", __func__, __LINE__); + return NULL; + } + res = strcat_s(path, WRITE_BUFFER_LEN, "."); + if (res) { + HCS_ERROR("%s:%d: strcat fail", __func__, __LINE__); + return NULL; + } + ParserObjectBase *child = it->child; + bool deepIn = false; + while (child != NULL) { + if (child->type != PARSEROP_CONFNODE) { + child = child->next; + continue; + } + if (child->hash == hash) { + return HcsAssembleNodeRefName(pathBuffer, WRITE_BUFFER_LEN, child->name); + } + + if (hash > child->hash && hash < (child->hash + child->size)) { + it = child; + deepIn = true; + break; + } + child = child->next; + } + if (!deepIn) { + HCS_ERROR("ref unknown node, hash = %"PRIu64, hash); + return NULL; + } + } + + return NULL; +} + +static int32_t HcsDecompilePrintBaseType(char *buffer, uint32_t bufferSize, const ParserObject *object); + +static int32_t HcsDecompilePrintArrayType(char *buffer, uint32_t bufferSize, const ParserObject *object) +{ + int32_t res = sprintf_s(buffer, bufferSize, "["); + PRINTF_CHECK_AND_RETURN(res); + ParserObject *arrayElement = (ParserObject *)object->objectBase.child; + while (arrayElement->objectBase.next) { + res = HcsDecompilePrintBaseType(buffer + strlen(buffer), bufferSize - strlen(buffer), arrayElement); + if (res) { + return EOUTPUT; + } + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ", "); + PRINTF_CHECK_AND_RETURN(res); + arrayElement = (ParserObject *)arrayElement->objectBase.next; + } + res = HcsDecompilePrintBaseType(buffer + strlen(buffer), bufferSize - strlen(buffer), arrayElement); + if (res) { + return EOUTPUT; + } + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), "]"); + PRINTF_CHECK_AND_RETURN(res); + + return NOERR; +} + +static int32_t HcsDecompilePrintBaseType(char *buffer, uint32_t bufferSize, const ParserObject *object) +{ + int32_t res; + switch (object->objectBase.type) { + case PARSEROP_UINT8: + case PARSEROP_UINT16: + case PARSEROP_UINT32: + case PARSEROP_UINT64: + res = sprintf_s(buffer, bufferSize, "0x%"PRIx64, object->objectBase.integerValue); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_STRING: + res = sprintf_s(buffer, bufferSize, "\"%s\"", object->objectBase.stringValue); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_NODEREF: { + char *refPath = HcsGetNodeRefPath(object->objectBase.value); + if (refPath == NULL) { + return EOUTPUT; + } + res = sprintf_s(buffer, bufferSize, "&%s", refPath); + HcsMemFree(refPath); + PRINTF_CHECK_AND_RETURN(res); + } + break; + case PARSEROP_ARRAY: + return HcsDecompilePrintArrayType(buffer, bufferSize, object); + default: + HCS_ERROR("unknown OpCode %u", object->objectBase.type); + return EFAIL; + } + + return NOERR; +} + +static int32_t HcsDecompileOutputWalk(ParserObject *current, int32_t walkDepth) +{ + if (current->objectBase.type != PARSEROP_CONFNODE && current->objectBase.type != PARSEROP_CONFTERM) { + return NOERR; + } + + int32_t res; + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t tabSize = walkDepth * HCS_TAB_SIZE; + if (walkDepth) { + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c", tabSize, ' '); + PRINTF_CHECK_AND_RETURN(res); + } + + switch (current->objectBase.type) { + case PARSEROP_CONFNODE: + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), + "%s {\n", current->configNode.name); + PRINTF_CHECK_AND_RETURN(res); + if (current->objectBase.child == NULL) { + res = sprintf_s(writeBuffer + strlen(writeBuffer) - 1, + WRITE_BUFFER_LEN - strlen(writeBuffer) + 1, "}\n"); + PRINTF_CHECK_AND_RETURN(res); + } + break; + case PARSEROP_CONFTERM: + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), + "%s = ", current->configNode.name); + PRINTF_CHECK_AND_RETURN(res); + res = HcsDecompilePrintBaseType(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), + (ParserObject *)current->configNode.child); + if (res) { + return res; + } + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), ";\n"); + PRINTF_CHECK_AND_RETURN(res); + break; + default: + break; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsDecompileCloseBraceGen(ParserObject *current, int32_t walkDepth) +{ + if (current->objectBase.type != PARSEROP_CONFNODE) { + return NOERR; + } + int32_t res; + int32_t tabSize = walkDepth * HCS_TAB_SIZE; + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + + if (current != HcsGetParserRoot()) { + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c}\n", tabSize, ' '); + PRINTF_CHECK_AND_RETURN(res); + } else { + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "}\n"); + PRINTF_CHECK_AND_RETURN(res); + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +int32_t HcsDecompileOutput() +{ + ParserObject *astRoot = HcsGetParserRoot(); + if (astRoot == NULL) { + return EOUTPUT; + } + + int32_t ret = EOUTPUT; + struct HcsFile *outputFIle = HcsOpenOutputFile(HCS_DECOMPILE_OUTPUT_FILE_SUFFIX); + if (outputFIle == NULL) { + goto OUT; + } + + const char *fileHeader = HCS_DECOMPILE_FILE_HEADER; + if (HcsOutputWrite(fileHeader, strlen(fileHeader))) { + goto OUT; + } + + ret = HcsWalkAst(astRoot, AST_WALK_ROUND, HcsDecompileOutputWalk, HcsDecompileCloseBraceGen); + +OUT: + HcsCloseOutput(outputFIle); + return ret; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_decompiler.c b/tools/hc-gen/src/hcs_decompiler.c new file mode 100755 index 00000000..de352ba7 --- /dev/null +++ b/tools/hc-gen/src/hcs_decompiler.c @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "hcs_option.h" +#include "hcs_file.h" +#include "hcs_opcode.h" +#include "hcs_parser.h" +#include "hcs_log.h" +#include "hcs_compiler.h" +#include "hcs_decompiler.h" + +static ParserObject *RebuildObject(uint8_t opCode); + +static bool HcsVerifyHbcFile() +{ + struct HcsFile *input = HcsSourceQueueTop(); + HbcHeader header = { 0 }; + uint32_t size = HcsSourceFileRead(input, (uint8_t*)&header, sizeof(header)); + if (size != sizeof(header)) { + HCS_ERROR("Illegal hcb file, invalid file size"); + return false; + } + + if (header.magicNumber != HBC_MAGIC_NUM) { + HCS_ERROR("file %s is not a hcb file", HcsGetCurrentSourceName()); + return false; + } + if (header.totalSize < 0) { + HcsOptSetAlign(true); + header.totalSize = -header.totalSize; + } + uint32_t fileSize = HcsSourceFileGetSize(input); + if (fileSize != (sizeof(header) + header.totalSize)) { + HCS_ERROR("size mismatch, may broken file"); + return false; + } + + HCS_INFO("Build by hcs compile %u.%u", header.versionMajor, header.versionMinor); + HCS_INFO("hcb file total size: %u\n", header.totalSize); + return true; +} + +#define HCS_STRING_READ_BUF_LEN 256 + +static char *ReadCString() +{ + char buff[HCS_STRING_READ_BUF_LEN] = {'\0'}; + int32_t index = 0; + while (HcsSourceFileRead(NULL, (uint8_t*)&buff[index], sizeof(char))) { + if (index == HCS_STRING_READ_BUF_LEN || buff[index] == '\0') { + break; + } + index++; + } + + if (index >= HCS_STRING_READ_BUF_LEN || buff[index] != '\0') { + HCS_ERROR("read unterminated or too long c string at %u", HcsGetSourceFilePos(NULL)); + return NULL; + } + uint32_t stringFullSize = index + 1; + uint32_t alignAppendSize = HcsAlign(stringFullSize) - stringFullSize; + if (alignAppendSize) { + uint8_t alignReadBuffer[ALIGN_SIZE]; + if (HcsSourceFileRead(NULL, alignReadBuffer, alignAppendSize) != alignAppendSize) { + HCS_ERROR("read c string length mismatch %u", HcsGetSourceFilePos(NULL)); + return NULL; + } + } + char *str = strdup(buff); + if (str == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return NULL; + } + return str; +} + +static bool ReadUint64(uint64_t *value) +{ + if (HcsSourceFileRead(NULL, (uint8_t*)value, sizeof(*value)) != sizeof(*value)) { + HCS_ERROR("fail to read uint64"); + return false; + } + return true; +} + +static bool ReadUint32(uint32_t *value) +{ + if (HcsSourceFileRead(NULL, (uint8_t*)value, sizeof(*value)) != sizeof(*value)) { + HCS_ERROR("fail to read uint32"); + return false; + } + + return true; +} + +static bool ReadUint16(uint16_t *value) +{ + if (HcsAlign(sizeof(uint16_t)) != sizeof(uint16_t)) { + uint32_t readValue = 0; + if (!ReadUint32(&readValue)) { + return false; + } + *value = (uint16_t)readValue; + return true; + } + if (HcsSourceFileRead(NULL, (uint8_t*)value, sizeof(*value)) != sizeof(*value)) { + HCS_ERROR("fail to read uint16"); + return false; + } + + return true; +} + +static bool ReadUint8(uint8_t *value) +{ + if (HcsAlign(sizeof(uint8_t)) != sizeof(uint8_t)) { + uint32_t readValue = 0; + if (!ReadUint32(&readValue)) { + return false; + } + *value = (uint8_t)readValue; + return true; + } + + if (HcsSourceFileRead(NULL, value, sizeof(*value)) != sizeof(*value)) { + HCS_ERROR("fail to read uint8"); + return false; + } + + return true; +} + +static bool NextByteCode(uint32_t *byteCode) +{ + switch (HcsAlign(OPCODE_BYTE_WIDTH)) { + case BYTE_SIZE: { + uint8_t value = 0; + bool ret = ReadUint8(&value); + *byteCode = value; + return ret; + } + case DWORD_SIZE: + return ReadUint32(byteCode); + default: + break; + } + return false; +} + +static ParserObject *RebuildNode() +{ + uint32_t nodeHash = HcsGetSourceFilePos(NULL) - HcsAlign(OPCODE_BYTE_WIDTH); + char *nodeName = ReadCString(); + if (nodeName == NULL) { + return NULL; + } + + ParserObject *node = HcsNewConfigNode(nodeName, CONFIG_NODE_NOREF, NULL); + if (node == NULL) { + HcsMemFree(nodeName); + return NULL; + } + uint32_t nodeSize = 0; + if (!ReadUint32(&nodeSize)) { + goto ERROR; + } + node->objectBase.hash = nodeHash; + node->objectBase.size = nodeSize; + uint32_t pos = HcsGetSourceFilePos(NULL); // node content start + uint64_t nodeEnd = nodeSize + pos; + while (pos < nodeEnd) { + uint32_t childOpCode; + if (!NextByteCode(&childOpCode)) { + HCS_ERROR("broken node"); + goto ERROR; + } + ParserObject *child = RebuildObject(childOpCode); + if (child == NULL) { + goto ERROR; + } + HcsAstAddChild(node, child); + pos = HcsGetSourceFilePos(NULL); + } + + return node; +ERROR: + HcsDeleteParserObjectTree(node); + return NULL; +} + +static ParserObject *RebuildTerm() +{ + char *termName = ReadCString(); + if (termName == NULL) { + return NULL; + } + uint32_t childOpCode; + if (!NextByteCode(&childOpCode)) { + HCS_ERROR("broken term"); + HcsMemFree(termName); + return NULL; + } + + ParserObject *value = RebuildObject(childOpCode); + if (value == NULL) { + HcsMemFree(termName); + return NULL; + } + ParserObject *term = HcsNewConfigTerm(termName, value); + if (term == NULL) { + HcsMemFree(termName); + HcsAstFreeObject(value); + } + return term; +} + +static ParserObject *RebuildArray() +{ + uint16_t arraySize = 0; + if (!ReadUint16(&arraySize)) { + return NULL; + } + ParserObject *array = HcsNewParserObject(NULL, PARSEROP_ARRAY, 0); + if (array == NULL) { + return NULL; + } + for (int32_t i = 0; i < arraySize; ++i) { + uint32_t elementOpCode; + if (!NextByteCode(&elementOpCode)) { + HCS_ERROR("broken term"); + goto ERROR; + } + ParserObject *element = RebuildObject(elementOpCode); + if (element == NULL) { + goto ERROR; + } + HcsAstAddChild(array, element); + } + return array; +ERROR: + HcsDeleteParserObjectTree(array); + return NULL; +} + +static ParserObject *RebuildNumberObject(uint8_t type) +{ + uint8_t u8Value = 0; + uint16_t u16Value = 0; + uint32_t u32Value = 0; + uint64_t u64Value = 0; + switch (type) { + case HCS_BYTE_OP: + if (!ReadUint8(&u8Value)) { + return NULL; + } + return HcsNewParserObject(NULL, PARSEROP_UINT8, u8Value); + case HCS_WORD_OP: + if (!ReadUint16(&u16Value)) { + return NULL; + } + return HcsNewParserObject(NULL, PARSEROP_UINT16, u16Value); + case HCS_DWORD_OP: + if (!ReadUint32(&u32Value)) { + return NULL; + } + return HcsNewParserObject(NULL, PARSEROP_UINT32, u32Value); + case HCS_QWORD_OP: + if (!ReadUint64(&u64Value)) { + return NULL; + } + return HcsNewParserObject(NULL, PARSEROP_UINT64, u64Value); + default: + break; + } + + return NULL; +} + +static ParserObject *RebuildStringObject() +{ + char *objectName = ReadCString(); + if (objectName == NULL) { + return NULL; + } + ParserObject *object = HcsNewParserObject(NULL, PARSEROP_STRING, (uint64_t)objectName); + if (object == NULL) { + HcsMemFree(objectName); + } + return object; +} + +static ParserObject *RebuildNodeRefObject() +{ + uint32_t refNodeHash = 0; + if (!ReadUint32(&refNodeHash)) { + return NULL; + } + + return HcsNewParserObject(NULL, PARSEROP_NODEREF, refNodeHash); +} + +static ParserObject *RebuildObject(uint8_t opCode) +{ + switch (opCode) { + case HCS_NODE_OP: + return RebuildNode(); + case HCS_TERM_OP: + return RebuildTerm(); + case HCS_NODEREF_OP: + return RebuildNodeRefObject(); + case HCS_BYTE_OP: /* fall-through */ + case HCS_WORD_OP: /* fall-through */ + case HCS_DWORD_OP: /* fall-through */ + case HCS_QWORD_OP: + return RebuildNumberObject(opCode); + case HCS_ARRAY_OP: + return RebuildArray(); + case HCS_STRING_OP: + return RebuildStringObject(); + default: + break; + } + HCS_ERROR("unknown OpCode %u", opCode); + return NULL; +} + +static bool RebuildAst() +{ + uint32_t currByteCode = 0; + bool ret = NextByteCode(&currByteCode); + if (!ret || currByteCode != HCS_NODE_OP) { + HCS_ERROR("miss root node"); + return false; + } + + ParserObject *rootObject = RebuildObject(currByteCode); + if (rootObject == NULL) { + return false; + } + + HcsSetParserRoot(rootObject); + return true; +} + +int32_t HcsDoDecompile() +{ + struct HcsFile *source = NULL; + uint32_t ret = HcsOpenSourceFile(HcsGetInputFileName(), &source, "rb"); + if (ret) { + return ret; + } + HcsSourceQueuePush(source); + + do { + if (!HcsVerifyHbcFile()) { + ret = EDECOMP; + break; + } + + if (!RebuildAst()) { + HCS_ERROR("failed to rebuild ast from hcb file"); + ret = EDECOMP; + break; + } + if (HcsVerbosePrint()) { + HcsDumpAst("Rebuild"); + } + } while (0); + + HcsSourceQueuePop(); + HcsCloseFile(source); + if (ret == NOERR) { + ret = HcsDecompileOutput(); + } + HcsDeleteParserObjectTree(HcsGetParserRoot()); + HcsSetParserRoot(NULL); + HcsSourceNameSetClean(); + return ret; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_file.c b/tools/hc-gen/src/hcs_file.c new file mode 100755 index 00000000..51a379cc --- /dev/null +++ b/tools/hc-gen/src/hcs_file.c @@ -0,0 +1,535 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include "hcs_parser.h" +#include "hcs_mem.h" +#include "hcs_log.h" +#include "hcs_file.h" + +static char *g_outputFilename = NULL; +static FILE *g_outputFIle = NULL; +const char *g_inputFileName = NULL; +static bool g_dummyOutput = false; +static uint32_t g_outputWriteCount = 0; +static struct HcsFileQueue g_inputSourceFileQueue = { 0 }; +static struct HcsSourceName *g_sourceNameSetHead = NULL; + +void HcsSetInputFileName(const char *name) +{ + g_inputFileName = name; +} + +const char *HcsGetInputFileName() +{ + return g_inputFileName; +} + +/* + * Return: true - not exist, false - already exist and not overwrite + */ +int32_t HcsSourceNameSetPush(const char *name) +{ + if (g_sourceNameSetHead == NULL) { + struct HcsSourceName *head = HcsMemZalloc(sizeof(*head)); + if (head == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return EOOM; + } + head->name = name; + g_sourceNameSetHead = head; + return NOERR; + } + + struct HcsSourceName *pre = g_sourceNameSetHead; + struct HcsSourceName *last = pre; + while (last != NULL) { + if (!strcmp(last->name, name)) { + return EREOPENF; + } + pre = last; + last = last->next; + } + + struct HcsSourceName *new = HcsMemZalloc(sizeof(struct HcsSourceName)); + if (new == NULL) { + HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + return EOOM; + } + new->name = name; + pre->next = new; + return NOERR; +} + +bool HcsSourceNameSetFind(const char *name) +{ + struct HcsSourceName *last = g_sourceNameSetHead; + + while (last != NULL) { + if (!strcmp(last->name, name)) { + return true; + } + last = last->next; + } + + return false; +} + +void HcsSourceNameSetClean(void) +{ + struct HcsSourceName *term = g_sourceNameSetHead; + + while (term != NULL) { + struct HcsSourceName *temp = term->next; + HcsMemFree((void *)term->name); + HcsMemFree(term); + term = temp; + } + + g_sourceNameSetHead = NULL; +} + +static const char *GetFileName(const char *path) +{ + int32_t length = (int32_t)strlen(path); + int32_t i = length - 1; + for (; i >= 0; --i) { + if (path[i] == OS_SEPARATOR) { + break; + } + } + + return i > 0 ? path + i + 1 : path; +} + +static const char *CopyFileName(const char *path) +{ + return strdup(GetFileName(path)); +} + +static const char *GetFileNameWithoutSuffix(const char *path) +{ + char *fileNameRet = strdup(path); + if (fileNameRet == NULL) { + HCS_ERROR("oom"); + return NULL; + } + char *it = fileNameRet + strlen(fileNameRet); + while (it != fileNameRet) { + if (*it == '.') { + *it = '\0'; + break; + } + if (*it == OS_SEPARATOR) { + break; + } + it--; + } + + return fileNameRet; +} + +static int32_t CopyAndSaveFileName(const char *filePath, char **savedFileName, char **savedFilePath) +{ + const char *fileName = CopyFileName(filePath); + if (fileName == NULL) { + return EOOM; + } + + /* if no specified output file name, use input name */ + if (HcsGetOutPutFileName() == NULL && HcsSetOutPutNameWithCurrentWorkPath(fileName)) { + HcsMemFree((void *)fileName); + return EOOM; + } + + char *path = strdup(filePath); + if (path == NULL || HcsSourceNameSetPush(path)) { + HcsMemFree((void *)fileName); + HcsMemFree((void *)path); + return EOOM; + } + *savedFileName = (char *)fileName; + *savedFilePath = path; + return NOERR; +} + +int32_t HcsOpenSourceFile(const char *path, struct HcsFile **file, const char *flag) +{ + char pathBuf[PATH_MAX] = {'\0'}; +#ifdef MINGW32 + char *realPath = _fullpath(pathBuf, path, PATH_MAX); +#else + char *realPath = realpath(path, pathBuf); +#endif + if (realPath == NULL) { + HCS_ERROR("fail to open source file: %s", path); + return EINVALF; + } + + /* push to name set and check reopen */ + int32_t ret = HcsSourceNameSetFind(realPath); + if (ret == true) { + return EREOPENF; + } + + HCS_DEBUG("source file path: %s", realPath); + FILE *f = fopen(realPath, flag ? flag : "r"); + if (f == NULL) { + HCS_ERROR("fail to open source file: %s", realPath); + return EINVALF; + } + + char *fileName = NULL; + char *filePath = NULL; + ret = CopyAndSaveFileName(realPath, &fileName, &filePath); + if (ret) { + fclose(f); + return EFAIL; + } + + struct HcsFile *sourceFile = HcsMemZalloc(sizeof(struct HcsFile)); + if (sourceFile == NULL) { + HcsMemFree(fileName); + fclose(f); + HCS_ERROR("oom"); + return EOOM; + } + sourceFile->name = fileName; + sourceFile->fullPath = filePath; + sourceFile->file = f; + sourceFile->pos = 0; + *file = sourceFile; + return NOERR; +} + +uint64_t HcsSourceFileGetSize(struct HcsFile *file) +{ + uint64_t currentPos = ftell(file->file); + + fseek(file->file, 0, SEEK_END); + uint64_t fileSize = ftell(file->file); + fseek(file->file, currentPos, SEEK_SET); + + return fileSize; +} + +int32_t HcsSourceFileRead(struct HcsFile *file, uint8_t *out, uint32_t readSize) +{ + struct HcsFile *currentSrc = file ? file : HcsSourceQueueTop(); + if (currentSrc == NULL) { + HCS_ERROR("source file not valid"); + return -EINVALF; + } + + return fread(out, 1, readSize, currentSrc->file); +} + +uint32_t HcsGetSourceFilePos(struct HcsFile *file) +{ + struct HcsFile *currentSrc = file ? file : HcsSourceQueueTop(); + return ftell(currentSrc->file); +} + +void HcsCloseFile(struct HcsFile *file) +{ + if (file == NULL) { + return; + } + + fclose(file->file); + HcsMemFree((void *)file->name); + HcsMemFree(file); +} + +int32_t HcsSetOutPutNameWithCurrentWorkPath(const char *name) +{ + char outPutPath[PATH_MAX] = {0}; + char *cwd = getcwd(outPutPath, PATH_MAX); + if (cwd == NULL || !strlen(cwd)) { + return EFAIL; + } + + if (sprintf_s(outPutPath + strlen(outPutPath), PATH_MAX - strlen(outPutPath), "%c", OS_SEPARATOR) < 0) { + return EFAIL; + } + + if (strcat_s(outPutPath, PATH_MAX, name) != EOK) { + return EFAIL; + } + + return HcsSetOutPutName(outPutPath); +} + +int32_t HcsSetOutPutName(const char *name) +{ + if (g_outputFilename != NULL) { + HcsMemFree(g_outputFilename); + } + + g_outputFilename = strdup(name); + if (g_outputFilename == NULL) { + HCS_ERROR("oom"); + return EOOM; + } +#ifdef OS_WIN + char *temp = g_outputFilename; + while (*temp != '\0') { + if (*temp == UNIX_SEPARATOR) { + *temp = WIN_SEPARATOR; + } + temp++; + } +#endif + + return NOERR; +} + +bool HcsSetOutputFileSuffix(const char *suffix) +{ + const char *fileNameBefore = g_outputFilename; + const char *fileNameWithoutSuffix = GetFileNameWithoutSuffix(fileNameBefore); + if (fileNameWithoutSuffix == NULL) { + return false; + } + + uint32_t newNameSize = strlen(g_outputFilename) + strlen(suffix) + 1; + char *newOutputFilename = HcsMemZalloc(newNameSize); + if (newOutputFilename == NULL) { + HcsMemFree((void *)fileNameWithoutSuffix); + return false; + } + + int32_t ret = strcpy_s(newOutputFilename, newNameSize, fileNameWithoutSuffix); + HcsMemFree((void *)fileNameWithoutSuffix); + if (ret) { + HCS_ERROR("string copy fail"); + HcsMemFree(newOutputFilename); + return false; + } + ret = strcat_s(newOutputFilename, newNameSize, suffix); + if (ret) { + HCS_ERROR("string copy fail"); + HcsMemFree(newOutputFilename); + return false; + } + + HcsMemFree((void *)fileNameBefore); + g_outputFilename = newOutputFilename; + return true; +} + +// return output file name only +const char *HcsGetStripedOutputFileName() +{ + return GetFileName(g_outputFilename); +} + +// return full path of output file +const char *HcsGetOutPutFileName() +{ + return g_outputFilename; +} + +bool HcsOutputNameVerify() +{ + const char *fileName = g_outputFilename; + char lastChar = fileName[strlen(fileName) - 1]; + if (lastChar == OS_SEPARATOR) { + HCS_ERROR("output name is DIR"); + return false; + } + + return true; +} + +struct HcsFile *HcsOpenOutputFile(const char *suffix) +{ + if (!HcsOutputNameVerify()) { + return NULL; + } + if (!HcsSetOutputFileSuffix(suffix)) { + return NULL; + } + const char *outputFileName = HcsGetOutPutFileName(); + g_outputFIle = fopen(outputFileName, "wb"); + if (g_outputFIle == NULL) { + HCS_ERROR("fail to open output file: %s", outputFileName); + return NULL; + } + + HCS_INFO("Output: %s", outputFileName); + struct HcsFile *outputFile = HcsMemZalloc(sizeof(struct HcsFile)); + if (outputFile == NULL) { + HCS_ERROR("oom"); + fclose(g_outputFIle); + g_outputFIle = NULL; + return NULL; + } + outputFile->name = outputFileName; + outputFile->file = g_outputFIle; + outputFile->pos = 0; + outputFile->fullPath = outputFileName; + g_outputWriteCount = 0; + + return outputFile; +} + +void HcsCloseOutput(struct HcsFile *output) +{ + if (output == NULL || output->file == NULL) { + return; + } + + fflush(output->file); + fclose(output->file); + + HcsMemFree(output); + g_outputWriteCount = 0; +} + +int32_t HcsOutputWrite(const void *buffer, uint32_t length) +{ + g_outputWriteCount += length; + if (g_dummyOutput || !length) { + return NOERR; + } + + uint32_t writeLen = fwrite(buffer, 1, length, g_outputFIle); + if (writeLen != length) { + HCS_ERROR("output file write fail"); + return EOUTPUT; + } + + return NOERR; +} + +int32_t HcsOutputWriteAlign(const void *buffer, uint32_t length) +{ + static const uint8_t alignData[ALIGN_SIZE] = {0}; + int32_t ret = HcsOutputWrite(buffer, length); + if (ret) { + return ret; + } + int32_t appendSize = HcsAlign(length) - length; + if (appendSize) { + ret = HcsOutputWrite(alignData, appendSize); + } + return ret; +} + +void HcsMockOutPut(bool dummyOutput) +{ + g_dummyOutput = dummyOutput; +} + +uint32_t HcsGetOutputCurrentCount(void) +{ + return g_outputWriteCount; +} + +void HcsResetOutputCurrentCount(void) +{ + g_outputWriteCount = 0; +} + +void HcsSourceQueuePush(struct HcsFile *sourceFile) +{ + struct HcsFileQueue *sourceQueue = &g_inputSourceFileQueue; + struct HcsFile *queueLast = sourceQueue->head; + if (queueLast == NULL) { + sourceQueue->head = sourceFile; + sourceQueue->count = 1; + return; + } + + while (queueLast->next) { + queueLast = queueLast->next; + } + + queueLast->next = sourceFile; + sourceQueue->count++; +} + +void HcsSourceQueuePop() +{ + struct HcsFileQueue *sourceQueue = &g_inputSourceFileQueue; + if (sourceQueue->head == NULL) { + return; + } + sourceQueue->head = sourceQueue->head->next; + sourceQueue->count--; +} + +struct HcsFile *HcsSourceQueueTop() +{ + return g_inputSourceFileQueue.head; +} + +uint32_t HcsSourceQueueSize() +{ + return g_inputSourceFileQueue.count; +} + +const char *HcsGetCurrentSourceName() +{ + struct HcsFile *source = HcsSourceQueueTop(); + return source ? source->fullPath : ""; +} + +bool HcsFileCopyDir(char *dst, uint32_t dstBufferSize, const char *fullPath) +{ + const char *c = strlen(fullPath) + fullPath; + while (c >= fullPath) { + if (*c == OS_SEPARATOR) { + break; + } + c--; + } + int32_t len = (int32_t)(c - fullPath) + 1; + if (len <= 0) { + HCS_ERROR("%s: path '%s' not include dir", __func__, fullPath); + return false; + } + + int32_t ret = strncpy_s(dst, dstBufferSize, fullPath, len); + if (ret) { + HCS_ERROR("%s:string copy fail", __func__); + return false; + } + dst[len] = '\0'; + + return true; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_hexdump.c b/tools/hc-gen/src/hcs_hexdump.c new file mode 100755 index 00000000..7e938298 --- /dev/null +++ b/tools/hc-gen/src/hcs_hexdump.c @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include +#include +#include + +#define HCS_HEXDUMP_ENTRY_SYMBOL "hdfConfigEntrySymbol" +#define HCS_HEXDUMP_FILE_SUFFIX "_hex.c" +#define PRINT_SKIP_STEP 2 +#define NUMS_PER_LINE 16 + +int32_t HcsHexdumpOutput(FILE *in, FILE *out) +{ + const char *prefix = HcsOptGetSymbolNamePrefix(); + if (prefix == NULL) { + prefix = ""; + } + if (fprintf(out, "static const unsigned char g_%s%s[] = {\n", prefix, HCS_HEXDUMP_ENTRY_SYMBOL) < 0) { + return EOUTPUT; + } + uint32_t writeCount = 0; + int32_t byte; + while ((byte = getc(in)) != EOF) { + if (fprintf(out, "%s0x%02x", (writeCount % NUMS_PER_LINE) ? ", " : &",\n "[PRINT_SKIP_STEP * !writeCount], + byte) < 0) { + return EOUTPUT; + } + writeCount++; + } + if (fprintf(out, "\n};\n") < 0) { + return EOUTPUT; + } + + if (fprintf(out, "static const unsigned int g_%sLen = %u;\n", HCS_HEXDUMP_ENTRY_SYMBOL, writeCount) < 0) { + return EOUTPUT; + } + if (fprintf(out, + "void HdfGetBuildInConfigData(const unsigned char** data, unsigned int* size)\n" + "{\n" + " *data = g_%s%s;\n" + " *size = g_%s%sLen;\n" + "}", + prefix, HCS_HEXDUMP_ENTRY_SYMBOL, prefix, HCS_HEXDUMP_ENTRY_SYMBOL) < 0) { + return EOUTPUT; + } + return NOERR; +} + +int32_t HcsBinaryToHexdump(const char *inputFileName) +{ + struct HcsFile *source = NULL; + if (HcsOpenSourceFile(inputFileName, &source, "rb")) { + HCS_ERROR("can not open %s", inputFileName); + return EINVALF; + } + + struct HcsFile *out = HcsOpenOutputFile(HCS_HEXDUMP_FILE_SUFFIX); + if (out == NULL) { + HCS_ERROR("can not open %s", HcsGetOutPutFileName()); + return EINVALF; + } + + int32_t ret = HcsHexdumpOutput(source->file, out->file); + if (ret) { + HCS_ERROR("fail to gen bytecode hexdump in C style"); + } + HcsCloseFile(source); + HcsCloseFile(out); + return ret; +} diff --git a/tools/hc-gen/src/hcs_main.c b/tools/hc-gen/src/hcs_main.c new file mode 100755 index 00000000..737ce0d7 --- /dev/null +++ b/tools/hc-gen/src/hcs_main.c @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hcs_compiler.h" +#include "hcs_decompiler.h" +#include "hcs_option.h" + +int32_t main(int32_t argc, char *argv[]) +{ + int32_t status = DoOption(argc, argv); + if (status != NOERR) { + return status; + } + + if (HcsOptDecompile()) { + status = HcsDoDecompile(); + } else { + status = HcsDoCompile(); + } + + return status ? EFAIL : NOERR; +} diff --git a/tools/hc-gen/src/hcs_mem.c b/tools/hc-gen/src/hcs_mem.c new file mode 100755 index 00000000..8e5e28a3 --- /dev/null +++ b/tools/hc-gen/src/hcs_mem.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include "hcs_mem.h" +#define MEM_MAX (1024*1024) + +void *HcsMemAlloc(uint32_t size) +{ + if (size == 0 || size > MEM_MAX) { + return NULL; + } + + void *newMem = malloc(size); + return newMem; +} + +void *HcsMemZalloc(uint32_t size) +{ + void *newMem = HcsMemAlloc(size); + if (newMem == NULL) { + return NULL; + } + (void)memset_s(newMem, size, 0, size); + return newMem; +} + +void HcsMemFree(void *ptr) +{ + if (ptr != NULL) { + free(ptr); + } +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_middle.c b/tools/hc-gen/src/hcs_middle.c new file mode 100755 index 00000000..29fd632b --- /dev/null +++ b/tools/hc-gen/src/hcs_middle.c @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "hcs_compiler.h" +#include "hcs_option.h" + +static int32_t HcsNodeExpand(ParserObject *current); + +static ParserObject *HcsLookupAstObject(const ParserObject *current, const char *path) +{ + /* Not absolute path, lookup in peers */ + if (!strchr(path, '.')) { + return HcsAstLookupObjectInPeers(current, path); + } + + /* Absolute path lookup form root and subtree */ + char *splitPath = strdup(path); + if (splitPath == NULL) { + HCS_ERROR("oom"); + return NULL; + } + char *nodeName = strtok(splitPath, "."); + + /* path must start with "root" */ + if (nodeName == NULL || strcmp(nodeName, "root") != 0) { + HcsMemFree(splitPath); + return NULL; + } + + /* skip root in path */ + nodeName = strtok(NULL, "."); + ParserObject *object = HcsGetParserRoot(); + while (nodeName != NULL) { + object = HcsAstLookupObjectInChildren(object, nodeName); + if (object == NULL) + break; + nodeName = strtok(NULL, "."); + } + HcsMemFree(splitPath); + + if (object != NULL) { + return object; + } + + return NULL; +} + +static int32_t HcsExpandNodeRef(ParserObject *object) +{ + ParserObject *refNode = HcsLookupAstObject(object, object->configNode.refNodePath); + if (refNode == NULL) { + HCS_OBJECT_ERROR(object, "ref node '%s' not exist", object->configNode.refNodePath); + return EINVALARG; + } + if (refNode->objectBase.status != PARSER_OBJ_IDLE) { + HCS_OBJECT_ERROR(object, "circular reference '%s'", object->configNode.refNodePath); + return EINVALARG; + } + + /* expand target ref or copy */ + int32_t res = HcsNodeExpand(refNode); + if (res) { + return res; + } + ParserObject *child = (ParserObject *)object->objectBase.child; + if (child == NULL) { + return 0; + } + + res = HcsAstCopySubTree(object, refNode, AST_COPY_SRC_OVER_DST); + if (res) { + return res; + } + HcsDeleteParserObjectTree(object); + return NOERR; +} + +static int32_t HcsExpandNodeCopy(ParserObject *object) +{ + object->configNode.nodeType = CONFIG_NODE_NOREF; + ParserObject *copyNode = HcsLookupAstObject(object, object->configNode.refNodePath); + if (copyNode == NULL) { + HCS_OBJECT_ERROR(object, "node %s copy node '%s' not exist", object->objectBase.name, + object->configNode.refNodePath); + return EINVALARG; + } + + /* check copy parent */ + ParserObjectBase *parent = object->objectBase.parent; + while (parent != NULL) { + if (parent == ©Node->objectBase) { + HCS_OBJECT_ERROR(object, "Never copy parent node which will make a loop reference"); + return EINVALARG; + } + parent = parent->parent; + } + + if (HcsOptShouldGenTextConfig()) { + ParserObjectBase *copyChild = copyNode->objectBase.child; + while (copyChild != NULL) { + if (copyChild->type == PARSEROP_CONFNODE) { + HCS_OBJECT_ERROR(object, "Not allow copy node has child node when output text config, at %s:%d", + copyChild->src, copyChild->lineno); + return EINVALARG; + } + copyChild = copyChild->next; + } + } + + return HcsAstCopySubTree(copyNode, object, AST_COPY_DST_OVER_SRC); +} + +static bool HcsProcessDelete(ParserObject *current) +{ + switch (current->objectBase.type) { + case PARSEROP_CONFNODE: + if (current->configNode.nodeType == CONFIG_NODE_DELETE) { + HcsDeleteParserObjectTree(current); + return true; + } + break; + case PARSEROP_CONFTERM: + if (current->objectBase.child->type == PARSEROP_DELETE) { + HcsDeleteParserObjectTree(current); + return true; + } + break; + default: + break; + } + + return false; +} + +static int32_t HcsNodeRefAssembling(ParserObject *current) +{ + ParserObject *refNode = + HcsLookupAstObject((ParserObject *)current->objectBase.parent, current->objectBase.stringValue); + if (refNode == NULL) { + HCS_OBJECT_ERROR(current, "reference invalid node %s", current->objectBase.stringValue); + return EINVALARG; + } + if (refNode->objectBase.type != PARSEROP_CONFNODE) { + HCS_OBJECT_ERROR(current, "reference node %s is not node", current->objectBase.stringValue); + return EINVALARG; + } + if (refNode->configNode.nodeType == CONFIG_NODE_REF) { + HCS_OBJECT_ERROR(current, "reference node %s referenced another", current->objectBase.stringValue); + return EINVALARG; + } + HcsMemFree(current->objectBase.stringValue); + current->objectBase.value = (uint64_t)refNode; + return NOERR; +} + +static int32_t HcsInheritNodeCompareWithBase(const ParserObject *obj, const ParserObject *base) +{ + ParserObjectBase *objChild = obj->objectBase.child; + + while (objChild != NULL) { + ParserObject *objInBase = NULL; + if (objChild->type == PARSEROP_CONFNODE && + ((ParserObject *)objChild)->configNode.nodeType == CONFIG_NODE_INHERIT) { + ParserObject *templateNode = + HcsLookupAstObject((ParserObject *)objChild, ((ParserObject *)objChild)->configNode.refNodePath); + if (templateNode == NULL) { + HCS_OBJECT_ERROR(objChild, "node '%s' inherit invalid template", objChild->name); + return EFAIL; + } + ParserObject *peerTemplate = HcsLookupAstObject((ParserObject *)objChild, templateNode->objectBase.name); + if (templateNode != peerTemplate) { + HCS_OBJECT_ERROR(objChild, "term '%s' not in base node", objChild->name); + return EFAIL; + } + objChild = objChild->next; + continue; + } else { + objInBase = HcsAstLookupObjectInChildren(base, objChild->name); + } + + if (objInBase == NULL) { + HCS_OBJECT_ERROR(objChild, "term '%s' not in base node", objChild->name); + return EFAIL; + } + if (objChild->type == PARSEROP_CONFNODE) { + return HcsInheritNodeCompareWithBase((ParserObject *)objChild, objInBase); + } + + objChild = objChild->next; + } + return NOERR; +} + +static int32_t HcsAddInstanceToTemplate(ParserObject *instanceNode, ParserObject *template) +{ + TemplateNodeInstance *instance = HcsMemZalloc(sizeof(TemplateNodeInstance)); + if (instance == NULL) { + return EOOM; + } + + instance->nodeObject = (struct ConfigNode *)instanceNode; + + TemplateNodeInstance *listEnd = template->configNode.subClasses; + if (listEnd == NULL) { + template->configNode.subClasses = instance; + } else { + while (listEnd->next != NULL) { + listEnd = listEnd->next; + } + + listEnd->next = instance; + } + instanceNode->configNode.inheritIndex = template->configNode.inheritCount++; + return NOERR; +} + +static int32_t HcsNodeInheritExpand(ParserObject *obj) +{ + ParserObject *base = HcsLookupAstObject(obj, obj->configNode.refNodePath); + if (base == NULL || base->objectBase.type != PARSEROP_CONFNODE || + base->configNode.nodeType != CONFIG_NODE_TEMPLATE) { + HCS_OBJECT_ERROR(obj, "inherit invalid node : %s", obj->configNode.refNodePath); + return EFAIL; + } + + obj->configNode.inheritNode = (struct ConfigNode *)base; + int32_t ret = HcsAstCopySubTree(base, obj, AST_COPY_DST_OVER_SRC); + if (ret) { + return ret; + } + + ret = HcsInheritNodeCompareWithBase(obj, base); + if (ret) { + return ret; + } + + return HcsAddInstanceToTemplate(obj, base); +} + +static int32_t HcsNodeExpand(ParserObject *current) +{ + if (HcsProcessDelete(current)) { + return NOERR; + } + + switch (current->objectBase.type) { + case PARSEROP_CONFNODE: { + current->objectBase.status = PARSER_OBJ_PROCESSING; + int32_t ret = NOERR; + if (current->configNode.nodeType == CONFIG_NODE_REF) { + return HcsExpandNodeRef(current); + } else if (current->configNode.nodeType == CONFIG_NODE_COPY) { + ret = HcsExpandNodeCopy(current); + } + current->objectBase.status = PARSER_OBJ_IDLE; + return ret; + } + case PARSEROP_NODEREF: + return HcsNodeRefAssembling(current); + default: + break; + } + + return NOERR; +} + +static int32_t HcsRedefineCheck(const ParserObject *object) +{ + if (object->objectBase.child == NULL) { + return NOERR; + } + + ParserObject *child = (ParserObject *)object->objectBase.child; + while (child != NULL) { + if (HcsIsAnonymousObject(object)) { + child = (ParserObject *)child->objectBase.next; + continue; + } + ParserObject *next = (ParserObject *)child->objectBase.next; + while (next != NULL) { + if (!HcsIsAnonymousObject(next) && !strcmp(child->objectBase.name, next->objectBase.name) && + (child->objectBase.src == next->objectBase.src)) { + HCS_OBJECT_ERROR(next, "'%s' redefined, first define at Line: %u", next->objectBase.name, + child->objectBase.lineno); + return EINVALARG; + } + next = (ParserObject *)next->objectBase.next; + } + child = (ParserObject *)child->objectBase.next; + } + + return NOERR; +} + +static int32_t HcsMiddleRedefineCheckCallback(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + return HcsRedefineCheck(current); +} + +static int32_t HcsMiddleInheritExpandCallback(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + if (current->objectBase.type == PARSEROP_CONFNODE && current->configNode.nodeType == CONFIG_NODE_INHERIT) { + return HcsNodeInheritExpand(current); + } + + return NOERR; +} + +static int32_t HcsMiddleProcessCallback(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + return HcsNodeExpand(current); +} + +static bool HcsApplyDelete(ParserObject *dst, ParserObject *src) +{ + if ((dst->objectBase.type == PARSEROP_CONFNODE && dst->configNode.nodeType == CONFIG_NODE_DELETE) || + (dst->objectBase.type == PARSEROP_CONFTERM && dst->objectBase.child->type == PARSEROP_DELETE)) { + HCS_OBJECT_WARNING(dst, "target object of delete not in base"); + } + + if ((src->objectBase.type == PARSEROP_CONFNODE && src->configNode.nodeType == CONFIG_NODE_DELETE) || + (src->objectBase.type == PARSEROP_CONFTERM && src->objectBase.child->type == PARSEROP_DELETE)) { + HcsDeleteParserObjectTree(dst); + HcsDeleteParserObjectTree(src); + return true; + } + + return false; +} + +static int32_t HcsMergeTree(ParserObject *dst, ParserObject *src) +{ + if (strcmp(src->objectBase.name, dst->objectBase.name) != 0) { + HCS_OBJECT_ERROR(src, "merge different node to %s:%d", dst->objectBase.src, dst->objectBase.lineno); + return EINVALARG; + } + + if (src->objectBase.type != dst->objectBase.type) { + HCS_OBJECT_ERROR(src, "conflict type with %s:%d", dst->objectBase.src, dst->objectBase.lineno); + return EINVALARG; + } + + if (HcsApplyDelete(dst, src)) { + return NOERR; + } + + /* overwrite source info */ + dst->objectBase.src = src->objectBase.src; + dst->objectBase.lineno = src->objectBase.lineno; + + /* overwrite value of base type */ + if (HcsIsStringObject(src)) { + HcsMemFree((void *)dst->objectBase.value); + dst->objectBase.value = src->objectBase.value; + src->objectBase.value = (uint64_t)NULL; + } else if (HcsIsNumberObject(src)) { + dst->objectBase.value = src->objectBase.value; + } + + /* process sub-tree objects */ + ParserObject *childSrc = (ParserObject *)src->objectBase.child; + int32_t ret = NOERR; + while (childSrc != NULL) { + ParserObject *childSrcNext = (ParserObject *)childSrc->objectBase.next; + ParserObject *childDst = HcsAstLookupObjectInChildren(dst, childSrc->objectBase.name); + if (childDst != NULL && childSrc->objectBase.type != childDst->objectBase.type) { + HCS_OBJECT_ERROR(childSrc, "overwrite with different type at %s:%d", childDst->objectBase.src, + childDst->objectBase.lineno); + return EINVALARG; + } + if (childDst == NULL) { + HcsAstRemoveChildLink(childSrc->objectBase.parent, (ParserObjectBase *)childSrc); + HcsAstAddChild(dst, childSrc); + } else if (childDst->objectBase.type == PARSEROP_ARRAY) { + ret = HcsAstCopyArray(childSrc, childDst); + break; + } else { + ret = HcsMergeTree(childDst, childSrc); + if (ret) { + break; + } + } + childSrc = childSrcNext; + } + + return ret; +} + +static void HcsOrderForest(ParserObject *root) +{ + if (root->objectBase.child == NULL) { + return; + } + + ParserObjectBase *childStart = root->objectBase.child; + ParserObjectBase *pre = childStart; + ParserObjectBase *next = childStart->next; + while (next != NULL) { + ParserObjectBase *tmp = next->next; + next->next = pre; + pre = next; + next = tmp; + } + + childStart->next = NULL; + root->objectBase.child = pre; +} + +static int32_t HcsMiddleMerge(ParserObject **mergedRoot) +{ + ParserObject *root = HcsGetParserRoot(); + HcsOrderForest(root); + + ParserObject *peer = (ParserObject *)root->objectBase.child; + while (peer->objectBase.next != NULL) { + ParserObject *next = (ParserObject *)peer->objectBase.next; + int32_t res = HcsMergeTree(peer, next); + if (res) { + return res; + } + HcsDeleteParserObjectTree(next); + } + HcsAstRemoveChildLink(peer->objectBase.parent, &peer->objectBase); + HcsSetParserRoot(peer); + *mergedRoot = peer; + return NOERR; +} + +int32_t HcsDoOptimize() +{ + ParserObject *root = HcsGetParserRoot(); + if (root == NULL) { + HCS_ERROR("parser return empty ast"); + return EINVALARG; + } + + /* redefine check */ + int32_t ret = HcsWalkAst(root, AST_WALK_BACKEND, NULL, HcsMiddleRedefineCheckCallback); + if (ret) { + return ret; + } + + /* merge multi file objects */ + ret = HcsMiddleMerge(&root); + if (ret) { + return ret; + } + + const char *moduleName = HcsGetModuleName(); + if (moduleName == NULL) { + return EINVALARG; + } + HCS_INFO("compile module : %s", moduleName); + /* expend node ref and node copy */ + ret = HcsWalkAst(root, AST_WALK_BACKEND, NULL, HcsMiddleProcessCallback); + if (ret) { + return ret; + } + + ret = HcsWalkAst(root, AST_WALK_FORWARD, HcsMiddleInheritExpandCallback, NULL); + if (ret) { + return ret; + } + + if (HcsVerbosePrint()) { + HcsDumpAst("Optimized"); + } + return ret; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_opcode.c b/tools/hc-gen/src/hcs_opcode.c new file mode 100755 index 00000000..64214236 --- /dev/null +++ b/tools/hc-gen/src/hcs_opcode.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "hcs_opcode.h" + + +OpCodeMapEntry g_byteCodeMap[PARSEROP_COUNT] = { + [PARSEROP_UINT8] = {HCS_BYTE_OP, BYTE_SIZE, "Uint8"}, + [PARSEROP_UINT16] = {HCS_WORD_OP, WORD_SIZE, "Uint16"}, + [PARSEROP_UINT32] = {HCS_DWORD_OP, DWORD_SIZE, "Uint32"}, + [PARSEROP_UINT64] = {HCS_QWORD_OP, QWORD_SIZE, "Uint64"}, + [PARSEROP_STRING] = {HCS_STRING_OP, 0, "String"}, + [PARSEROP_ARRAY] = {HCS_ARRAY_OP, WORD_SIZE, "Array"}, /* ElementCount - WORD */ + [PARSEROP_CONFNODE] = {HCS_NODE_OP, DWORD_SIZE, "ConfigNode"}, /* SubSize - DWORD */ + [PARSEROP_CONFTERM] = {HCS_TERM_OP, 0, "ConfigTerm"}, + [PARSEROP_NODEREF] = {HCS_NODEREF_OP, DWORD_SIZE, "NodeRef"}, /* RefHashCode - DWORD */ +}; + +const OpCodeMapEntry *HcsGetOpCodeMap() +{ + return g_byteCodeMap; +} + +const OpCodeMapEntry *HcsParserObjectTypeToByteCode(uint32_t objectType) +{ + if (objectType >= PARSEROP_COUNT) { + return NULL; + } + return &g_byteCodeMap[objectType]; +} + +const char *HcsOpcodeToStr(uint16_t objectType) +{ + if (objectType >= PARSEROP_COUNT) { + return "illegal OpCode, out of range"; + } + + return g_byteCodeMap[objectType].opStr; +} + +void HcsCalculateOpcodeSize(ParserObject *object) +{ + const OpCodeMapEntry *byteCodeMap = HcsGetOpCodeMap(); + uint32_t size = HcsAlign(OPCODE_BYTE_WIDTH) + HcsAlign(byteCodeMap[object->objectBase.type].size); + switch (object->objectBase.opCode) { + case HCS_NODE_OP: /* fall-through */ + case HCS_TERM_OP: + /* name string */ + size += HcsAlign(strlen(object->objectBase.name) + 1); // add 1 for '\0' + break; + case HCS_STRING_OP: + size += HcsAlign(strlen(object->objectBase.stringValue) + 1); + break; + default: + break; + } + + ParserObjectBase *child = object->objectBase.child; + uint32_t subSize = 0; + while (child != NULL) { + subSize += child->size; + child = child->next; + } + + object->objectBase.size += subSize + size; + object->objectBase.subSize = subSize; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_option.c b/tools/hc-gen/src/hcs_option.c new file mode 100755 index 00000000..6e2e9e41 --- /dev/null +++ b/tools/hc-gen/src/hcs_option.c @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "hcs_file.h" +#include "hcs_compiler.h" +#include "hcs_log.h" + +#define ARG_COUNT_MIN 2 +#define USAGE(option, info) HCS_PRINT(" %-12s%s\n", option, info) + +bool g_genTextConfigOutput = false; +bool g_genByteCodeConfigOutput = true; +bool g_genByteCodeHexdump = false; +bool g_verbosePrint = false; +bool g_decompile = false; +bool g_shouldAlign = false; +const char *g_symbolPrefix = NULL; + +bool HcsOptShouldAlign() +{ + return g_shouldAlign; +} + +void HcsOptSetAlign(bool align) +{ + g_shouldAlign = align; +} + + +bool HcsOptShouldGenTextConfig() +{ + return g_genTextConfigOutput; +} +bool HcsOptShouldGenByteCodeConfig() +{ + return g_genByteCodeConfigOutput; +} +bool HcsOptDecompile() +{ + return g_decompile; +} + +const char *HcsOptGetSymbolNamePrefix() +{ + return g_symbolPrefix; +} + +bool HcsOptShouldGenHexdump() +{ + return g_genByteCodeHexdump; +} + +void ShowUsage() +{ + HCS_PRINT("Usage: hc-gen [Options] [File]\n"); + HCS_PRINT("options:\n"); + USAGE("-o ", "output file name, default same as input"); + USAGE("-a", "hcb align with four bytes"); + USAGE("-b", "output binary output, default enable"); + USAGE("-t", "output config in C language source file style"); + USAGE("-i", "output binary hex dump in C language source file style"); + USAGE("-p ", "prefix of generated symbol name"); + USAGE("-d", "decompile hcb to hcs"); + USAGE("-V", "show verbose info"); + USAGE("-v", "show version"); + USAGE("-h", "show this help message"); +} + +#define HCS_SUPPORT_ARGS "o:ap:bditvVh" + +void ShowVersionInfo() +{ + HCS_PRINT("Hcs compiler v%u.%u\n", HCS_COMPILER_VERSION_MAJOR, HCS_COMPILER_VERSION_MINOR); + HCS_PRINT("Copyright (c) Huawei Technologies Co., Ltd. 2020\n"); +} + +static int32_t ProcessOption(int32_t argc, char *argv[]) +{ + int32_t op = 0; + while (op != HCS_OPTION_END) { + op = getopt(argc, argv, HCS_SUPPORT_ARGS); + switch (op) { + case 'o': + if (HcsSetOutPutName(optarg)) { + return EOPTION; + } + break; + case 'a': + g_shouldAlign = true; + break; + case 'b': + g_genByteCodeConfigOutput = true; + break; + case 't': + g_genTextConfigOutput = true; + g_genByteCodeConfigOutput = false; + break; + case 'p': + g_symbolPrefix = optarg; + break; + case 'i': + g_genByteCodeHexdump = true; + break; + case 'V': + g_verbosePrint = true; + break; + case 'd': + g_decompile = true; + break; + case 'v': + ShowVersionInfo(); + return EFAIL; + case 'h': /* fall-through */ + case '?': + ShowUsage(); + return EOPTION; + default: + break; + } + } + + return NOERR; +} + +int32_t DoOption(int32_t argc, char *argv[]) +{ + if (argc < ARG_COUNT_MIN) { + ShowUsage(); + return EOPTION; + } + + int32_t ret = ProcessOption(argc, argv); + if (ret) { + return ret; + } + + if (optind >= argc) { + HCS_ERROR("Miss input file name"); + return EOPTION; + } else { + const char *inputFIlePath = argv[optind]; + HCS_DEBUG("opt info:input file name:%s\n", inputFIlePath); + HcsSetInputFileName(inputFIlePath); + } + return 0; +} + +bool HcsVerbosePrint() +{ + return g_verbosePrint; +} \ No newline at end of file diff --git a/tools/hc-gen/src/hcs_parser.c b/tools/hc-gen/src/hcs_parser.c new file mode 100755 index 00000000..39a9633a --- /dev/null +++ b/tools/hc-gen/src/hcs_parser.c @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "hcs_file.h" +#include "hcs_compiler.h" +#include "hcs_gener.h" +#include "hcs_ast.h" +#include "hcs_option.h" + +const char *g_nodeTypeStringMap[CONFIG_NODE_TYPE_COUNT] = { + [CONFIG_NODE_NOREF] = "NodeReference", + [CONFIG_NODE_COPY] = "NodeCopy", + [CONFIG_NODE_REF] = "NodeReference", + [CONFIG_NODE_DELETE] = "NodeDelete", + [CONFIG_NODE_INHERIT] = "NodeInherit", + [CONFIG_NODE_TEMPLATE] = "NodeTemplate", +}; + +uint32_t HcsAlign(uint32_t size) +{ + if (HcsOptShouldAlign()) { + return (size + ALIGN_SIZE - 1) & (~(ALIGN_SIZE - 1)); + } else { + return size; + } +} + +const char *HcsParserNodeTypeToStr(uint32_t nodeType) +{ + if (nodeType >= CONFIG_NODE_TYPE_COUNT) { + return ""; + } + + return g_nodeTypeStringMap[nodeType]; +} + +bool HcsIsNumberObject(const ParserObject *obj) +{ + return obj->objectBase.type >= PARSEROP_UINT8 && obj->objectBase.type <= PARSEROP_UINT64; +} + +bool HcsIsStringObject(const ParserObject *obj) +{ + return obj->objectBase.type == PARSEROP_STRING; +} + +bool HcsIsSameTypeObject(const ParserObject *cs, const ParserObject *ct) +{ + if (HcsIsNumberObject(cs)) { + return HcsIsNumberObject(ct); + } else if (cs->objectBase.type == PARSEROP_CONFTERM || cs->objectBase.type == PARSEROP_ARRAY) { + return ct->objectBase.type == cs->objectBase.type && cs->objectBase.child->type == ct->objectBase.child->type; + } else { + return ct->objectBase.type == cs->objectBase.type; + } +} + +void HcsSetCompilerIn(FILE *in); + +static void InitParser(const struct HcsFile *sourceFile) +{ + HcsSetCompilerIn(sourceFile->file); + HcsParserRestart(sourceFile->file); + HcsSetCurrentSourceLine(1); +} + +void ParserCleanUp() +{ + ParserObject *astRoot = HcsGetParserRoot(); + HcsDeleteParserObjectTree(astRoot); + HcsSourceNameSetClean(); +} + +int32_t HcsProcessInclude(char *includePath, uint32_t lineNumber) +{ + if (includePath[0] == '/' || !strstr(includePath, HCS_SOURCE_FILE_SUFFIX)) { + HCS_ERROR("File:%s Line:%u\n\tinclude file %s is invalid", HcsGetCurrentSourceName(), lineNumber, includePath); + return EFAIL; + } + + struct HcsFile *currentSource = HcsSourceQueueTop(); + /* assembly include path to current source file */ + uint32_t pathSize = strlen(currentSource->fullPath) + strlen(includePath) + 1; + char *path = HcsMemZalloc(pathSize); + if (path == NULL) { + HCS_ERROR("oom"); + return EOOM; + } + + if (HcsFileCopyDir(path, pathSize, currentSource->fullPath) != true) { + HcsMemFree(path); + return EFAIL; + } + + int32_t res = strcat_s(path, pathSize, includePath); + if (res != EOK) { + HcsMemFree(path); + HCS_ERROR("%s:string cat fail", __func__); + return EFAIL; + } + HcsMemFree(includePath); + + struct HcsFile *source = NULL; + uint32_t ret = HcsOpenSourceFile(path, &source, NULL); + if (ret == EREOPENF) { + HcsMemFree(path); + return NOERR; + } + + if (ret) { + HCS_ERROR("File:%s Line:%u\n\tinclude file %s is invalid", HcsGetCurrentSourceName(), lineNumber, path); + HcsMemFree(path); + return EINVALF; + } + + HcsSourceQueuePush(source); + HcsMemFree(path); + return NOERR; +} + +int32_t HcsDoCompile() +{ + struct HcsFile *source = NULL; + char *forestName = strdup("ForestRoot"); + if (forestName == NULL) { + return EOOM; + } + ParserObject *astForest = HcsNewParserObject(forestName, PARSEROP_CONFNODE, 0); + if (astForest == NULL) { + HcsMemFree(forestName); + return EFAIL; + } + + uint32_t ret = HcsOpenSourceFile(HcsGetInputFileName(), &source, NULL); + if (ret) { + HCS_ERROR("Invalid source file: %s", HcsGetInputFileName()); + HcsAstFreeObject(astForest); + return ret; + } + HcsSourceQueuePush(source); + + /* parse specified source file and included files */ + while (HcsSourceQueueSize()) { + source = HcsSourceQueueTop(); + HCS_DEBUG("parsing file : %s%s", source->fullPath, source->name); + InitParser(source); + + /* do parse */ + ret = HcsCompilerparse(); + ParserObject *currentRoot = HcsGetParserRoot(); + /* pop current file, parse next file which maybe imported by include */ + HcsSourceQueuePop(); + HcsCloseFile(source); + if (ret) { + goto OUT; + } + + HcsAstAddChild(astForest, currentRoot); + HcsSetParserRoot(NULL); + } + HcsSetParserRoot(astForest); + + if (HcsVerbosePrint()) { + HcsDumpAst("Origin"); + } + + /* middle process */ + ret = HcsDoOptimize(); + if (ret) { + goto OUT; + } + + /* output */ + if (HcsOptShouldGenTextConfig()) { + ret = HcsTextCodeOutput(); + } else if (HcsOptShouldGenByteCodeConfig()) { + ret = HcsBytecodeOutput(); + } +OUT: + ParserCleanUp(); + if (HcsGetParserRoot() != astForest) { + HcsDeleteParserObjectTree(astForest); + } + return ret; +} diff --git a/tools/hc-gen/src/hcs_text_gen.c b/tools/hc-gen/src/hcs_text_gen.c new file mode 100755 index 00000000..70ae4b97 --- /dev/null +++ b/tools/hc-gen/src/hcs_text_gen.c @@ -0,0 +1,1302 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include "hcs_ast.h" +#include "hcs_file.h" +#include "hcs_log.h" +#include "hcs_mem.h" +#include "hcs_option.h" +#include "hcs_parser.h" + +#define TAB_SIZE 4 +#define WRITE_BUFFER_LEN 256 +#define INCLUDE_PATH_MAX_LEN 128 +#define VARIABLE_NAME_LEN 128 +#define GEN_CODE_MARGIN_SIZE 100 +#define GEN_ARRAY_SEP_SIZE 2 +#define HCS_CONFIG_FILE_HEADER "/*\n" \ + " * It's HDF config auto-gen file, do not modify it manually\n" \ + " */\n\n" + +#define HCS_CONFIG_INCLUDE_HEADER "#include \n\n" + +#define DEFAULT_PREFIX "HdfConfig" + +#define HCS_CONFIG_INCLUDE_FUNC_DECLARATION "const struct %s%sRoot* HdfGet%sModuleConfigRoot(void);\n\n" + +#define HCS_CONFIG_FUNC_IMPLEMENT "\nconst struct %s%sRoot* HdfGet%sModuleConfigRoot(void)\n" \ + "{\n" \ + " return &%s;\n" \ + "}\n" + +static char *g_configRootVariableName = NULL; +static char *g_bigHumpModuleName = NULL; +static const char *g_namePrefix = DEFAULT_PREFIX; +static char *g_littleHumpNamePrefix = NULL; + +static void ToCamelString(char *str, uint32_t strLen) +{ + if (!strLen) { + return; + } + + if (strchr(str, '_') == NULL) { + return; + } + + char *ptr = str; + char *processed = str; + uint32_t count = 0; + while (*ptr && count <= strLen) { + if (*ptr != '_') { + *processed++ = *ptr++; + } else { + ptr++; + *ptr = (char)toupper(*ptr); + } + count++; + } + *processed = '\0'; +} + +static void ToUpperCamelString(char *str, uint32_t strLen) +{ + if (!strLen) { + return; + } + + ToCamelString(str, strLen); + str[0] = (char)toupper(str[0]); +} + +static void ToLowerCamelString(char *str, uint32_t strLen) +{ + if (!strLen) { + return; + } + + ToCamelString(str, strLen); + str[0] = (char)tolower(str[0]); +} + +static int32_t InitConfigVariableNames() +{ + if (g_bigHumpModuleName == NULL) { + const char *moduleName = HcsGetModuleName(); + g_bigHumpModuleName = HcsMemZalloc(strlen(moduleName) + 1); + if (g_bigHumpModuleName == NULL) { + return EOOM; + } + if (strcpy_s(g_bigHumpModuleName, strlen(moduleName) + 1, moduleName) != EOK) { + HCS_ERROR("string copy fail"); + return EFAIL; + } + ToUpperCamelString(g_bigHumpModuleName, strlen(g_bigHumpModuleName)); + } + if (g_littleHumpNamePrefix == NULL) { + char *littleHumpPrefix = strdup(g_namePrefix); + if (littleHumpPrefix == NULL) { + return EOOM; + } + ToLowerCamelString(littleHumpPrefix, strlen(littleHumpPrefix)); + g_littleHumpNamePrefix = littleHumpPrefix; + } + if (g_configRootVariableName == NULL) { + const uint32_t nameLen = VARIABLE_NAME_LEN; + g_configRootVariableName = HcsMemZalloc(nameLen); + if (g_configRootVariableName == NULL) { + return EOOM; + } + + int32_t ret = sprintf_s(g_configRootVariableName, nameLen, "g_%s%sModuleRoot", g_littleHumpNamePrefix, + g_bigHumpModuleName); + if (ret <= 0) { + return EFAIL; + } + } + + return NOERR; +} + +static void ReleaseConfigVariableNames() +{ + if (g_configRootVariableName != NULL) { + HcsMemFree(g_configRootVariableName); + g_configRootVariableName = NULL; + } + + if (g_bigHumpModuleName != NULL) { + HcsMemFree(g_bigHumpModuleName); + g_bigHumpModuleName = NULL; + } + + if (g_littleHumpNamePrefix != NULL) { + HcsMemFree(g_littleHumpNamePrefix); + g_littleHumpNamePrefix = NULL; + } +} + +static const char *GetConfigRootVariableName() +{ + return g_configRootVariableName; +} + +typedef struct HcsSymbol { + char *name; + const ParserObject *object; + uint32_t duplicateCount; + struct HcsSymbol *left; + struct HcsSymbol *right; + struct HcsSymbol *parent; +} HcsSymbol; + +typedef struct HcsSymbolTable { + HcsSymbol *symbols; + uint32_t size; +} HcsSymbolTable; + +static HcsSymbolTable *g_hcsSymbolTable = NULL; +static int32_t HcsImplementGenWalkCallBack(ParserObject *current, int32_t walkDepth); +static int32_t HcsImplementCloseBraceGen(ParserObject *current, int32_t walkDepth); + +static bool HcsIsInSubClassNode(const ParserObject *object) +{ + while (object != NULL) { + if (object->configNode.nodeType == CONFIG_NODE_INHERIT) { + return true; + } + object = (ParserObject *)object->objectBase.parent; + } + return false; +} + +static bool HcsIsInTemplateNode(const ParserObject *object) +{ + while (object != NULL) { + if (object->configNode.nodeType == CONFIG_NODE_TEMPLATE) { + return true; + } + object = (ParserObject *)object->objectBase.parent; + } + return false; +} + +static void HcsReleaseSymbol(struct HcsSymbol *s) +{ + if (s == NULL) { + return; + } + if (s->left != NULL) { + HcsReleaseSymbol(s->left); + s->left = NULL; + } + if (s->right != NULL) { + HcsReleaseSymbol(s->right); + s->right = NULL; + } + HcsMemFree(s->name); + HcsMemFree(s); +} + +static void HcsSymbolTableRelease() +{ + HcsReleaseSymbol(g_hcsSymbolTable->symbols); + HcsMemFree(g_hcsSymbolTable); + g_hcsSymbolTable = NULL; +} + +static HcsSymbol *HcsNewSymbol(const char *name, const ParserObject *object) +{ + HcsSymbol *newSymbol = HcsMemZalloc(sizeof(HcsSymbol)); + if (newSymbol == NULL) { + HCS_ERROR("oom"); + return NULL; + } + char *symbolName = strdup(name); + if (symbolName == NULL) { + HcsMemFree(newSymbol); + return NULL; + } + newSymbol->name = symbolName; + newSymbol->object = object; + newSymbol->duplicateCount = 1; + + return newSymbol; +} +static int32_t HcsSymbolTableInit() +{ + if (g_hcsSymbolTable != NULL) { + HcsSymbolTableRelease(); + } + + g_hcsSymbolTable = HcsMemZalloc(sizeof(HcsSymbolTable)); + return (g_hcsSymbolTable != NULL) ? NOERR : EOOM; +} + +static int32_t HcsSymbolTableReset() +{ + HcsSymbolTableRelease(); + return HcsSymbolTableInit(); +} + +int32_t HcsSymbolTableAdd(const char *name, const ParserObject *object) +{ + HcsSymbol *symbolRoot = g_hcsSymbolTable->symbols; + HcsSymbol *newSymbol = HcsNewSymbol(name, object); + if (newSymbol == NULL) { + return EOOM; + } + int32_t cmpRes; + HcsSymbol *insert = NULL; + HcsSymbol *p = symbolRoot; + while (p != NULL) { + insert = p; + cmpRes = strcasecmp(name, p->name); + if (!cmpRes) { + HCS_OBJECT_ERROR(object, + "duplicate node name at %s:%u\n To avoid redefining structures," + " not allow duplicate node name at text config mode", + p->object->objectBase.src, p->object->objectBase.lineno); + HcsReleaseSymbol(newSymbol); + return EINVALARG; + } + p = cmpRes < 0 ? p->left : p->right; + } + + if (insert == NULL) { + g_hcsSymbolTable->symbols = newSymbol; + } else if (cmpRes < 0) { + insert->left = newSymbol; + } else { + insert->right = newSymbol; + } + + g_hcsSymbolTable->size++; + + return NOERR; +} + +HcsSymbol *HcsSymbolTableFind(const char *name) +{ + HcsSymbol *p = g_hcsSymbolTable->symbols; + while (p != NULL) { + int32_t cmpRes = strcasecmp(name, p->name); + if (cmpRes == 0) { + return p; + } + p = cmpRes < 0 ? p->left : p->right; + } + + return NULL; +} + +const char *g_typeMap[PARSEROP_COUNT] = { + [PARSEROP_UINT8] = "uint8_t", + [PARSEROP_UINT16] = "uint16_t", + [PARSEROP_UINT32] = "uint32_t", + [PARSEROP_UINT64] = "uint64_t", + [PARSEROP_STRING] = "const char*", +}; + +static int32_t GenConfigStructName(const ParserObject *node, char *name, uint32_t nameBuffLen) +{ + char nameBuffer[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = strcpy_s(nameBuffer, OBJECT_NAME_MAX_LEN, HcsGetModuleName()); + PRINTF_CHECK_AND_RETURN(res); + ToUpperCamelString(nameBuffer, strlen(nameBuffer)); + res = sprintf_s(name, nameBuffLen, "%s%s", g_namePrefix, nameBuffer); + PRINTF_CHECK_AND_RETURN(res); + + res = strcpy_s(nameBuffer, OBJECT_NAME_MAX_LEN, node->configNode.name); + PRINTF_CHECK_AND_RETURN(res); + ToUpperCamelString(nameBuffer, strlen(nameBuffer)); + res = sprintf_s(name + strlen(name), nameBuffLen - strlen(name), "%s", nameBuffer); + PRINTF_CHECK_AND_RETURN(res); + + return NOERR; +} + +static int32_t GenConfigArrayName(ParserObject *array, char *name, uint32_t nameBuffLen) +{ + char buffer[OBJECT_NAME_MAX_LEN] = {'\0'}; + + if (strcpy_s(buffer, sizeof(buffer), array->objectBase.name) != EOK) { + HCS_ERROR("%s: string copy fail", __func__); + return EOUTPUT; + } + ToUpperCamelString(buffer, strlen(buffer)); + + int32_t ret = sprintf_s(name, nameBuffLen, "g_hcsConfigArray%s", buffer); + PRINTF_CHECK_AND_RETURN(ret); + + HcsSymbol *symbol = HcsSymbolTableFind(name); + if (symbol == NULL) { + if (HcsSymbolTableAdd(name, array)) { + return EFAIL; + } + array->configTerm.signNum = 1; + } else if (!array->configTerm.signNum) { + array->configTerm.signNum = symbol->duplicateCount + 1; + symbol->duplicateCount++; + } + + ret = sprintf_s(name + strlen(name), nameBuffLen - strlen(name), "%d", array->configTerm.signNum); + PRINTF_CHECK_AND_RETURN(ret); + return NOERR; +} + +static const char *GetArrayType(const ParserObject *array) +{ + uint32_t type = PARSEROP_UINT8; + ParserObject *element = (ParserObject *)array->objectBase.child; + while (element != NULL) { + type = element->objectBase.type > type ? element->objectBase.type : type; + element = (ParserObject *)element->objectBase.next; + } + + return g_typeMap[type]; +} + +static int32_t GetArraySize(const ParserObject *array) +{ + uint32_t size = 0; + ParserObjectBase *element = array->objectBase.child; + while (element != NULL) { + size++; + element = element->next; + } + return size; +} + +static int32_t HcsPrintTermDefinition(char *buffer, uint32_t bufferSize, const ParserObject *object) +{ + ParserObject *termContext = (ParserObject *)object->objectBase.child; + int32_t res; + switch (termContext->objectBase.type) { + case PARSEROP_ARRAY: + if (HcsIsInTemplateNode(object)) { + res = sprintf_s(buffer, bufferSize, "const %s *%s;\n", GetArrayType(termContext), + object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), "%*cuint32_t %sSize;\n", TAB_SIZE, + ' ', object->configTerm.name); + } else { + res = sprintf_s(buffer, bufferSize, "%s %s[%d];\n", GetArrayType(termContext), object->configTerm.name, + GetArraySize(termContext)); + } + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_UINT8: + case PARSEROP_UINT16: + case PARSEROP_UINT32: + case PARSEROP_UINT64: + case PARSEROP_STRING: + res = sprintf_s(buffer, bufferSize - strlen(buffer), "%s %s;\n", g_typeMap[termContext->objectBase.type], + object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_NODEREF: { + char refType[OBJECT_NAME_MAX_LEN] = {'\0'}; + res = GenConfigStructName((ParserObject *)termContext->objectBase.value, refType, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + res = sprintf_s(buffer, bufferSize - strlen(buffer), "const struct %s* %s;\n", refType, + object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + } break; + default: + break; + } + + return NOERR; +} + +static int32_t HcsObjectDefinitionGen(const ParserObject *current) +{ + if (current->objectBase.type != PARSEROP_CONFNODE && current->objectBase.type != PARSEROP_CONFTERM) { + return NOERR; + } + + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c", TAB_SIZE, ' '); + PRINTF_CHECK_AND_RETURN(res); + switch (current->objectBase.type) { + case PARSEROP_CONFNODE: { + char structName[OBJECT_NAME_MAX_LEN] = {'\0'}; + res = GenConfigStructName(current, structName, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + if (current->configNode.nodeType == CONFIG_NODE_TEMPLATE) { + char nodeName[OBJECT_NAME_MAX_LEN] = {0}; + if (strcpy_s(nodeName, sizeof(nodeName), current->configNode.name)) { + return EOUTPUT; + } + ToLowerCamelString(nodeName, strlen(nodeName)); + res = sprintf_s(writeBuffer + TAB_SIZE, WRITE_BUFFER_LEN - strlen(writeBuffer), + "const struct %s* %s;\n", structName, nodeName); + PRINTF_CHECK_AND_RETURN(res); + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), + "%*cuint16_t %sSize;\n", TAB_SIZE, ' ', nodeName); + } else if (current->configNode.nodeType == CONFIG_NODE_INHERIT) { + return NOERR; + } else { + res = sprintf_s(writeBuffer + TAB_SIZE, WRITE_BUFFER_LEN - strlen(writeBuffer), "struct %s %s;\n", + structName, current->configNode.name); + } + PRINTF_CHECK_AND_RETURN(res); + break; + } + case PARSEROP_CONFTERM: + HcsPrintTermDefinition(writeBuffer + TAB_SIZE, WRITE_BUFFER_LEN - strlen(writeBuffer), current); + break; + default: + break; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsDuplicateCheckWalkCallBack(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + if (current->objectBase.type != PARSEROP_CONFNODE || HcsIsInSubClassNode(current)) { + return NOERR; + } + + return HcsSymbolTableAdd(current->objectBase.name, current); +} + +static int32_t HcsGenNormalNodeDefinition(ParserObject *object, int32_t walkDepth) +{ + (void)walkDepth; + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char structName[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = GenConfigStructName(object, structName, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + if (HcsSymbolTableFind(structName)) { + return NOERR; + } else { + HcsSymbolTableAdd(structName, object); + } + + res = sprintf_s(writeBuffer, (WRITE_BUFFER_LEN - 1), "struct %s {\n", structName); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(writeBuffer, strlen(writeBuffer))) { + return EOUTPUT; + } + + ParserObject *terms = (ParserObject *)object->objectBase.child; + while (terms != NULL) { + res = HcsObjectDefinitionGen(terms); + if (res) { + return res; + } + terms = (ParserObject *)terms->objectBase.next; + } + + res = sprintf_s(writeBuffer, (WRITE_BUFFER_LEN - 1), "};\n\n"); + PRINTF_CHECK_AND_RETURN(res); + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsGenNodeTemplateDefinition(ParserObject *object, int32_t walkDepth) +{ + return HcsGenNormalNodeDefinition(object, walkDepth); +} + +static int32_t HcsDefinitionGenWalkCallBack(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + if (current->objectBase.type != PARSEROP_CONFNODE) { + return NOERR; + } + if (current->configNode.nodeType == CONFIG_NODE_TEMPLATE) { + return HcsGenNodeTemplateDefinition(current, walkDepth); + } else if (current->configNode.nodeType == CONFIG_NODE_INHERIT) { + return NOERR; + } else { + return HcsGenNormalNodeDefinition(current, walkDepth); + } +} + +static uint32_t HcsPrintTermValue(char *buffer, uint32_t buffSize, const ParserObject *object) +{ + int32_t res = 0; + switch (object->objectBase.type) { + case PARSEROP_UINT8: /* fallthrough */ + case PARSEROP_UINT16: /* fallthrough */ + case PARSEROP_UINT32: /* fallthrough */ + case PARSEROP_UINT64: + res = sprintf_s(buffer, buffSize, "0x%" PRIx64, object->objectBase.integerValue); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_STRING: + res = sprintf_s(buffer, buffSize, "\"%s\"", object->objectBase.stringValue); + PRINTF_CHECK_AND_RETURN(res); + break; + default: + break; + } + + return res; +} + +#define MAX_CONFIG_TREE_DEPTH 100 +static char *HcsBuildObjectPath(const ParserObject *refObject) +{ + const char *pathArray[MAX_CONFIG_TREE_DEPTH] = {0}; + int32_t count = 0; + size_t pathStringLen = strlen(GetConfigRootVariableName()) + 1; + const ParserObject *it = refObject; + + while (it != HcsGetParserRoot() && count < MAX_CONFIG_TREE_DEPTH) { + pathArray[count++] = it->objectBase.name; + pathStringLen += strlen(it->objectBase.name) + 1; + it = (ParserObject *)it->objectBase.parent; + } + if (count >= MAX_CONFIG_TREE_DEPTH) { + HCS_ERROR("reference a config node nested too deep over %u", MAX_CONFIG_TREE_DEPTH); + return NULL; + } + + char *path = HcsMemZalloc(pathStringLen); + if (path == NULL) { + HCS_ERROR("%s:oom", __func__); + return NULL; + } + + int32_t res = strcat_s(path, pathStringLen, GetConfigRootVariableName()); + if (res) { + HcsMemFree(path); + HCS_ERROR("%s:string cat fail", __func__); + return NULL; + } + + for (int32_t i = count - 1; i >= 0; --i) { + res = strcat_s(path, pathStringLen, "."); + if (res) { + HcsMemFree(path); + HCS_ERROR("%s:string cat fail", __func__); + return NULL; + } + res = strcat_s(path, pathStringLen, pathArray[i]); + if (res) { + HcsMemFree(path); + HCS_ERROR("%s:string cat fail", __func__); + return NULL; + } + } + + return path; +} + +static int32_t HcsPrintArrayImplInSubClass(char *buffer, uint32_t bufferSize, ParserObject *object, uint8_t tabSize) +{ + int32_t size = sprintf_s(buffer, bufferSize, "%*c.%s = ", tabSize, ' ', object->objectBase.name); + PRINTF_CHECK_AND_RETURN(size); + if (GenConfigArrayName(object, buffer + size, bufferSize - size)) { + return EOUTPUT; + } + size = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ",\n"); + PRINTF_CHECK_AND_RETURN(size); + size = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), "%*c.%sSize = %d,\n", tabSize, ' ', + object->configTerm.name, GetArraySize((ParserObject *)object->objectBase.child)); + PRINTF_CHECK_AND_RETURN(size); + return HcsOutputWrite(buffer, strlen(buffer)); +} + +static int32_t HcsPrintArrayContent(const ParserObject *object, int32_t tabSize) +{ + if (!GetArraySize(object)) { + return NOERR; + } + + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + ParserObject *element = (ParserObject *)object->objectBase.child; + uint32_t writeSize = 0; + while (element != NULL) { + int32_t size = HcsPrintTermValue(writeBuffer + writeSize, sizeof(writeBuffer) - writeSize, element); + writeBuffer[writeSize + size++] = ','; + writeBuffer[writeSize + size++] = ' '; + writeSize += size; + if (writeSize >= GEN_CODE_MARGIN_SIZE) { + writeSize -= 1; /* strip space at line end */ + size = sprintf_s(writeBuffer + writeSize, sizeof(writeBuffer) - writeSize, "\n%*c", tabSize, ' '); + PRINTF_CHECK_AND_RETURN(size); + writeSize += size; + if (HcsOutputWrite(writeBuffer, writeSize)) { + return EOUTPUT; + } + writeSize = 0; + } + element = (ParserObject *)element->configTerm.next; + } + + return writeSize ? HcsOutputWrite(writeBuffer, writeSize - GEN_ARRAY_SEP_SIZE) : NOERR; +} + +static int32_t HcsPrintArrayImplement(char *buffer, uint32_t bufferSize, ParserObject *object, uint8_t tabSize) +{ + if (HcsIsInSubClassNode(object)) { + return HcsPrintArrayImplInSubClass(buffer, bufferSize, object, tabSize); + } + + ParserObject *termContext = (ParserObject *)object->objectBase.child; + int32_t res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), "%*c.%s = { ", tabSize, ' ', + object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(buffer, strlen(buffer))) { + return EOUTPUT; + } + if (HcsPrintArrayContent(termContext, tabSize + TAB_SIZE)) { + HCS_ERROR("fail to write array content"); + return EOUTPUT; + } + res = sprintf_s(buffer, bufferSize, " },\n"); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(buffer, strlen(buffer))) { + return EOUTPUT; + } + return NOERR; +} + +static int32_t HcsPrintTermImplement(char *buffer, uint32_t bufferSize, ParserObject *object, int32_t tabSize) +{ + int32_t res; + sprintf_s(buffer, bufferSize, "%*c", tabSize, ' '); + ParserObject *termContext = (ParserObject *)object->objectBase.child; + switch (termContext->objectBase.type) { + case PARSEROP_UINT8: + /* fall-through */ + case PARSEROP_UINT16: + /* fall-through */ + case PARSEROP_UINT32: + /* fall-through */ + case PARSEROP_UINT64: + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ".%s = ", object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + if (!HcsPrintTermValue(buffer + strlen(buffer), bufferSize - strlen(buffer), termContext)) { + return EOUTPUT; + } + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ",\n"); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_STRING: + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ".%s = ", object->configTerm.name); + PRINTF_CHECK_AND_RETURN(res); + if (!HcsPrintTermValue(buffer + strlen(buffer), bufferSize - strlen(buffer), termContext)) { + return EOUTPUT; + } + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ",\n"); + PRINTF_CHECK_AND_RETURN(res); + break; + case PARSEROP_ARRAY: + if (HcsPrintArrayImplement(buffer + strlen(buffer), bufferSize - strlen(buffer), object, tabSize)) { + return EOUTPUT; + } + buffer[0] = '\0'; + break; + case PARSEROP_NODEREF: { + char *refPath = HcsBuildObjectPath((ParserObject *)object->objectBase.child->value); + if (refPath == NULL) { + return EOUTPUT; + } + res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ".%s = &%s,\n", + object->configTerm.name, refPath); + HcsMemFree(refPath); + PRINTF_CHECK_AND_RETURN(res); + break; + } + default: + break; + } + + return NOERR; +} + +static int32_t HcsGenTemplateVariableName(ParserObject *object, char *nameBuff, uint32_t nameBufferSize) +{ + char tempName[OBJECT_NAME_MAX_LEN] = {'\0'}; + if (strcpy_s(tempName, sizeof(tempName), object->objectBase.name)) { + HCS_ERROR("s: string copy fail"); + return EOUTPUT; + } + ToUpperCamelString(tempName, sizeof(tempName)); + HcsSymbol *sym = HcsSymbolTableFind(object->objectBase.name); + if (sym == NULL) { + HcsSymbolTableAdd(object->objectBase.name, object); + } else if (sym->object != object && object->configNode.templateSignNum == 0) { + sym->duplicateCount++; + object->configNode.templateSignNum = sym->duplicateCount; + } + + int32_t res; + if (object->configNode.templateSignNum) { + res = sprintf_s(nameBuff, nameBufferSize, "g_%s%s%d", g_littleHumpNamePrefix, tempName, + object->configNode.templateSignNum); + } else { + res = sprintf_s(nameBuff, nameBufferSize, "g_%s%s", g_littleHumpNamePrefix, tempName); + } + + return (res > 0) ? NOERR : EFAIL; +} + +static int32_t HcsTemplateNodeImplGen(ParserObject *current, int32_t tabSize) +{ + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char templateVariableName[VARIABLE_NAME_LEN] = {'\0'}; + if (HcsGenTemplateVariableName(current, templateVariableName, sizeof(templateVariableName))) { + return EOUTPUT; + } + char nodeName[OBJECT_NAME_MAX_LEN] = {0}; + if (strcpy_s(nodeName, sizeof(nodeName), current->configNode.name)) { + HCS_ERROR("%s: string copy fail", __func__); + return EOUTPUT; + } + ToLowerCamelString(nodeName, strlen(nodeName)); + int32_t res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c.%s = %s,\n", tabSize, ' ', nodeName, + current->configNode.inheritCount ? templateVariableName : "0"); + PRINTF_CHECK_AND_RETURN(res); + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), "%*c.%sSize = %d,\n", + tabSize, ' ', nodeName, current->configNode.inheritCount); + PRINTF_CHECK_AND_RETURN(res); + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsInheritObjectImplGen(ParserObject *current, int32_t tabSize) +{ + if (current->configNode.nodeType == CONFIG_NODE_TEMPLATE) { + return HcsTemplateNodeImplGen(current, tabSize); + } + + return NOERR; +} + +static int32_t HcsObjectImplementGen(ParserObject *current, int32_t tabSize) +{ + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t res; + switch (current->objectBase.type) { + case PARSEROP_CONFNODE: { + if (current->configNode.nodeType != CONFIG_NODE_NOREF) { + res = HcsInheritObjectImplGen(current, tabSize); + return res ? res : EASTWALKBREAK; + } + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c.%s = {\n", tabSize, ' ', current->configNode.name); + PRINTF_CHECK_AND_RETURN(res); + if (current->objectBase.child == NULL) { + res = sprintf_s(writeBuffer + strlen(writeBuffer) - 1, WRITE_BUFFER_LEN - strlen(writeBuffer) + 1, + "},\n"); + PRINTF_CHECK_AND_RETURN(res); + } + } break; + case PARSEROP_CONFTERM: + res = HcsPrintTermImplement(writeBuffer, WRITE_BUFFER_LEN, current, tabSize); + if (res) { + return res; + } + break; + default: + return NOERR; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsImplementGenWalkCallBack(ParserObject *current, int32_t walkDepth) +{ + if (current->objectBase.type != PARSEROP_CONFNODE && current->objectBase.type != PARSEROP_CONFTERM) { + return NOERR; + } + + if (current->objectBase.type != PARSEROP_CONFNODE && HcsIsInSubClassNode(current)) { + return NOERR; + } + + if (current == HcsGetParserRoot()) { + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char structName[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = GenConfigStructName(current, structName, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "static const struct %s %s = {\n", structName, + GetConfigRootVariableName()); + PRINTF_CHECK_AND_RETURN(res); + if (current->objectBase.child == NULL) { + res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), "};\n"); + PRINTF_CHECK_AND_RETURN(res); + } + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + } + return HcsObjectImplementGen(current, walkDepth * TAB_SIZE); +} + +static int32_t HcsImplementCloseBraceGen(ParserObject *current, int32_t walkDepth) +{ + if (current->objectBase.type != PARSEROP_CONFNODE) { + return NOERR; + } + + if (current->configNode.nodeType == CONFIG_NODE_INHERIT) { + return NOERR; + } + + int32_t tabSize = walkDepth * TAB_SIZE; + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + + int32_t res; + if (current != HcsGetParserRoot()) { + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "%*c},\n", tabSize, ' '); + PRINTF_CHECK_AND_RETURN(res); + } else { + res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "};\n"); + PRINTF_CHECK_AND_RETURN(res); + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static void ToUpperString(char *str, uint32_t strLen) +{ + for (uint32_t i = 0; i < strLen; ++i) { + str[i] = (char)toupper(str[i]); + } +} + +static void StripFileNameSuffix(char *fileName, uint32_t fileNameLen) +{ + for (uint32_t i = 0; i < fileNameLen; ++i) { + if (fileName[i] == '.') { + fileName[i] = '\0'; + break; + } + } +} + +#define HCS_HEADER_MACRO_MAX_LEN 150 +static char *GenHeaderProtectionMacro() +{ + const char *outPutFileName = HcsGetStripedOutputFileName(); + char *headerMacro = strdup(outPutFileName); + if (headerMacro == NULL) { + HCS_ERROR("oom"); + return NULL; + } + StripFileNameSuffix(headerMacro, strlen(headerMacro)); + ToUpperString(headerMacro, strlen(headerMacro)); + + char *macro = HcsMemZalloc(sizeof(char) * HCS_HEADER_MACRO_MAX_LEN); + if (macro == NULL) { + HCS_ERROR("oom"); + HcsMemFree(headerMacro); + return NULL; + } + + int32_t res = sprintf_s(macro, HCS_HEADER_MACRO_MAX_LEN, "HCS_CONFIG_%s_HEADER_H", headerMacro); + if (res <= 0) { + HcsMemFree(headerMacro); + HcsMemFree(macro); + return NULL; + } + HcsMemFree(headerMacro); + return macro; +} + +static int32_t HcsWriteHeaderFileHead() +{ + /* Write copyright info */ + const char *header = HCS_CONFIG_FILE_HEADER; + if (HcsOutputWrite(header, strlen(header))) { + return EOUTPUT; + } + + /* Write header protection macro */ + char *headerProtectMacro = GenHeaderProtectionMacro(); + if (headerProtectMacro == NULL) { + return EOUTPUT; + } + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t ret = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "#ifndef %s\n#define %s\n\n", + headerProtectMacro, headerProtectMacro); + HcsMemFree(headerProtectMacro); + if (ret <= 0) { + return EOUTPUT; + } + + if (HcsOutputWrite(writeBuffer, strlen(writeBuffer))) { + return EOUTPUT; + } + + /* Write include header file */ + header = HCS_CONFIG_INCLUDE_HEADER; + if (HcsOutputWrite(header, strlen(header))) { + return EOUTPUT; + } + + return NOERR; +} + +static int32_t HcsWriteHeaderFileEnd() +{ + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + /* Write header protection macro */ + char *headerMacro = GenHeaderProtectionMacro(); + if (headerMacro == NULL) { + return EOUTPUT; + } + int32_t ret = sprintf_s(writeBuffer, (WRITE_BUFFER_LEN - 1), "#endif // %s", headerMacro); + HcsMemFree(headerMacro); + if (ret <= 0) { + return EOUTPUT; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsWriteFunctionDeclaration() +{ + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t ret = sprintf_s(writeBuffer, (WRITE_BUFFER_LEN - 1), HCS_CONFIG_INCLUDE_FUNC_DECLARATION, g_namePrefix, + g_bigHumpModuleName, g_bigHumpModuleName); + if (ret <= 0) { + return EOUTPUT; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsWriteFunctionImplement() +{ + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t ret = sprintf_s(writeBuffer, (WRITE_BUFFER_LEN - 1), HCS_CONFIG_FUNC_IMPLEMENT, g_namePrefix, + g_bigHumpModuleName, g_bigHumpModuleName, GetConfigRootVariableName()); + if (ret <= 0) { + return EOUTPUT; + } + + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsOutputHeaderFile() +{ + struct HcsFile *outputFIle = NULL; + ParserObject *astRoot = HcsGetParserRoot(); + if (astRoot == NULL) { + return EOUTPUT; + } + + /* Duplicate node name check */ + if (HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, HcsDuplicateCheckWalkCallBack)) { + return EOUTPUT; + } + + outputFIle = HcsOpenOutputFile(".h"); + if (outputFIle == NULL) { + return EINVALF; + } + + int32_t ret = HcsWriteHeaderFileHead(); + if (ret) { + goto OUT; + } + /* Generate C header file containing the structure definition of config */ + if (!HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, HcsDefinitionGenWalkCallBack)) { + ret = HcsWriteFunctionDeclaration(); + if (ret) { + goto OUT; + } + } + + ret = HcsWriteHeaderFileEnd(); +OUT: + HcsCloseOutput(outputFIle); + return ret; +} + + +static int32_t g_baseTabsize = 0; + +static int32_t HcsTemplateObjectGenWalk(ParserObject *current, int32_t walkDepth) +{ + return HcsObjectImplementGen(current, walkDepth * TAB_SIZE + g_baseTabsize); +} + +static int32_t HcsTemplateCloseBraceGen(ParserObject *current, int32_t walkDepth) +{ + return HcsImplementCloseBraceGen(current, walkDepth + g_baseTabsize / TAB_SIZE); +} + +static int32_t HcsTemplateVariableGen(ParserObject *current) +{ + ParserObject *child = (ParserObject *)current->objectBase.child; + while (child != NULL) { + int32_t res = HcsWalkAst(child, AST_WALK_ROUND, HcsTemplateObjectGenWalk, HcsTemplateCloseBraceGen); + if (res) { + return res; + } + child = (ParserObject *)child->objectBase.next; + } + return NOERR; +} + +static int32_t HcsTemplateImplGenWalkCallBack(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + if (current->objectBase.type != PARSEROP_CONFNODE || current->configNode.nodeType != CONFIG_NODE_TEMPLATE) { + return NOERR; + } + + if (!current->configNode.inheritCount) { + return NOERR; + } + + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char nameBuff[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = GenConfigStructName(current, nameBuff, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "static const struct %s ", nameBuff); + PRINTF_CHECK_AND_RETURN(res); + if (HcsGenTemplateVariableName(current, nameBuff, sizeof(nameBuff))) { + return EOUTPUT; + } + res = sprintf_s(writeBuffer + strlen(writeBuffer), sizeof(writeBuffer) - strlen(writeBuffer), + "%s[] = {\n", nameBuff); + PRINTF_CHECK_AND_RETURN(res); + HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + /* Generate C global variables definition file */ + + TemplateNodeInstance *subClasses = current->configNode.subClasses; + g_baseTabsize = TAB_SIZE + TAB_SIZE; + while (subClasses != NULL) { + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "%*c[%d] = {\n", TAB_SIZE, ' ', + subClasses->nodeObject->inheritIndex); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(writeBuffer, res)) { + return EOUTPUT; + } + if (HcsTemplateVariableGen((ParserObject *)subClasses->nodeObject)) { + return EOUTPUT; + } + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "%*c},\n", TAB_SIZE, ' '); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(writeBuffer, strlen(writeBuffer))) { + return EOUTPUT; + } + subClasses = subClasses->next; + } + + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "};\n\n"); + PRINTF_CHECK_AND_RETURN(res); + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsArrayVariablesDeclareGen(ParserObject *term) +{ + if (!HcsIsInSubClassNode(term)) { + return NOERR; + } + + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char nameBuff[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = GenConfigArrayName(term, nameBuff, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + ParserObject *array = (ParserObject *)term->configTerm.child; + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "\nstatic const %s %s[%d] = {\n%*c", GetArrayType(array), + nameBuff, GetArraySize(array), TAB_SIZE, ' '); + PRINTF_CHECK_AND_RETURN(res); + if (HcsOutputWrite(writeBuffer, strlen(writeBuffer))) { + return EOUTPUT; + } + if (HcsPrintArrayContent(array, TAB_SIZE)) { + HCS_ERROR("fail to write array content"); + return EOUTPUT; + } + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "\n};\n"); + PRINTF_CHECK_AND_RETURN(res); + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsTemplateVariablesDeclareGenWalk(ParserObject *current, int32_t walkDepth) +{ + (void)walkDepth; + if (current->objectBase.type == PARSEROP_CONFTERM && HcsGetTermType(current) == PARSEROP_ARRAY) { + return HcsArrayVariablesDeclareGen(current); + } else if (current->objectBase.type != PARSEROP_CONFNODE || current->configNode.nodeType != CONFIG_NODE_TEMPLATE) { + return NOERR; + } + + if (!current->configNode.inheritCount) { + return NOERR; + } + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + char nameBuff[OBJECT_NAME_MAX_LEN] = {'\0'}; + int32_t res = GenConfigStructName(current, nameBuff, OBJECT_NAME_MAX_LEN - 1); + if (res) { + return res; + } + + res = sprintf_s(writeBuffer, sizeof(writeBuffer), "static const struct %s ", nameBuff); + PRINTF_CHECK_AND_RETURN(res); + if (HcsGenTemplateVariableName(current, nameBuff, sizeof(nameBuff))) { + return EOUTPUT; + } + res = sprintf_s(writeBuffer + strlen(writeBuffer), sizeof(writeBuffer) - strlen(writeBuffer), "%s[];\n", nameBuff); + PRINTF_CHECK_AND_RETURN(res); + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsTemplateVariablesDeclareGen(ParserObject *astRoot) +{ + uint32_t writeCount = HcsGetOutputCurrentCount(); + if (HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, HcsTemplateVariablesDeclareGenWalk)) { + return EOUTPUT; + } + if (writeCount == HcsGetOutputCurrentCount()) { + /* if no template variable generated, should not output end line */ + return NOERR; + } + char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; + int32_t res = sprintf_s(writeBuffer, sizeof(writeBuffer), "\n"); + PRINTF_CHECK_AND_RETURN(res); + return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); +} + +static int32_t HcsOutputTemplateImplement(ParserObject *astRoot) +{ + if (HcsTemplateVariablesDeclareGen(astRoot)) { + return EOUTPUT; + } + + /* all template node will be global variables */ + return HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, HcsTemplateImplGenWalkCallBack); +} + +static int32_t HcsOutputCFile() +{ + ParserObject *astRoot = HcsGetParserRoot(); + if (astRoot == NULL) { + return EOUTPUT; + } + + if (HcsSymbolTableReset()) { + return EOUTPUT; + } + + struct HcsFile *outputFIle = HcsOpenOutputFile(".c"); + if (outputFIle == NULL) { + return EINVALF; + } + + const char *header = HCS_CONFIG_FILE_HEADER; + if (HcsOutputWrite(header, strlen(header))) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + + char include[INCLUDE_PATH_MAX_LEN] = {'\0'}; + int32_t res = sprintf_s(include, INCLUDE_PATH_MAX_LEN, "#include \"%s", HcsGetStripedOutputFileName()); + if (res <= 0) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + + res = sprintf_s(include + strlen(include) - 1, WRITE_BUFFER_LEN - strlen(include), "h\"\n\n"); + if (res <= 0) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + + if (HcsOutputWrite(include, strlen(include))) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + + res = HcsOutputTemplateImplement(astRoot); + if (res) { + HcsCloseOutput(outputFIle); + return EOUTPUT; + } + + /* Generate C global variables definition file */ + res = HcsWalkAst(astRoot, AST_WALK_ROUND, HcsImplementGenWalkCallBack, HcsImplementCloseBraceGen); + if (res) { + HcsCloseOutput(outputFIle); + return res; + } + + res = HcsWriteFunctionImplement(); + HcsCloseOutput(outputFIle); + return res; +} + +int32_t HcsTextCodeOutput() +{ + int32_t ret = HcsSymbolTableInit(); + if (ret) { + return ret; + } + + const char *symbolPrefix = HcsOptGetSymbolNamePrefix(); + if (symbolPrefix != NULL) { + g_namePrefix = symbolPrefix; + } + + do { + ret = InitConfigVariableNames(); + if (ret) { + break; + } + ret = HcsOutputHeaderFile(); + if (ret) { + break; + } + + ret = HcsOutputCFile(); + } while (false); + + ReleaseConfigVariableNames(); + HcsSymbolTableRelease(); + return ret; +} diff --git a/utils/include/hdf_cstring.h b/utils/include/hdf_cstring.h new file mode 100755 index 00000000..dedda5cf --- /dev/null +++ b/utils/include/hdf_cstring.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_CSTRING_H +#define HDF_CSTRING_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfCString { + int size; + char value[0]; +}; + +bool HdfStringToInt(const char* str, int *value); +uint32_t HdfStringMakeHashKey(const char *key, uint32_t mask); +struct HdfCString *HdfCStringObtain(const char *str); +void HdfCStringRecycle(struct HdfCString *inst); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_CSTRING_H */ diff --git a/utils/include/hdf_slist.h b/utils/include/hdf_slist.h new file mode 100755 index 00000000..b9bf13e5 --- /dev/null +++ b/utils/include/hdf_slist.h @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_SINGLE_LIST_H +#define HDF_SINGLE_LIST_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfSListNode { + struct HdfSListNode *next; // next element in list, or NULL +}; + +struct HdfSList { + struct HdfSListNode *root; +}; + +struct HdfSListIterator { + int stepOnNext; + struct HdfSListNode *previous; // points to the item before the current one + struct HdfSListNode *current; // points to the current item (to detect item removal) +}; + +typedef void (*HdfSListDeleter)(struct HdfSListNode *); + +typedef bool (*HdfSListSearchCompare)(struct HdfSListNode *, uint32_t); + +typedef bool (*HdfSListAddCompare)(struct HdfSListNode *, struct HdfSListNode *); + +/* + * @brief Init the list + * + * @param[in] list :the operation list. + * + * @return None + */ +void HdfSListInit(struct HdfSList *list); + +/* + * @brief search to see whether specific element is attach into the list. + * + * @param[in] list the operation list. + * @param[in] searchKey -search key of list node. + * @param[in] comparer -comparer of list node. + * + * @return struct HdfSListNode of search result + * -# NULL if not found. + */ +struct HdfSListNode *HdfSListSearch(struct HdfSList *list, uint32_t searchKey, HdfSListSearchCompare compare); + +/* + * @brief tests if list is empty + * + * @param[in] list the operation list. + * + * @return bool result of queue status. + */ +bool HdfSListIsEmpty(struct HdfSList *list); + +/* + * @brief find the last item in the list + * + * @param[in] list the operation list. + * + * @return last link of list. + */ +struct HdfSListNode *HdfSListGetLast(struct HdfSList *list); + +/* + * @brief add item to the head of the list + * + * @param[in] list :the operation list. + * @param[in] p_node :the new element to add. + * + * @return None + */ +void HdfSListAdd(struct HdfSList *list, struct HdfSListNode *link); + +/* + * @brief add item to list as last element + * + * @param[in] list the operation list. + * @param[in] p_node :the new element to add. + * + * @return None + */ +void HdfSListAddTail(struct HdfSList *list, struct HdfSListNode *link); + +/* + * @brief add item to list as ordered + * + * @param[in] list the operation list. + * @param[in] p_node :the new element to add. + * @param[in] comparer :compared. + * + * @return bool result of queue status. + */ +bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddCompare compare); + +/* + * @brief remove item from list + * + * @param[in] list :the operation list. + * @param[in] p_node :the element to remove. + * + * @return the result of remove node. + * -# HDF_SUCCESS link has been successfully removed. + * -# HDF_FAILURE link was not found in the list. + */ +void HdfSListRemove(struct HdfSList *list, struct HdfSListNode *link); + +/* + * @brief flush the list and free memory + * + * @param[in] list the operation list. + * @param[in] deleter :the func of free memory. + * + * @return None + */ +void HdfSListFlush(struct HdfSList *list, HdfSListDeleter deleter); + +/* + * @brief calculate the element count in the list. + * + * @param[in] list :the list to count. + * + * @return the count of list. + */ +int HdfSListCount(struct HdfSList *list); + +/* + * @brief get first element + * + * @param[in] list the operation list. + * + * @return the first element in the list. + */ +struct HdfSListNode *HdfSListPeek(struct HdfSList *list); + +/* + * @brief get next element of p_link; + * + * @param[in] p_link: the operation link. + * + * @return the next element of the link pass in + */ +struct HdfSListNode *HdfSListNext(struct HdfSListNode *link); + +/* + * @brief get and remove first element + * + * @param[in] list the operation list. + * + * @return the first element in the list. + */ +struct HdfSListNode *HdfSListPop(struct HdfSList *list); + +/* + * @brief initialize iterator + * + * @param[in] iterator the point of iterator. + * @param[in] list the point of operation list. + * + * @return None + */ +void HdfSListIteratorInit(struct HdfSListIterator *iterator, struct HdfSList *list); + +/* + * @brief check whether list has next node. + * + * @param[in] iterator the point of iterator. + * + * @return the result of check next. + */ +bool HdfSListIteratorHasNext(struct HdfSListIterator *iterator); + +/* + * @brief get next link in the list and move iterator to next. + * + * @param[in] iterator the point of iterator. + * + * @return point to next element of it. + */ +struct HdfSListNode *HdfSListIteratorNext(struct HdfSListIterator *iterator); + +/* + * @brief remove current node that iterator point to and move iterator to next node + * + * @param[in] iterator the point of iterator. + * + * @return None + */ +void HdfSListIteratorRemove(struct HdfSListIterator *iterator); + +/* + * @brief insert new node before the node that iterator point to.and hold current iterator. + * + * @param[in] list the operation list. + * + * @return None + */ +void HdfSListIteratorInsert(struct HdfSListIterator *iterator, struct HdfSListNode *link); + +#define OFFSET_OF(type, mem) ((size_t) &((type *)0)->mem) + +#define HDF_SLIST_CONTAINER_OF(mtype, ptr, type, mem) ({ \ + const mtype*__mptr = (ptr); \ + (type *)((char *)__mptr - OFFSET_OF(type, mem)); \ +}) + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_SINGLE_LIST_H */ diff --git a/utils/include/hdf_sref.h b/utils/include/hdf_sref.h new file mode 100755 index 00000000..00f7297d --- /dev/null +++ b/utils/include/hdf_sref.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HDF_SREF_H +#define HDF_SREF_H + +#include "osal_atomic.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct HdfSRef; + +struct IHdfSRefListener { + void (*OnFirstAcquire)(struct HdfSRef *); + void (*OnLastRelease)(struct HdfSRef *); +}; + +struct HdfSRef { + OsalAtomic refs; + struct IHdfSRefListener *listener; + void (*Acquire)(struct HdfSRef *); + void (*Release)(struct HdfSRef *); +}; + +void HdfSRefAcquire(struct HdfSRef *sref); +void HdfSRefRelease(struct HdfSRef *sref); +void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener); + +#ifdef __cplusplus +} +#endif + +#endif /* HDF_SREF_H */ diff --git a/utils/src/hdf_cstring.c b/utils/src/hdf_cstring.c new file mode 100755 index 00000000..33217993 --- /dev/null +++ b/utils/src/hdf_cstring.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_cstring.h" +#include +#include +#include +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" + +uint32_t HdfStringMakeHashKey(const char *key, uint32_t mask) +{ + uint32_t hashValue = 0; + const uint32_t seed = 131; // 31 131 1313 13131 131313 etc.. + while ((key != NULL) && *key) { + hashValue = hashValue * seed + (*key++); + } + return (hashValue & 0x7FFFFFFF) | mask; +} + +bool HdfStringToInt(const char *str, int *value) +{ + if (str == NULL || value == NULL) { + return false; + } + + char *end = NULL; + errno = 0; + const int base = 10; + long result = strtol(str, &end, base); + if (end == str || end[0] != '\0' || errno == ERANGE || result > INT_MAX || result < INT_MIN) { + return false; + } + + *value = (int)result; + return true; +} + +struct HdfCString *HdfCStringObtain(const char *str) +{ + struct HdfCString *instance = NULL; + if (str != NULL) { + size_t strLen = strlen(str); + size_t size = sizeof(struct HdfCString) + strLen + 1; + instance = (struct HdfCString *)OsalMemCalloc(size); + if (instance == NULL) { + HDF_LOGE("HdfCStringObtain failed, alloc memory failed"); + return NULL; + } + if (strncpy_s(instance->value, strLen + 1, str, strLen) != EOK) { + HDF_LOGE("HdfCStringObtain failed, strncpy_s failed"); + OsalMemFree(instance); + return NULL; + } + instance->size = strLen; + } + return instance; +} + +void HdfCStringRecycle(struct HdfCString *inst) +{ + if (inst != NULL) { + OsalMemFree(inst); + } +} diff --git a/utils/src/hdf_slist.c b/utils/src/hdf_slist.c new file mode 100755 index 00000000..c6fd97aa --- /dev/null +++ b/utils/src/hdf_slist.c @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_slist.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG utils_slist + +void HdfSListInit(struct HdfSList *list) +{ + if (list != NULL) { + list->root = NULL; + } +} + +bool HdfSListIsEmpty(struct HdfSList *list) +{ + return ((list == NULL) || (list->root == NULL)); +} + +struct HdfSListNode *HdfSListSearch(struct HdfSList *list, uint32_t keyValue, HdfSListSearchCompare compare) +{ + struct HdfSListIterator it; + if (compare == NULL) { + return NULL; + } + HdfSListIteratorInit(&it, list); + while (HdfSListIteratorHasNext(&it)) { + struct HdfSListNode *listNode = HdfSListIteratorNext(&it); + if (compare(listNode, keyValue)) { + return listNode; + } + } + return NULL; +} + +struct HdfSListNode *HdfSListGetLast(struct HdfSList *list) +{ + struct HdfSListNode *last = NULL; + struct HdfSListNode *iterator = NULL; + if (list == NULL) { + return NULL; + } + + for (iterator = list->root; iterator; iterator = iterator->next) { + if (iterator != NULL) { + last = iterator; + } + } + return last; +} + +void HdfSListAdd(struct HdfSList *list, struct HdfSListNode *link) +{ + struct HdfSListNode *iterator = NULL; + if (list == NULL || link == NULL) { + return; + } + + for (iterator = list->root; iterator; iterator = iterator->next) { + if (iterator == link) { + return; + } + } + + link->next = list->root; + list->root = link; +} + +void HdfSListAddTail(struct HdfSList *list, struct HdfSListNode *link) +{ + struct HdfSListNode *iterator = NULL; + if (list == NULL || link == NULL) { + return; + } + + for (iterator = (struct HdfSListNode *)list; iterator->next; iterator = iterator->next) { + if (iterator->next == link) { + return; + } + } + + link->next = NULL; + iterator->next = link; +} + +bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddCompare compare) +{ + struct HdfSListNode *iterator = NULL; + if (list == NULL || link == NULL || compare == NULL) { + HDF_LOGE("input is invalid"); + return false; + } + for (iterator = list->root; iterator; iterator = iterator->next) { + if (iterator == link) { + HDF_LOGE("link is already in list"); + return false; + } + } + if (compare(link, list->root)) { + link->next = list->root; + list->root = link; + return true; + } + for (iterator = list->root; iterator && iterator->next; iterator = iterator->next) { + if (compare(iterator, link) && compare(link, iterator->next)) { + link->next = iterator->next; + iterator->next = link; + return true; + } + } + if ((list->root == NULL) || (iterator == NULL)) { + link->next = NULL; + list->root = link; + } else { + link->next = NULL; + iterator->next = link; + } + return true; +} + +void HdfSListRemove(struct HdfSList *list, struct HdfSListNode *link) +{ + struct HdfSListNode *iterator = NULL; + if (list == NULL || link == NULL) { + return; + } + + for (iterator = (struct HdfSListNode *)list; iterator; iterator = iterator->next) { + if (iterator->next == link) { + iterator->next = link->next; + return; + } + } +} + +void HdfSListFlush(struct HdfSList *list, HdfSListDeleter deleter) +{ + struct HdfSListIterator iterator; + if (list == NULL) { + return; + } + + HdfSListIteratorInit(&iterator, list); + while (HdfSListIteratorHasNext(&iterator)) { + void *listNode = (void *)HdfSListIteratorNext(&iterator); + HdfSListIteratorRemove(&iterator); + if (deleter != NULL) { + deleter(listNode); + } + } +} + +int HdfSListCount(struct HdfSList *list) +{ + struct HdfSListNode *iterator = NULL; + int counter = 0; + if (list == NULL) { + return counter; + } + + for (iterator = (struct HdfSListNode *)list; iterator->next; iterator = iterator->next) { + counter++; + } + return counter; +} + +struct HdfSListNode *HdfSListPeek(struct HdfSList *list) +{ + if (list == NULL) { + return NULL; + } + + return list->root; +} + +struct HdfSListNode *HdfSListNext(struct HdfSListNode *link) +{ + if (link == NULL) { + return NULL; + } + + return link->next; +} + +struct HdfSListNode *HdfSListPop(struct HdfSList *list) +{ + if (list == NULL || list->root == NULL) { + return NULL; + } + + struct HdfSListNode *first = list->root; + list->root = first->next; + return first; +} + +void HdfSListIteratorInit(struct HdfSListIterator *iterator, struct HdfSList *list) +{ + if (iterator == NULL || list == NULL) { + if (iterator != NULL) { + iterator->stepOnNext = 0; + iterator->previous = NULL; + iterator->current = NULL; + } + return; + } + iterator->stepOnNext = 0; + iterator->previous = (struct HdfSListNode *)list; + iterator->current = list->root; +} + +bool HdfSListIteratorHasNext(struct HdfSListIterator *iterator) +{ + if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + return false; + } + + if (!iterator->stepOnNext) { + return iterator->current != NULL; + } + + if (iterator->previous->next != iterator->current) { + // current item has been removed + return iterator->previous->next != NULL; + } + + // current items has not been removed + return iterator->current->next != NULL; +} + +struct HdfSListNode *HdfSListIteratorNext(struct HdfSListIterator *iterator) +{ + if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + return NULL; + } + + if (iterator->stepOnNext) { + if (iterator->previous->next == iterator->current) { + iterator->previous = iterator->current; + iterator->current = iterator->current->next; + } else { + // curr was removed from the list, set it again but don't advance prev + iterator->current = iterator->previous->next; + } + } else { + iterator->stepOnNext = 1; + } + + return iterator->current; +} + +void HdfSListIteratorRemove(struct HdfSListIterator *iterator) +{ + if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + return; + } + + iterator->current = iterator->current->next; + iterator->previous->next = iterator->current; + iterator->stepOnNext = 0; +} + +void HdfSListIteratorInsert(struct HdfSListIterator *iterator, struct HdfSListNode *link) +{ + if (iterator == NULL || link == NULL) { + return; + } + + link->next = iterator->current; + iterator->previous->next = link; + iterator->previous = link; +} + diff --git a/utils/src/hdf_sref.c b/utils/src/hdf_sref.c new file mode 100755 index 00000000..c6608330 --- /dev/null +++ b/utils/src/hdf_sref.c @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "hdf_sref.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hdf_sref + +void HdfSRefAcquire(struct HdfSRef *sref) +{ + int32_t lockRef; + if (sref == NULL) { + HDF_LOGE("Acquire input sref is null"); + return; + } + OsalAtomicInc(&sref->refs); + lockRef = OsalAtomicRead(&sref->refs); + if ((lockRef == 1) && (sref->listener != NULL)) { + struct IHdfSRefListener *listener = sref->listener; + if (listener->OnFirstAcquire != NULL) { + listener->OnFirstAcquire(sref); + } + } +} + +void HdfSRefRelease(struct HdfSRef *sref) +{ + int32_t lockRef; + if (sref == NULL) { + HDF_LOGE("Release input sref is null"); + return; + } + OsalAtomicDec(&sref->refs); + lockRef = OsalAtomicRead(&sref->refs); + if ((lockRef == 0) && (sref->listener != NULL)) { + struct IHdfSRefListener *listener = sref->listener; + if (listener->OnLastRelease != NULL) { + listener->OnLastRelease(sref); + } + } +} + +void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener) +{ + if ((sref == NULL) || (listener == NULL)) { + HDF_LOGE("Input params is invalid"); + return; + } + OsalAtomicSet(&sref->refs, 0); + sref->listener = listener; + sref->Acquire = HdfSRefAcquire; + sref->Release = HdfSRefRelease; +} +