diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..755f09aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.o +*.a +*.d +*.cmd diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 00000000..9877bc28 --- /dev/null +++ b/OAT.xml @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 27cb7c89..e182839b 100644 --- a/README.md +++ b/README.md @@ -156,9 +156,9 @@ For details, see [WLAN Overview](https://gitee.com/openharmony/docs/blob/master drivers\_framework -[drivers\_adapter\_uhdf](https://gitee.com/openharmony/drivers_adapter_uhdf/blob/master/README.md) +[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README.md) -[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_uhdf/blob/master/README.md) +[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README.md) -[drivers\_adapter\_khdf\_liteos](https://gitee.com/openharmony/drivers_adapter_uhdf/blob/master/README.md) +[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README.md) diff --git a/README_zh.md b/README_zh.md index 9cac9299..ecc7f41f 100644 --- a/README_zh.md +++ b/README_zh.md @@ -156,13 +156,9 @@ HDF驱动框架详细开发请参考[驱动开发指南](https://gitee.com/openh drivers\_framework -[drivers\_adapter\_uhdf](https://gitee.com/openharmony/drivers_adapter_uhdf/blob/master/README_zh.md) +[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README_zh.md) [drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README_zh.md) -[drivers\_adapter\_khdf\_liteos](https://gitee.com/openharmony/drivers_adapter_khdf_liteos/blob/master/README_zh.md) - - - -
+[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md) diff --git a/ability/config/device_resource_if.c b/ability/config/device_resource_if.c index 6bea6afd..5f75a409 100644 --- a/ability/config/device_resource_if.c +++ b/ability/config/device_resource_if.c @@ -41,7 +41,7 @@ static bool DeviceResourceIfaceConstruct(struct DeviceResourceIface *instance, D HcsIfaceConstruct(instance); break; default: - HDF_LOGE("%s: Currently, this configuration type is not supported. the type is %d", __func__, type); + HDF_LOGE("%s: Currently, this configuration type is not supported, the type is %d", __func__, type); return false; } return true; diff --git a/ability/config/hcs_parser/include/hcs_blob_if.h b/ability/config/hcs_parser/include/hcs_blob_if.h index b50c8f35..b2a73121 100644 --- a/ability/config/hcs_parser/include/hcs_blob_if.h +++ b/ability/config/hcs_parser/include/hcs_blob_if.h @@ -71,7 +71,7 @@ static inline uint32_t HcsGetPrefix(const char *start) #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'. +#define HCS_STRING_LENGTH(str) (HcsIsByteAlign() ? HcsAlignSize(strlen(str) + 1) : (strlen(str) + 1)) int32_t HcsGetDataTypeOffset(const char *start); int32_t HcsGetAttrLength(const char *start); int32_t HcsGetNodeOrAttrLength(const char *start); @@ -82,4 +82,4 @@ 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 +#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 index 2aa2c63e..d56bbcd7 100644 --- a/ability/config/hcs_parser/include/hcs_generate_tree.h +++ b/ability/config/hcs_parser/include/hcs_generate_tree.h @@ -13,9 +13,9 @@ #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 + uint32_t offset; // The offset of the node in the blob. + struct DeviceResourceNode *node; // The head node of a 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 +#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 index 216eecc3..a20e26ba 100644 --- a/ability/config/hcs_parser/include/hcs_parser.h +++ b/ability/config/hcs_parser/include/hcs_parser.h @@ -13,4 +13,4 @@ bool HcsDecompile(const char *hcsBlob, uint32_t offset, struct DeviceResourceNode **root); -#endif // HCS_PARSER_H \ No newline at end of file +#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 index b02bc332..09875dec 100644 --- a/ability/config/hcs_parser/include/hcs_tree_if.h +++ b/ability/config/hcs_parser/include/hcs_tree_if.h @@ -56,4 +56,4 @@ const struct DeviceResourceNode *HcsGetNodeByRefAttr(const struct DeviceResource #endif #endif /* __cplusplus */ -#endif // HCS_TREE_IF_H \ No newline at end of file +#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 index 1f007c6f..dfb023d8 100644 --- a/ability/config/hcs_parser/src/hcs_blob_if.c +++ b/ability/config/hcs_parser/src/hcs_blob_if.c @@ -13,7 +13,7 @@ static bool g_byteAlign = false; -bool HcsIsByteAlign() +bool HcsIsByteAlign(void) { return g_byteAlign; } @@ -185,7 +185,7 @@ static bool CheckHcsBlobLength(uint32_t length, struct HbcHeader *header) HDF_LOGI("%s: the blobLength: %u, byteAlign: %d", __func__, blobLength, g_byteAlign); } if ((length != blobLength) || (blobLength < minLength)) { - HDF_LOGE("%s failed, Hcsblob file length is %u, But the length of calculation is %u", + HDF_LOGE("%s failed, Hcsblob file length is %u, but the calculated length is %u", __func__, length, blobLength); return false; } @@ -201,7 +201,7 @@ bool HcsCheckBlobFormat(const char *start, uint32_t length) } header = (struct HbcHeader *)start; if (header->magicNumber != HBC_MAGIC_NUMBER) { - HDF_LOGE("%s failed, the magic of HBC is %x", __func__, header->magicNumber); + HDF_LOGE("%s failed, the magic number of HBC is %x", __func__, header->magicNumber); return false; } if (!CheckHcsBlobLength(length, header)) { diff --git a/ability/config/hcs_parser/src/hcs_generate_tree.c b/ability/config/hcs_parser/src/hcs_generate_tree.c index cd638683..c3306ed6 100644 --- a/ability/config/hcs_parser/src/hcs_generate_tree.c +++ b/ability/config/hcs_parser/src/hcs_generate_tree.c @@ -53,7 +53,7 @@ static bool UpdateTreeStack(struct TreeStack **treeStack, int32_t *treeLayer, st uint32_t offset) { if (*treeLayer >= (TREE_STACK_MAX - 1)) { - HDF_LOGE("%s failed, the treeLayer error. treeLayer: %d", __func__, *treeLayer); + HDF_LOGE("%s failed, the treeLayer error, treeLayer: %d", __func__, *treeLayer); return false; } (*treeLayer)++; @@ -83,7 +83,7 @@ static int32_t ParseByteCode(const char *treeStart, int32_t offset, char **treeM { int32_t termOffset = HcsGetNodeOrAttrLength(treeStart + offset); if (termOffset <= 0) { - HDF_LOGE("%s failed, HcsGetNodeOrAttrLength failed, errno: %d", __func__, termOffset); + HDF_LOGE("%s failed, HcsGetNodeOrAttrLength error, errno: %d", __func__, termOffset); return HDF_FAILURE; } @@ -111,7 +111,7 @@ static int32_t ParseByteCode(const char *treeStart, int32_t offset, char **treeM } parentOrCurNode = GetParentNode(offset, *treeStack, treeLayerOrMemLen, termOffset); if (!AddAttrInNode(treeStart + offset, parentOrCurNode, treeMem)) { - HDF_LOGE("%s failed, the AddAttrInNode error", __func__); + HDF_LOGE("%s failed, AddAttrInNode error", __func__); return HDF_FAILURE; } break; @@ -136,14 +136,14 @@ int32_t GenerateCfgTree(const char *treeStart, int32_t length, char *treeMem, st 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__); + HDF_LOGE("%s failed, ParseByteCode error", __func__); treeLayerOrMemLen = eachOffset; break; } offset += eachOffset; } if ((treeMem != NULL) && (root != NULL) && (treeLayerOrMemLen > 0)) { - // the treeStack[1] is root + // The treeStack[1] is root *root = treeStack[1].node; } OsalMemFree(treeStack); diff --git a/ability/config/hcs_parser/src/hcs_parser.c b/ability/config/hcs_parser/src/hcs_parser.c index 50ef7643..29596bd5 100644 --- a/ability/config/hcs_parser/src/hcs_parser.c +++ b/ability/config/hcs_parser/src/hcs_parser.c @@ -23,19 +23,19 @@ bool HcsDecompile(const char *hcsBlob, uint32_t offset, struct DeviceResourceNod { int32_t nodeLength = HcsGetNodeLength(hcsBlob + offset); if (nodeLength < 0) { - HDF_LOGE("%s failed, HcsGetNodeLength failed", __func__); + HDF_LOGE("%s failed, HcsGetNodeLength error", __func__); return false; } int32_t treeMemLength = GetHcsTreeSize(hcsBlob + offset, nodeLength); if (treeMemLength <= 0) { - HDF_LOGE("%s failed, GetHcsTreeSize failed", __func__); + HDF_LOGE("%s failed, GetHcsTreeSize error, treeMemLength = %d", __func__, treeMemLength); return false; } char *treeMem = (char *)OsalMemCalloc(treeMemLength); if (treeMem == NULL) { - HDF_LOGE("%s failed, OsalMemCalloc Device tree memory failed", __func__); + HDF_LOGE("%s failed, OsalMemCalloc error", __func__); return false; } int32_t treeLayer = GenerateCfgTree(hcsBlob + offset, nodeLength, treeMem, root); diff --git a/ability/config/hcs_parser/src/hcs_tree_if.c b/ability/config/hcs_parser/src/hcs_tree_if.c index d4aba7c6..2b760a49 100644 --- a/ability/config/hcs_parser/src/hcs_tree_if.c +++ b/ability/config/hcs_parser/src/hcs_tree_if.c @@ -36,7 +36,7 @@ bool HcsGetBool(const struct DeviceResourceNode *node, const char *attrName) } if (!HcsSwapToUint8(&value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return false; } return value ? true : false; @@ -44,7 +44,7 @@ bool HcsGetBool(const struct DeviceResourceNode *node, const char *attrName) #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", \ + HDF_LOGE("%s failed, the attr of %s is NULL, or the value is NULL, the value is default value", \ __func__, ((attrName) == NULL) ? "error attrName" : (attrName)); \ if ((value) != NULL) { \ *(value) = (def); \ @@ -60,7 +60,7 @@ int32_t HcsGetUint8(const struct DeviceResourceNode *node, const char *attrName, if (!HcsSwapToUint8(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -73,7 +73,7 @@ int32_t HcsGetUint16(const struct DeviceResourceNode *node, const char *attrName if (!HcsSwapToUint16(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -86,7 +86,7 @@ int32_t HcsGetUint32(const struct DeviceResourceNode *node, const char *attrName if (!HcsSwapToUint32(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -99,7 +99,7 @@ int32_t HcsGetUint64(const struct DeviceResourceNode *node, const char *attrName if (!HcsSwapToUint64(value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -116,7 +116,7 @@ static const char *GetArrayElem(const struct DeviceResourceAttr *attr, uint32_t return NULL; } if (index >= count) { - HDF_LOGE("%s failed, the index: %u >= count: %u", __func__, index, count); + HDF_LOGE("%s failed, index: %u >= count: %u", __func__, index, count); return NULL; } for (i = 0; i < index; i++) { @@ -144,7 +144,7 @@ int32_t HcsGetUint8ArrayElem(const struct DeviceResourceNode *node, const char * } if (!HcsSwapToUint8(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_ERR_INVALID_OBJECT; } return HDF_SUCCESS; @@ -165,7 +165,7 @@ int32_t HcsGetUint16ArrayElem(const struct DeviceResourceNode *node, const char } if (!HcsSwapToUint16(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_ERR_INVALID_OBJECT; } return HDF_SUCCESS; @@ -186,7 +186,7 @@ int32_t HcsGetUint32ArrayElem(const struct DeviceResourceNode *node, const char } if (!HcsSwapToUint32(value, realValue + HCS_PREFIX_LENGTH, HcsGetPrefix(realValue))) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_ERR_INVALID_OBJECT; } return HDF_SUCCESS; @@ -202,7 +202,7 @@ int32_t HcsGetUint64ArrayElem(const struct DeviceResourceNode *node, const char 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__); + HDF_LOGE("%s failed, invalid realValue (NULL) or incorrect prefix", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -211,11 +211,11 @@ int32_t HcsGetUint64ArrayElem(const struct DeviceResourceNode *node, const char #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)); \ + HDF_LOGE("%s failed, the result is %d", __func__, (result)); \ continue; \ } \ if ((result) != HDF_SUCCESS) { \ - HDF_LOGE("%s failed, the ret is %d", __func__, (result)); \ + HDF_LOGE("%s failed, the result is %d", __func__, (result)); \ return result; \ } \ } while (0) @@ -316,7 +316,7 @@ int32_t HcsGetString(const struct DeviceResourceNode *node, const char *attrName RETURN_DEFAULT_VALUE(attr, attrName, value, def); if (HcsGetPrefix(attr->value) != CONFIG_STRING) { *value = def; - HDF_LOGE("%s failed, Incorrect prefix code", __func__); + HDF_LOGE("%s failed, incorrect prefix", __func__); return HDF_FAILURE; } *value = attr->value + HCS_PREFIX_LENGTH; @@ -366,7 +366,7 @@ const struct DeviceResourceNode *HcsGetNodeByMatchAttr(const struct DeviceResour const struct DeviceResourceNode *curNode = NULL; 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__); + HDF_LOGE("%s failed, attrValue or instance error", __func__); return NULL; } curNode = (node != NULL) ? node : instance->GetRootNode(); diff --git a/ability/config/test/unittest/common/hdf_config_test.cpp b/ability/config/test/unittest/common/hdf_config_test.cpp index 69c1800f..f8cd98cd 100644 --- a/ability/config/test/unittest/common/hdf_config_test.cpp +++ b/ability/config/test/unittest/common/hdf_config_test.cpp @@ -19,7 +19,7 @@ using namespace testing::ext; namespace ConfigTest { -const int8_t HDF_MSG_RESUL_DEFALUT = 3; +const int8_t HDF_MSG_RESULT_DEFAULT = 3; // hcs config test case number enum HdfTestCaseCmd { @@ -84,23 +84,19 @@ void HdfConfigTest::TearDownTestCase() HdfTestCloseService(); } -void HdfConfigTest::SetUp() -{ -} +void HdfConfigTest::SetUp() {} -void HdfConfigTest::TearDown() -{ -} +void HdfConfigTest::TearDown() {} /** * @tc.name: HslTestCreateDMHslToTree001 - * @tc.desc: Create a config tree, enter config test + * @tc.desc: Create a configuration tree and start configuration test * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestCreateDMHslToTree001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestCreateDMHslToTree001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_CREATE_DM_HSL_TO_TREE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_CREATE_DM_HSL_TO_TREE_001, HDF_MSG_RESULT_DEFAULT}; printf("HdfConfigTest enter\n\r"); EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -111,9 +107,9 @@ HWTEST_F(HdfConfigTest, HslTestCreateDMHslToTree001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -123,9 +119,9 @@ HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -135,9 +131,9 @@ HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -147,9 +143,9 @@ HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -159,9 +155,9 @@ HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -171,9 +167,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -183,9 +179,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -195,9 +191,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -207,9 +203,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8ArraySuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8ArraySuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -219,9 +215,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8ArraySuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -231,9 +227,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -243,9 +239,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -255,9 +251,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -268,9 +264,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -280,9 +276,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16ArraySuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16ArraySuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -292,9 +288,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16ArraySuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -304,9 +300,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -316,9 +312,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -328,9 +324,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -341,9 +337,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -353,9 +349,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32ArraySuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32ArraySuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -365,9 +361,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32ArraySuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -377,9 +373,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -389,9 +385,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -401,9 +397,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -414,9 +410,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -426,9 +422,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64ArraySuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64ArraySuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -438,9 +434,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64ArraySuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -450,9 +446,9 @@ HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetElemNumSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetElemNumSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -462,9 +458,9 @@ HWTEST_F(HdfConfigTest, HslTestGetElemNumSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetElemNumFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetElemNumFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -474,9 +470,9 @@ HWTEST_F(HdfConfigTest, HslTestGetElemNumFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetChildNodeSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetChildNodeSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -486,9 +482,9 @@ HWTEST_F(HdfConfigTest, HslTestGetChildNodeSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetChildNodeFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetChildNodeFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -498,9 +494,9 @@ HWTEST_F(HdfConfigTest, HslTestGetChildNodeFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -510,9 +506,9 @@ HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -522,9 +518,9 @@ HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetStringSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetStringSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -534,9 +530,9 @@ HWTEST_F(HdfConfigTest, HslTestGetStringSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetStringFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetStringFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -546,9 +542,9 @@ HWTEST_F(HdfConfigTest, HslTestGetStringFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -559,9 +555,9 @@ HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -571,9 +567,9 @@ HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemFail001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefSuccess001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefSuccess001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_001, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_001, HDF_MSG_RESULT_DEFAULT}; EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } @@ -583,9 +579,9 @@ HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefSuccess001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000DQ0TB */ -HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefFail001, TestSize.Level1) +HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefFail001, TestSize.Level0) { - struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_002, HDF_MSG_RESUL_DEFALUT}; + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_002, HDF_MSG_RESULT_DEFAULT}; printf("HdfConfigTest last enter\n\r"); EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); } diff --git a/ability/sbuf/include/hdf_sbuf.h b/ability/sbuf/include/hdf_sbuf.h index 6fd3bd6c..29ed7006 100644 --- a/ability/sbuf/include/hdf_sbuf.h +++ b/ability/sbuf/include/hdf_sbuf.h @@ -9,10 +9,11 @@ * @addtogroup Core * @{ * - * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * @brief Provides functions to use the OpenHarmony Driver Foundation (HDF). * - * The HDF implements driver framework capabilities such as driver loading, service management, - * and driver message model. You can develop drivers based on the HDF. + * The HDF implements driver framework capabilities such as driver loading, service management, driver message model, + * and power management. + * You can develop drivers based on the HDF. * * @since 1.0 */ @@ -20,8 +21,8 @@ /** * @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. + * @brief Declares functions related to the HDF SBUF. The HDF provides data serialization and deserialization + * capabilities for data transmission between user-space applications and kernel-space drivers. * * @since 1.0 */ @@ -33,19 +34,24 @@ #ifdef __cplusplus extern "C" { +#else +typedef uint16_t char16_t; #endif /* __cplusplus */ +struct HdfSBuf; +struct HdfSbufImpl; +struct HdfRemoteService; + /** - * @brief Defines a HdfSBuf. + * @brief Enumerates HDF SBUF types. * * @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 */ +enum HdfSbufType { + SBUF_RAW = 0, /* SBUF used for communication between the user space and the kernel space */ + SBUF_IPC, /* SBUF used for inter-process communication (IPC) */ + SBUF_IPC_HW, /* Reserved for extension */ + SBUF_TYPE_MAX, /* Maximum value of the SBUF type */ }; /** @@ -60,6 +66,18 @@ struct HdfSBuf { */ bool HdfSbufWriteBuffer(struct HdfSBuf *sbuf, const void *data, uint32_t writeSize); +/** + * @brief Writes unpadded data to a SBuf. You can call {@link HdfSbufReadUnpadBuffer} to read the unpadded data. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param data Indicates the pointer to the data to write. The value cannot be a null pointer. + * @param writeSize Indicates the size of the data to write. The value cannot be 0. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteUnpadBuffer(struct HdfSBuf *sbuf, const uint8_t *data, uint32_t writeSize); + /** * @brief Writes a 64-bit unsigned integer to a SBuf. * @@ -159,13 +177,133 @@ bool HdfSbufWriteInt8(struct HdfSBuf *sbuf, int8_t value); */ bool HdfSbufWriteString(struct HdfSBuf *sbuf, const char *value); +/** + * @brief Writes a wide character string to a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the wide character string to write. + * @param size Indicates the size of the wide character string to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteString16(struct HdfSBuf *sbuf, const char16_t *value, uint32_t size); + +/** + * @brief Writes a floating-point number to a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the floating-point number to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteFloat(struct HdfSBuf *sbuf, float value); + +/** + * @brief Writes a double-precision floating-point number to a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the double-precision floating-point number to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteDouble(struct HdfSBuf *sbuf, double value); + +/** + * @brief Writes a file descriptor to a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param fd Indicates the file descriptor to write. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufWriteFileDescriptor(struct HdfSBuf *sbuf, int fd); + +/** + * @brief Writes an IPC service to a SBuf. The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param service Indicates the pointer to the IPC service to write. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t HdfSBufWriteRemoteService(struct HdfSBuf *sbuf, const struct HdfRemoteService *service); + +/** + * @brief Reads an IPC service from a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the pointer to the IPC service object if the operation is successful; + * returns a null pointer otherwise. + * + * @since 1.0 + */ +struct HdfRemoteService *HdfSBufReadRemoteService(struct HdfSBuf *sbuf); + +/** + * @brief Reads a file descriptor from a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns a valid file descriptor if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfSbufReadFileDescriptor(struct HdfSBuf *sbuf); + +/** + * @brief Reads a double-precision floating-point number from a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the double-precision floating-point number read, + * which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadDouble(struct HdfSBuf *sbuf, double *value); + +/** + * @brief Reads a floating-point number from a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param value Indicates the pointer to the floating-point number read, which is requested by the caller. + * @return Returns true if the operation is successful; returns false otherwise. + * + * @since 1.0 + */ +bool HdfSbufReadFloat(struct HdfSBuf *sbuf, float *value); + +/** + * @brief Reads a wide character string from a SBuf. + * The SBUF of the SBUF_RAW type does not support this function. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the pointer to the wide character string if the operation is successful; + * returns a null pointer otherwise. + * + * @since 1.0 + */ +const char16_t *HdfSBufReadString16(struct HdfSBuf *sbuf); + /** * @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. + * 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. * @@ -173,6 +311,17 @@ bool HdfSbufWriteString(struct HdfSBuf *sbuf, const char *value); */ bool HdfSbufReadBuffer(struct HdfSBuf *sbuf, const void **data, uint32_t *readSize); +/** + * @brief Reads unpadded data from a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param length Indicates the length of the data to read. + * @return Returns the pointer to the unpadded data if the operation is successful; returns a null pointer otherwise. + * + * @since 1.0 + */ +const uint8_t *HdfSbufReadUnpadBuffer(struct HdfSBuf *sbuf, size_t length); + /** * @brief Reads a 64-bit unsigned integer from a SBuf. * @@ -273,10 +422,11 @@ bool HdfSbufReadInt8(struct HdfSBuf *sbuf, int8_t *value); const char *HdfSbufReadString(struct HdfSBuf *sbuf); /** - * @brief Obtains the pointer to the data stored in aSBuf. + * @brief Obtains the pointer to the data stored in a SBuf. * * @param sbuf Indicates the pointer to the target SBuf. - * @return Returns the pointer to the data stored in the target SBuf. + * @return Returns the pointer to the data stored in the target SBuf if the operation is successful; + * returns a null pointer otherwise. * * @since 1.0 */ @@ -296,6 +446,7 @@ void HdfSbufFlush(struct HdfSBuf *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); @@ -310,10 +461,20 @@ size_t HdfSbufGetCapacity(const struct HdfSBuf *sbuf); */ size_t HdfSbufGetDataSize(const struct HdfSBuf *sbuf); +/** + * @brief Sets the data size of a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @param size Indicates the data size to set, which cannot exceed the size obtained via {@link HdfSbufGetDataSize}. + * + * @since 1.0 + */ +void HdfSbufSetDataSize(struct HdfSBuf *sbuf, size_t size); + /** * @brief Obtains a SBuf instance. * - * @param capacity Indicates the initial capacity of theSBuf. + * @param capacity Indicates the initial capacity of the SBuf. * @return Returns the SBuf instance. * * @since 1.0 @@ -343,9 +504,9 @@ struct HdfSBuf *HdfSBufObtainDefaultSize(void); struct HdfSBuf *HdfSBufBind(uintptr_t base, size_t size); /** - * @brief Releases a SBuf . + * @brief Releases a SBuf. * - * @param sbuf Indicates the pointer to the SBuf to release. + * @param sbuf Indicates the pointer to the target SBuf. * * @since 1.0 */ @@ -383,6 +544,62 @@ struct HdfSBuf *HdfSBufCopy(const struct HdfSBuf *sbuf); */ void HdfSbufTransDataOwnership(struct HdfSBuf *sbuf); +/** + * @brief Obtains a SBuf instance of a specified type. + * + * @param type Indicates the SBUF type, which is defined in {@link HdfSbufType}. + * @return Returns the SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufTypedObtain(uint32_t type); + +/** + * @brief Obtains a SBuf instance of a specified type based on the implementation of an existing SBuf. + * + * @param type Indicates the SBUF type, which is defined in {@link HdfSbufType}. + * @param impl Indicates the pointer to the implementation of an existing SBuf. + * @return Returns the new SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufTypedObtainInplace(uint32_t type, struct HdfSbufImpl *impl); + +/** + * @brief Obtains a SBuf instance of a specified type with the given initial capacity. + * + * @param type Indicates the SBUF type, which is defined in {@link HdfSbufType}. + * @param capacity Indicates the initial capacity of the SBuf. + * @return Returns the new SBuf instance. + * + * @since 1.0 + */ +struct HdfSBuf *HdfSBufTypedObtainCapacity(uint32_t type, size_t capacity); + +/** + * @brief Creates a SBuf instance of a specified type 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 type Indicates the SBUF type, which is defined in {@link HdfSbufType}. + * @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 *HdfSBufTypedBind(uint32_t type, uintptr_t base, size_t size); + +/** + * @brief Obtains the implementation of a SBuf. + * + * @param sbuf Indicates the pointer to the target SBuf. + * @return Returns the pointer to the implementation of the SBuf. + * + * @since 1.0 + */ +struct HdfSbufImpl *HdfSbufGetImpl(struct HdfSBuf *sbuf); + #ifdef __cplusplus } #endif /* __cplusplus */ diff --git a/ability/sbuf/include/hdf_sbuf_impl.h b/ability/sbuf/include/hdf_sbuf_impl.h new file mode 100644 index 00000000..4b7906ad --- /dev/null +++ b/ability/sbuf/include/hdf_sbuf_impl.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_SBU_IMPL_H +#define HDF_SBU_IMPL_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfSbufConstructor { + struct HdfSbufImpl *(*obtain)(size_t capacity); + struct HdfSbufImpl *(*bind)(uintptr_t base, size_t size); +}; + +struct HdfRemoteService; + +struct HdfSbufImpl { + bool (*writeBuffer)(struct HdfSbufImpl *sbuf, const uint8_t *data, uint32_t writeSize); + bool (*writeUnpadBuffer)(struct HdfSbufImpl *sbuf, const uint8_t *data, uint32_t writeSize); + bool (*writeUint64)(struct HdfSbufImpl *sbuf, uint64_t value); + bool (*writeUint32)(struct HdfSbufImpl *sbuf, uint32_t value); + bool (*writeUint16)(struct HdfSbufImpl *sbuf, uint16_t value); + bool (*writeUint8)(struct HdfSbufImpl *sbuf, uint8_t value); + bool (*writeInt64)(struct HdfSbufImpl *sbuf, int64_t value); + bool (*writeInt32)(struct HdfSbufImpl *sbuf, int32_t value); + bool (*writeInt16)(struct HdfSbufImpl *sbuf, int16_t value); + bool (*writeInt8)(struct HdfSbufImpl *sbuf, int8_t value); + bool (*writeString)(struct HdfSbufImpl *sbuf, const char *value); + bool (*writeFileDescriptor)(struct HdfSbufImpl *sbuf, int fd); + bool (*writeFloat)(struct HdfSbufImpl *sbuf, float value); + bool (*writeDouble)(struct HdfSbufImpl *sbuf, double value); + bool (*readDouble)(struct HdfSbufImpl *sbuf, double *value); + bool (*readFloat)(struct HdfSbufImpl *sbuf, float *value); + int (*readFileDescriptor)(struct HdfSbufImpl *sbuf); + bool (*writeString16)(struct HdfSbufImpl *sbuf, const char16_t *value, uint32_t size); + bool (*readBuffer)(struct HdfSbufImpl *sbuf, const uint8_t **data, uint32_t *readSize); + const uint8_t *(*readUnpadBuffer)(struct HdfSbufImpl *sbuf, size_t length); + bool (*readUint64)(struct HdfSbufImpl *sbuf, uint64_t *value); + bool (*readUint32)(struct HdfSbufImpl *sbuf, uint32_t *value); + bool (*readUint16)(struct HdfSbufImpl *sbuf, uint16_t *value); + bool (*readUint8)(struct HdfSbufImpl *sbuf, uint8_t *value); + bool (*readInt64)(struct HdfSbufImpl *sbuf, int64_t *value); + bool (*readInt32)(struct HdfSbufImpl *sbuf, int32_t *value); + bool (*readInt16)(struct HdfSbufImpl *sbuf, int16_t *value); + bool (*readInt8)(struct HdfSbufImpl *sbuf, int8_t *value); + const char *(*readString)(struct HdfSbufImpl *sbuf); + const char16_t *(*readString16)(struct HdfSbufImpl *sbuf); + int32_t (*writeRemoteService)(struct HdfSbufImpl *sbuf, const struct HdfRemoteService *service); + struct HdfRemoteService *(*readRemoteService)(struct HdfSbufImpl *sbuf); + const uint8_t *(*getData)(const struct HdfSbufImpl *sbuf); + void (*flush)(struct HdfSbufImpl *sbuf); + size_t (*getCapacity)(const struct HdfSbufImpl *sbuf); + size_t (*getDataSize)(const struct HdfSbufImpl *sbuf); + void (*setDataSize)(struct HdfSbufImpl *sbuf, size_t size); + void (*recycle)(struct HdfSbufImpl *sbuf); + struct HdfSbufImpl *(*move)(struct HdfSbufImpl *sbuf); + struct HdfSbufImpl *(*copy)(const struct HdfSbufImpl *sbuf); + void (*transDataOwnership)(struct HdfSbufImpl *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 index 60341b0d..9aea25fc 100644 --- a/ability/sbuf/src/hdf_sbuf.c +++ b/ability/sbuf/src/hdf_sbuf.c @@ -6,459 +6,451 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include "securec.h" -#include "osal_mem.h" -#include "hdf_log.h" #include "hdf_sbuf.h" +#include "hdf_log.h" +#include "hdf_sbuf_impl.h" +#include "osal_mem.h" -#define HDF_SBUF_GROW_SIZE_DEFAULT 256 -#define HDF_SBUF_MAX_SIZE (512 * 1024) // 512kB -#define HDF_SBUF_ALIGN 4 +#define HDF_SBUF_DEFAULT_SIZE 256 +#define HDF_SBUF_IMPL_CHECK_RETURN(sbuf, api, retCode) \ + do { \ + if (sbuf == NULL || sbuf->impl == NULL) { \ + HDF_LOGE("%s: invalid sbuf object", __func__); \ + return retCode; \ + } \ + if (sbuf->impl->api == NULL) { \ + HDF_LOGE(#api " is not support on %d sbuf", sbuf->type); \ + return retCode; \ + } \ + } while (0) -#ifndef INT16_MAX -#ifdef S16_MAX -#define INT16_MAX S16_MAX -#else -#define INT16_MAX 32767 -#endif // !S16_MAX -#endif // INT16_MAX +#define HDF_SBUF_IMPL_CHECK_RETURN_VOID(sbuf, api) \ + do { \ + if (sbuf == NULL || sbuf->impl == NULL) { \ + HDF_LOGE("%s: invalid sbuf object", __func__); \ + return; \ + } \ + if (sbuf->impl->api == NULL) { \ + HDF_LOGE(#api " is not support on %d sbuf", sbuf->type); \ + return; \ + } \ + } while (0) -static inline size_t HdfSbufGetAlignSize(size_t size) +struct HdfSBuf { + struct HdfSbufImpl *impl; + uint32_t type; +}; + +struct HdfSbufImpl *SbufObtainRaw(size_t capacity); +struct HdfSbufImpl *SbufBindRaw(uintptr_t base, size_t size); +struct HdfSbufImpl *SbufObtainIpc(size_t capacity) __attribute__((weak)); +struct HdfSbufImpl *SbufBindIpc(uintptr_t base, size_t size) __attribute__((weak)); +struct HdfSbufImpl *SbufObtainIpcHw(size_t capacity) __attribute__((weak)); +struct HdfSbufImpl *SbufBindRawIpcHw(uintptr_t base, size_t size) __attribute__((weak)); + +static const struct HdfSbufConstructor g_sbufConstructorMap[SBUF_TYPE_MAX] = { + [SBUF_RAW] = { + .obtain = SbufObtainRaw, + .bind = SbufBindRaw, + }, + [SBUF_IPC] = { + .obtain = SbufObtainIpc, + .bind = SbufBindIpc, + }, + [SBUF_IPC_HW] = { + .obtain = SbufObtainIpcHw, + .bind = SbufBindRawIpcHw, + }, +}; + +static const struct HdfSbufConstructor *HdfSbufConstructorGet(uint32_t type) { - 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; + if (type >= SBUF_TYPE_MAX) { + return NULL; } - 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; + return &g_sbufConstructorMap[type]; } 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; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, getData, NULL); + return (uint8_t *)sbuf->impl->getData(sbuf->impl); } void HdfSbufFlush(struct HdfSBuf *sbuf) { - if (sbuf != NULL) { - sbuf->readPos = 0; - sbuf->writePos = 0; - } + HDF_SBUF_IMPL_CHECK_RETURN_VOID(sbuf, getData); + sbuf->impl->flush(sbuf->impl); } size_t HdfSbufGetCapacity(const struct HdfSBuf *sbuf) { - return (sbuf != NULL) ? sbuf->capacity : 0; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, getCapacity, HDF_FAILURE); + return (sbuf != NULL && sbuf->impl != NULL) ? sbuf->impl->getCapacity(sbuf->impl) : 0; } size_t HdfSbufGetDataSize(const struct HdfSBuf *sbuf) { - return (sbuf != NULL) ? sbuf->writePos : 0; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, getDataSize, HDF_FAILURE); + return sbuf->impl->getDataSize(sbuf->impl); } -static bool HdfSbufGrow(struct HdfSBuf *sbuf, uint32_t growSize) +void HdfSbufSetDataSize(struct HdfSBuf *sbuf, size_t size) { - 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 (sbuf->data != NULL) { - 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 || sbuf->data == 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 || sbuf->data == 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; + HDF_SBUF_IMPL_CHECK_RETURN_VOID(sbuf, setDataSize); + sbuf->impl->setDataSize(sbuf->impl, size); } 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; - } + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, getCapacity, false); + return sbuf->impl->writeBuffer(sbuf->impl, (const uint8_t *)data, writeSize); +} + +bool HdfSbufWriteUnpadBuffer(struct HdfSBuf *sbuf, const uint8_t *data, uint32_t writeSize) +{ 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; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeUnpadBuffer, false); + return sbuf->impl->writeUnpadBuffer(sbuf->impl, data, writeSize); +} + +const uint8_t *HdfSbufReadUnpadBuffer(struct HdfSBuf *sbuf, size_t length) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readUnpadBuffer, false); + return sbuf->impl->readUnpadBuffer(sbuf->impl, length); } bool HdfSbufReadBuffer(struct HdfSBuf *sbuf, const void **data, uint32_t *readSize) { - if (sbuf == NULL || sbuf->data == 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; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readBuffer, false); + return sbuf->impl->readBuffer(sbuf->impl, (const uint8_t **)data, readSize); } bool HdfSbufWriteUint64(struct HdfSBuf *sbuf, uint64_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeUint64, false); + return sbuf->impl->writeUint64(sbuf->impl, value); } bool HdfSbufWriteUint32(struct HdfSBuf *sbuf, uint32_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeUint32, false); + return sbuf->impl->writeUint32(sbuf->impl, value); } bool HdfSbufWriteUint16(struct HdfSBuf *sbuf, uint16_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeUint16, false); + return sbuf->impl->writeUint16(sbuf->impl, value); } bool HdfSbufWriteUint8(struct HdfSBuf *sbuf, uint8_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeUint8, false); + return sbuf->impl->writeUint8(sbuf->impl, value); } bool HdfSbufWriteInt64(struct HdfSBuf *sbuf, int64_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeInt64, false); + return sbuf->impl->writeInt64(sbuf->impl, value); } bool HdfSbufWriteInt32(struct HdfSBuf *sbuf, int32_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeInt32, false); + return sbuf->impl->writeInt32(sbuf->impl, value); } bool HdfSbufWriteInt16(struct HdfSBuf *sbuf, int16_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeInt16, false); + return sbuf->impl->writeInt16(sbuf->impl, value); } bool HdfSbufWriteInt8(struct HdfSBuf *sbuf, int8_t value) { - return HdfSbufWrite(sbuf, (uint8_t *)(&value), sizeof(value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeInt8, false); + return sbuf->impl->writeInt8(sbuf->impl, value); } bool HdfSbufWriteString(struct HdfSBuf *sbuf, const char *value) { - if (sbuf == NULL) { - HDF_LOGE("%s:input null", __func__); - return false; - } + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeString, false); + return sbuf->impl->writeString(sbuf->impl, value); +} - return HdfSbufWriteBuffer(sbuf, value, value ? (strlen(value) + 1) : 0); +bool HdfSbufWriteString16(struct HdfSBuf *sbuf, const char16_t *value, uint32_t size) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeString16, false); + return sbuf->impl->writeString16(sbuf->impl, value, size); } bool HdfSbufReadUint64(struct HdfSBuf *sbuf, uint64_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readUint64, false); + return sbuf->impl->readUint64(sbuf->impl, value); } bool HdfSbufReadUint32(struct HdfSBuf *sbuf, uint32_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readUint32, false); + return sbuf->impl->readUint32(sbuf->impl, value); } bool HdfSbufReadUint16(struct HdfSBuf *sbuf, uint16_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readUint16, false); + return sbuf->impl->readUint16(sbuf->impl, value); } bool HdfSbufReadUint8(struct HdfSBuf *sbuf, uint8_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readUint8, false); + return sbuf->impl->readUint8(sbuf->impl, value); } bool HdfSbufReadInt64(struct HdfSBuf *sbuf, int64_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readInt64, false); + return sbuf->impl->readInt64(sbuf->impl, value); } bool HdfSbufReadInt32(struct HdfSBuf *sbuf, int32_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readInt32, false); + return sbuf->impl->readInt32(sbuf->impl, value); } bool HdfSbufReadInt16(struct HdfSBuf *sbuf, int16_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readInt16, false); + return sbuf->impl->readInt16(sbuf->impl, value); } bool HdfSbufReadInt8(struct HdfSBuf *sbuf, int8_t *value) { - return HdfSbufRead(sbuf, (uint8_t *)(value), sizeof(*value)); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readInt8, false); + return sbuf->impl->readInt8(sbuf->impl, value); } const char *HdfSbufReadString(struct HdfSBuf *sbuf) { - if (sbuf == NULL || sbuf->data == 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; + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readString, false); + return sbuf->impl->readString(sbuf->impl); } -struct HdfSBuf *HdfSBufObtainDefaultSize() +bool HdfSBufWriteString16(struct HdfSBuf *sbuf, const char16_t *value, uint32_t size) { - return HdfSBufObtain(HDF_SBUF_GROW_SIZE_DEFAULT); + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeString16, false); + return sbuf->impl->writeString16(sbuf->impl, value, size); +} + +const char16_t *HdfSBufReadString16(struct HdfSBuf *sbuf) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readString16, false); + return sbuf->impl->readString16(sbuf->impl); +} + +int32_t HdfSBufWriteRemoteService(struct HdfSBuf *sbuf, const struct HdfRemoteService *service) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeRemoteService, false); + return sbuf->impl->writeRemoteService(sbuf->impl, service); +} + +struct HdfRemoteService *HdfSBufReadRemoteService(struct HdfSBuf *sbuf) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readRemoteService, false); + return sbuf->impl->readRemoteService(sbuf->impl); +} + +bool HdfSbufWriteFloat(struct HdfSBuf *sbuf, float data) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeFloat, false); + return sbuf->impl->writeFloat(sbuf->impl, data); +} + +bool HdfSbufWriteDouble(struct HdfSBuf *sbuf, double data) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeDouble, false); + return sbuf->impl->writeDouble(sbuf->impl, data); +} + +bool HdfSbufWriteFileDescriptor(struct HdfSBuf *sbuf, int fd) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, writeFileDescriptor, false); + return sbuf->impl->writeFileDescriptor(sbuf->impl, fd); +} + +int HdfSbufReadFileDescriptor(struct HdfSBuf *sbuf) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readFileDescriptor, false); + return sbuf->impl->readFileDescriptor(sbuf->impl); +} + +bool HdfSbufReadDouble(struct HdfSBuf *sbuf, double *data) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readDouble, false); + return sbuf->impl->readDouble(sbuf->impl, data); +} + +bool HdfSbufReadFloat(struct HdfSBuf *sbuf, float *data) +{ + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, readFloat, false); + return sbuf->impl->readFloat(sbuf->impl, data); +} + +struct HdfSBuf *HdfSBufTypedObtainCapacity(uint32_t type, size_t capacity) +{ + const struct HdfSbufConstructor *constructor = HdfSbufConstructorGet(type); + if (constructor == NULL) { + HDF_LOGE("sbuf constructor %d not implement", type); + return NULL; + } + if (constructor->obtain == NULL) { + HDF_LOGE("sbuf constructor %d obtain method not implement", type); + return NULL; + } + + struct HdfSBuf *sbuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (sbuf == NULL) { + HDF_LOGE("instance sbuf failure"); + return NULL; + } + + sbuf->impl = constructor->obtain(capacity); + if (sbuf->impl == NULL) { + OsalMemFree(sbuf); + HDF_LOGE("sbuf obtain fail, size=%u", (uint32_t)capacity); + return NULL; + } + sbuf->type = type; + return sbuf; +} + +struct HdfSBuf *HdfSBufTypedObtainInplace(uint32_t type, struct HdfSbufImpl *impl) +{ + if (type >= SBUF_TYPE_MAX || impl == NULL) { + return NULL; + } + + struct HdfSBuf *sbuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (sbuf == NULL) { + HDF_LOGE("obtain in-place sbuf failure"); + return NULL; + } + + sbuf->impl = impl; + sbuf->type = type; + return sbuf; +} + +struct HdfSBuf *HdfSBufTypedObtain(uint32_t type) +{ + return HdfSBufTypedObtainCapacity(type, HDF_SBUF_DEFAULT_SIZE); +} + +struct HdfSBuf *HdfSBufTypedBind(uint32_t type, uintptr_t base, size_t size) +{ + const struct HdfSbufConstructor *constructor = HdfSbufConstructorGet(type); + if (constructor == NULL) { + HDF_LOGE("sbuf constructor %d not implement", type); + return NULL; + } + + if (constructor->bind == NULL) { + HDF_LOGE("sbuf constructor %d bind method not implement", type); + return NULL; + } + + struct HdfSBuf *sbuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (sbuf == NULL) { + HDF_LOGE("instance sbuf failure"); + return NULL; + } + + sbuf->impl = constructor->bind(base, size); + if (sbuf->impl == NULL) { + OsalMemFree(sbuf); + HDF_LOGE("sbuf bind fail"); + return NULL; + } + sbuf->type = type; + return sbuf; } 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; - } + return HdfSBufTypedObtainCapacity(SBUF_RAW, capacity); +} - 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 *HdfSBufObtainDefaultSize() +{ + return HdfSBufObtain(HDF_SBUF_DEFAULT_SIZE); } struct HdfSBuf *HdfSBufBind(uintptr_t base, size_t size) { - if (base == 0 || size == 0) { - return NULL; - } - /* 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; + return HdfSBufTypedBind(SBUF_RAW, base, size); } struct HdfSBuf *HdfSBufCopy(const struct HdfSBuf *sbuf) { - if (sbuf == NULL || sbuf->data == NULL) { + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, copy, NULL); + struct HdfSBuf *newBuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (newBuf == NULL) { return NULL; } - - struct HdfSBuf *new = HdfSBufObtain(sbuf->capacity); - if (new == NULL) { + newBuf->impl = sbuf->impl->copy(sbuf->impl); + if (newBuf->impl == NULL) { + OsalMemFree(newBuf); return NULL; } - new->capacity = sbuf->capacity; - new->readPos = 0; - new->writePos = sbuf->writePos; - if (memcpy_s(new->data, new->capacity, sbuf->data, sbuf->writePos) != EOK) { - HdfSBufRecycle(new); - return NULL; - } - - return new; + newBuf->type = sbuf->type; + return newBuf; } struct HdfSBuf *HdfSBufMove(struct HdfSBuf *sbuf) { - if (sbuf == NULL || sbuf->isBind) { + HDF_SBUF_IMPL_CHECK_RETURN(sbuf, move, NULL); + struct HdfSBuf *newBuf = (struct HdfSBuf *)OsalMemAlloc(sizeof(struct HdfSBuf)); + if (newBuf == NULL) { return NULL; } - - struct HdfSBuf *new = OsalMemCalloc(sizeof(struct HdfSBuf)); - if (new == NULL) { + newBuf->impl = sbuf->impl->move(sbuf->impl); + if (newBuf->impl == NULL) { + OsalMemFree(newBuf); 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; + return newBuf; } void HdfSbufTransDataOwnership(struct HdfSBuf *sbuf) { - if (sbuf == NULL) { - return; - } - - sbuf->isBind = false; + HDF_SBUF_IMPL_CHECK_RETURN_VOID(sbuf, transDataOwnership); + sbuf->impl->transDataOwnership(sbuf->impl); } void HdfSBufRecycle(struct HdfSBuf *sbuf) { if (sbuf != NULL) { - if (sbuf->data != NULL && !sbuf->isBind) { - OsalMemFree(sbuf->data); + if (sbuf->impl != NULL && sbuf->impl->recycle != NULL) { + sbuf->impl->recycle(sbuf->impl); + sbuf->impl = NULL; } OsalMemFree(sbuf); } } + +struct HdfSbufImpl *HdfSbufGetImpl(struct HdfSBuf *sbuf) +{ + if (sbuf != NULL) { + return sbuf->impl; + } + + return NULL; +} \ No newline at end of file diff --git a/ability/sbuf/src/hdf_sbuf_impl_raw.c b/ability/sbuf/src/hdf_sbuf_impl_raw.c new file mode 100644 index 00000000..051eacb4 --- /dev/null +++ b/ability/sbuf/src/hdf_sbuf_impl_raw.c @@ -0,0 +1,553 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_log.h" +#include "hdf_sbuf.h" +#include "hdf_sbuf_impl.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_SBUF_GROW_SIZE_DEFAULT 256 +#define HDF_SBUF_MAX_SIZE (512 * 1024) // 512KB +#define HDF_SBUF_ALIGN 4 + +#ifndef INT16_MAX +#ifdef S16_MAX +#define INT16_MAX S16_MAX +#else +#define INT16_MAX 32767 +#endif // !S16_MAX +#endif // INT16_MAX + +struct HdfSBufRaw { + struct HdfSbufImpl infImpl; + size_t writePos; /**< Current write position */ + size_t readPos; /**< Current read position */ + size_t capacity; /**< Storage capacity, 512 KB at most. */ + uint8_t *data; /**< Pointer to data storage */ + bool isBind; /**< Whether to bind the externally transferred pointer to data storage */ +}; + +#define SBUF_RAW_CAST(impl) (struct HdfSBufRaw *)(impl) + +static struct HdfSBufRaw *SbufRawImplNewInstance(size_t capacity); +static void SbufInterfaceAssign(struct HdfSbufImpl *inf); + +static size_t SbufRawImplGetAlignSize(size_t size) +{ + return (size + HDF_SBUF_ALIGN - 1) & (~(HDF_SBUF_ALIGN - 1)); +} + +static void SbufRawImplRecycle(struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf != NULL) { + if (sbuf->data != NULL && !sbuf->isBind) { + OsalMemFree(sbuf->data); + } + OsalMemFree(sbuf); + } +} + +static size_t SbufRawImplGetLeftWriteSize(struct HdfSBufRaw *sbuf) +{ + return (sbuf->capacity < sbuf->writePos) ? 0 : (sbuf->capacity - sbuf->writePos); +} + +static size_t SbufRawImplGetLeftReadSize(struct HdfSBufRaw *sbuf) +{ + return (sbuf->writePos < sbuf->readPos) ? 0 : (sbuf->writePos - sbuf->readPos); +} + +static bool SbufRawImplWriteRollback(struct HdfSbufImpl *impl, uint32_t size) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL) { + return false; + } + + size_t alignSize = SbufRawImplGetAlignSize(size); + if (sbuf->writePos < alignSize) { + return false; + } + + sbuf->writePos -= alignSize; + return true; +} + +static bool SbufRawImplReadRollback(struct HdfSbufImpl *impl, uint32_t size) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL) { + return false; + } + + size_t alignSize = SbufRawImplGetAlignSize(size); + if (sbuf->readPos < alignSize) { + return false; + } + + sbuf->readPos -= alignSize; + return true; +} + +static const uint8_t *SbufRawImplGetData(const struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL) { + HDF_LOGE("The obtained data is null, and the input Sbuf is null."); + return NULL; + } + return (uint8_t *)sbuf->data; +} + +static void SbufRawImplSetDataSize(struct HdfSbufImpl *impl, size_t size) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL) { + return; + } + if (size <= sbuf->capacity) { + sbuf->readPos = 0; + sbuf->writePos = size; + } +} + +static void SbufRawImplFlush(struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf != NULL) { + sbuf->readPos = 0; + sbuf->writePos = 0; + } +} + +static size_t SbufRawImplGetCapacity(const struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + return (sbuf != NULL) ? sbuf->capacity : 0; +} + +static size_t SbufRawImplGetDataSize(const struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + return (sbuf != NULL) ? sbuf->writePos : 0; +} + +static bool SbufRawImplGrow(struct HdfSBufRaw *sbuf, uint32_t growSize) +{ + if (sbuf->isBind) { + HDF_LOGE("%s: binded sbuf oom", __func__); + return false; + } + + uint32_t newSize = SbufRawImplGetAlignSize(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 (sbuf->data != NULL) { + 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 SbufRawImplWrite(struct HdfSbufImpl *impl, const uint8_t *data, uint32_t size) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->data == NULL || data == NULL) { + return false; + } + + if (size == 0) { + return true; + } + + size_t alignSize = SbufRawImplGetAlignSize(size); + // in case of desireCapacity overflow + if (alignSize < size) { + HDF_LOGE("desireCapacity overflow"); + return false; + } + size_t writeableSize = SbufRawImplGetLeftWriteSize(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 (!SbufRawImplGrow(sbuf, growSize)) { + return false; + } + writeableSize = SbufRawImplGetLeftWriteSize(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 SbufRawImplRead(struct HdfSbufImpl *impl, uint8_t *data, uint32_t readSize) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->data == NULL || data == NULL) { + return false; + } + + if (readSize == 0) { + return true; + } + + size_t alignSize = SbufRawImplGetAlignSize(readSize); + if (alignSize > SbufRawImplGetLeftReadSize(sbuf)) { + HDF_LOGE("Read out of buffer range"); + return false; + } + + if (memcpy_s(data, readSize, sbuf->data + sbuf->readPos, readSize) != EOK) { + return false; // never hit + } + sbuf->readPos += alignSize; + return true; +} + +static bool SbufRawImplWriteUint64(struct HdfSbufImpl *impl, uint64_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteUint32(struct HdfSbufImpl *impl, uint32_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteUint16(struct HdfSbufImpl *impl, uint16_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteUint8(struct HdfSbufImpl *impl, uint8_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteInt64(struct HdfSbufImpl *impl, int64_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteInt32(struct HdfSbufImpl *impl, int32_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteInt16(struct HdfSbufImpl *impl, int16_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteInt8(struct HdfSbufImpl *impl, int8_t value) +{ + return SbufRawImplWrite(impl, (uint8_t *)(&value), sizeof(value)); +} + +static bool SbufRawImplWriteBuffer(struct HdfSbufImpl *impl, const uint8_t *data, uint32_t writeSize) +{ + if (impl == NULL) { + HDF_LOGE("Failed to write the Sbuf, invalid input params"); + return false; + } + if (data == NULL) { + return SbufRawImplWriteInt32(impl, 0); + } + + if (!SbufRawImplWriteInt32(impl, writeSize)) { + return false; + } + if (!SbufRawImplWrite(impl, data, writeSize)) { + (void)SbufRawImplWriteRollback(impl, sizeof(int32_t)); + return false; + } + + return true; +} + +static bool SbufRawImplWriteString(struct HdfSbufImpl *impl, const char *value) +{ + if (impl == NULL) { + HDF_LOGE("%s: input null", __func__); + return false; + } + + return SbufRawImplWriteBuffer(impl, (const uint8_t *)value, value ? (strlen(value) + 1) : 0); +} + +static bool SbufRawImplReadUint64(struct HdfSbufImpl *impl, uint64_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadUint32(struct HdfSbufImpl *impl, uint32_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadUint16(struct HdfSbufImpl *impl, uint16_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadUint8(struct HdfSbufImpl *impl, uint8_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadInt64(struct HdfSbufImpl *impl, int64_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadInt32(struct HdfSbufImpl *impl, int32_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadInt16(struct HdfSbufImpl *impl, int16_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadInt8(struct HdfSbufImpl *impl, int8_t *value) +{ + return SbufRawImplRead(impl, (uint8_t *)(value), sizeof(*value)); +} + +static bool SbufRawImplReadBuffer(struct HdfSbufImpl *impl, const uint8_t **data, uint32_t *readSize) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->data == NULL || data == NULL || readSize == NULL) { + HDF_LOGE("%s: input invalid", __func__); + return false; + } + + int buffSize = 0; + if (!SbufRawImplReadInt32(impl, &buffSize)) { + return false; + } + + if (buffSize == 0) { + *data = NULL; + *readSize = 0; + return true; + } + size_t alignSize = SbufRawImplGetAlignSize(buffSize); + if (alignSize > SbufRawImplGetLeftReadSize(sbuf)) { + HDF_LOGE("%s:readBuff out of range", __func__); + (void)SbufRawImplReadRollback(impl, sizeof(int32_t)); + return false; + } + + *data = sbuf->data + sbuf->readPos; + *readSize = buffSize; + sbuf->readPos += alignSize; + return true; +} + +static const char *SbufRawImplReadString(struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->data == NULL) { + HDF_LOGE("%s: input null", __func__); + return NULL; + } + /* This length contains the '\0' at the end of the string. */ + int32_t strLen = 0; + if (!SbufRawImplReadInt32(impl, &strLen) || strLen <= 0) { + return NULL; + } + size_t alignSize = SbufRawImplGetAlignSize(strLen); + if (strLen > INT16_MAX || alignSize > SbufRawImplGetLeftReadSize(sbuf)) { + (void)SbufRawImplReadRollback(impl, sizeof(int32_t)); + return NULL; + } + + char *str = (char *)(sbuf->data + sbuf->readPos); + sbuf->readPos += alignSize; + /* Set '\0' at end of the string forcibly. */ + str[strLen - 1] = '\0'; + return str; +} + +static struct HdfSbufImpl *SbufRawImplCopy(const struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->data == NULL) { + return NULL; + } + + struct HdfSBufRaw *new = SbufRawImplNewInstance(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) { + SbufRawImplRecycle(&new->infImpl); + return NULL; + } + + return &new->infImpl; +} + +static struct HdfSbufImpl *SbufRawImplMove(struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL || sbuf->isBind) { + return NULL; + } + + struct HdfSBufRaw *new = OsalMemCalloc(sizeof(struct HdfSBufRaw)); + 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; + SbufRawImplFlush(&sbuf->infImpl); + SbufInterfaceAssign(&new->infImpl); + + return &new->infImpl; +} + +static void SbufRawImplTransDataOwnership(struct HdfSbufImpl *impl) +{ + struct HdfSBufRaw *sbuf = SBUF_RAW_CAST(impl); + if (sbuf == NULL) { + return; + } + + sbuf->isBind = false; +} + +static void SbufInterfaceAssign(struct HdfSbufImpl *inf) +{ + inf->writeBuffer = SbufRawImplWriteBuffer; + inf->writeUint64 = SbufRawImplWriteUint64; + inf->writeUint32 = SbufRawImplWriteUint32; + inf->writeUint16 = SbufRawImplWriteUint16; + inf->writeUint8 = SbufRawImplWriteUint8; + inf->writeInt64 = SbufRawImplWriteInt64; + inf->writeInt32 = SbufRawImplWriteInt32; + inf->writeInt16 = SbufRawImplWriteInt16; + inf->writeInt8 = SbufRawImplWriteInt8; + inf->writeString = SbufRawImplWriteString; + inf->readBuffer = SbufRawImplReadBuffer; + inf->readUint64 = SbufRawImplReadUint64; + inf->readUint32 = SbufRawImplReadUint32; + inf->readUint16 = SbufRawImplReadUint16; + inf->readUint8 = SbufRawImplReadUint8; + inf->readInt64 = SbufRawImplReadInt64; + inf->readInt32 = SbufRawImplReadInt32; + inf->readInt16 = SbufRawImplReadInt16; + inf->readInt8 = SbufRawImplReadInt8; + inf->readString = SbufRawImplReadString; + inf->getData = SbufRawImplGetData; + inf->flush = SbufRawImplFlush; + inf->getCapacity = SbufRawImplGetCapacity; + inf->getDataSize = SbufRawImplGetDataSize; + inf->setDataSize = SbufRawImplSetDataSize; + inf->recycle = SbufRawImplRecycle; + inf->move = SbufRawImplMove; + inf->copy = SbufRawImplCopy; + inf->transDataOwnership = SbufRawImplTransDataOwnership; +} + +static struct HdfSBufRaw *SbufRawImplNewInstance(size_t capacity) +{ + if (capacity > HDF_SBUF_MAX_SIZE) { + HDF_LOGE("%s: Sbuf size exceeding max limit", __func__); + return NULL; + } + struct HdfSBufRaw *sbuf = (struct HdfSBufRaw *)OsalMemCalloc(sizeof(struct HdfSBufRaw)); + if (sbuf == NULL) { + HDF_LOGE("Sbuf instance failure"); + return NULL; + } + + sbuf->data = (uint8_t *)OsalMemCalloc(capacity); + if (sbuf->data == NULL) { + OsalMemFree(sbuf); + HDF_LOGE("sbuf obtain memory oom, size=%u", (uint32_t)capacity); + return NULL; + } + sbuf->capacity = capacity; + sbuf->writePos = 0; + sbuf->readPos = 0; + sbuf->isBind = false; + SbufInterfaceAssign(&sbuf->infImpl); + return sbuf; +} + +struct HdfSbufImpl *SbufObtainRaw(size_t capacity) +{ + struct HdfSBufRaw *sbuf = SbufRawImplNewInstance(capacity); + if (sbuf == NULL) { + return NULL; + } + return &sbuf->infImpl; +} + +struct HdfSbufImpl *SbufBindRaw(uintptr_t base, size_t size) +{ + if (base == 0 || size == 0) { + return NULL; + } + /* 4-byte alignment is required for base. */ + if ((base & 0x3) != 0) { + HDF_LOGE("Base not in 4-byte alignment"); + return NULL; + } + struct HdfSBufRaw *sbuf = (struct HdfSBufRaw *)OsalMemAlloc(sizeof(struct HdfSBufRaw)); + 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; + SbufInterfaceAssign(&sbuf->infImpl); + return &sbuf->infImpl; +} \ No newline at end of file diff --git a/core/adapter/syscall/include/hdf_syscall_adapter.h b/core/adapter/syscall/include/hdf_syscall_adapter.h index 60de08bd..cb83b3f9 100644 --- a/core/adapter/syscall/include/hdf_syscall_adapter.h +++ b/core/adapter/syscall/include/hdf_syscall_adapter.h @@ -34,8 +34,8 @@ struct HdfDevListenerThread { struct pollfd *pfds; uint16_t pfdSize; bool pollChanged; - struct DListHead *listenerListPtr; bool shouldStop; + struct DListHead *listenerListPtr; uint8_t status; }; diff --git a/core/adapter/syscall/src/hdf_devmgr_adapter.c b/core/adapter/syscall/src/hdf_devmgr_adapter.c index 1d9b37cf..5a4e63e3 100644 --- a/core/adapter/syscall/src/hdf_devmgr_adapter.c +++ b/core/adapter/syscall/src/hdf_devmgr_adapter.c @@ -20,23 +20,23 @@ int32_t HdfLoadDriverByServiceName(const char *serviceName) } struct HdfIoService *ioService = HdfIoServiceBind(DEV_MGR_NODE); if (ioService == NULL) { - HDF_LOGE("Fail to get %s service", DEV_MGR_NODE); + HDF_LOGE("failed to get %s service", DEV_MGR_NODE); return ret; } data = HdfSBufObtainDefaultSize(); if (data == NULL) { - HDF_LOGE("fail to obtain sbuf data"); + HDF_LOGE("failed to obtain sbuf data"); ret = HDF_DEV_ERR_NO_MEMORY; goto out; } if (!HdfSbufWriteString(data, serviceName)) { - HDF_LOGE("fail to write sbuf"); + HDF_LOGE("failed to write sbuf"); ret = HDF_FAILURE; goto out; } ret = ioService->dispatcher->Dispatch(&ioService->object, DEVMGR_LOAD_SERVICE, data, NULL); if (ret != HDF_SUCCESS) { - HDF_LOGE("fail to send service call"); + HDF_LOGE("failed to load khdf driver %s", serviceName); } out: HdfIoServiceRecycle(ioService); @@ -54,23 +54,23 @@ int32_t HdfGetServiceNameByDeviceClass(DeviceClass deviceClass, struct HdfSBuf * } struct HdfIoService *ioService = HdfIoServiceBind(DEV_MGR_NODE); if (ioService == NULL) { - HDF_LOGE("Fail to get %s service", DEV_MGR_NODE); + HDF_LOGE("failed to get %s service", DEV_MGR_NODE); return ret; } data = HdfSBufObtainDefaultSize(); if (data == NULL) { - HDF_LOGE("fail to obtain sbuf data"); + HDF_LOGE("failed to obtain sbuf data"); ret = HDF_DEV_ERR_NO_MEMORY; goto out; } if (!HdfSbufWriteInt32(data, deviceClass)) { - HDF_LOGE("fail to write sbuf"); + HDF_LOGE("failed to write sbuf"); ret = HDF_FAILURE; goto out; } ret = ioService->dispatcher->Dispatch(&ioService->object, DEVMGR_GET_SERVICE, data, reply); if (ret != HDF_SUCCESS) { - HDF_LOGE("fail to send service call"); + HDF_LOGE("failed to query service by class"); } out: HdfIoServiceRecycle(ioService); diff --git a/core/adapter/syscall/src/hdf_syscall_adapter.c b/core/adapter/syscall/src/hdf_syscall_adapter.c index 2848d39c..be11c63e 100644 --- a/core/adapter/syscall/src/hdf_syscall_adapter.c +++ b/core/adapter/syscall/src/hdf_syscall_adapter.c @@ -95,7 +95,7 @@ static int32_t HdfDevEventDispatchLocked(const struct HdfDevListenerThread *thre return HDF_DEV_ERR_NO_MEMORY; } - /* dispatch event to SERVICE GROUP listener */ + /* Dispatch events to the service group listener */ if (thread->listenerListPtr != NULL) { DLIST_FOR_EACH_ENTRY(listener, thread->listenerListPtr, struct HdfDevEventlistener, listNode) { if (listener->onReceive != NULL) { @@ -103,21 +103,19 @@ static int32_t HdfDevEventDispatchLocked(const struct HdfDevListenerThread *thre } else if (listener->callBack != NULL) { (void)listener->callBack(listener->priv, bwr->cmdCode, sbuf); } - HdfSbufFlush(sbuf); - sbuf->writePos = bwr->readConsumed; + HdfSbufSetDataSize(sbuf, bwr->readConsumed); } } OsalMutexLock(&adapter->mutex); - /* dispatch event to SERVICE(SyscallAdapter) listener */ + /* Dispatch events to the service (SyscallAdapter) listener */ DLIST_FOR_EACH_ENTRY(listener, &adapter->listenerList, struct HdfDevEventlistener, listNode) { if (listener->onReceive != NULL) { (void)listener->onReceive(listener, &adapter->super, bwr->cmdCode, sbuf); } else if (listener->callBack != NULL) { (void)listener->callBack(listener->priv, bwr->cmdCode, sbuf); } - HdfSbufFlush(sbuf); - sbuf->writePos = bwr->readConsumed; + HdfSbufSetDataSize(sbuf, bwr->readConsumed); } OsalMutexUnlock(&adapter->mutex); @@ -131,20 +129,20 @@ static int32_t HdfDevEventReadAndDispatch(struct HdfDevListenerThread *thread, i int32_t ret = HDF_SUCCESS; bwr.readBuffer = (uintptr_t)OsalMemAlloc(HDF_DEFAULT_BWR_READ_SIZE); - bwr.cmdCode = -1; - bwr.readConsumed = 0; - bwr.readSize = HDF_DEFAULT_BWR_READ_SIZE; if (bwr.readBuffer == (uintptr_t)NULL) { HDF_LOGE("%s: oom", __func__); return HDF_DEV_ERR_NO_MEMORY; } + bwr.cmdCode = -1; + bwr.readConsumed = 0; + bwr.readSize = HDF_DEFAULT_BWR_READ_SIZE; OsalMutexLock(&thread->mutex); struct HdfSyscallAdapter *adapter = HdfFdToAdapterLocked(thread, fd); if (adapter == NULL) { - HDF_LOGI("%s:adapter invalid\n", __func__); - OsalMSleep(1); + HDF_LOGI("%s: invalid adapter", __func__); + OsalMSleep(1); // yield to sync adapter list goto finish; } @@ -156,7 +154,9 @@ static int32_t HdfDevEventReadAndDispatch(struct HdfDevListenerThread *thread, i ret = errno; if (ret == -HDF_DEV_ERR_NORANGE) { if (HdfDevEventGrowReadBuffer(&bwr) == HDF_SUCCESS) { - continue; /* read buffer may not enough, grow read buffer and try again */ + /* read buffer may not enough, grow read buffer and try again--The read buffere is insufficient. + Expand the buffer and try again. */ + continue; } } if (ret == -HDF_DEV_ERR_NODATA) { @@ -209,14 +209,6 @@ static int32_t AssignPfds(struct HdfDevListenerThread *thread, struct pollfd **p return pfdCount; } -static void HdfDevListenerThreadFree(struct HdfDevListenerThread *thread) -{ - OsalMutexDestroy(&thread->mutex); - OsalMemFree(thread->pfds); - OsalThreadDestroy(&thread->thread); - OsalMemFree(thread); -} - #define POLL_WAIT_TIME_MS 100 static int32_t HdfDevEventListenTask(void *para) { @@ -262,8 +254,11 @@ exit: OsalMemFree(pfds); if (thread->shouldStop) { - /* exit due to async exit call, should free thread struct */ - HdfDevListenerThreadFree(thread); + /* Exit due to async call and free the thread struct. */ + OsalMutexDestroy(&thread->mutex); + OsalThreadDestroy(&thread->thread); + OsalMemFree(thread->pfds); + OsalMemFree(thread); } return HDF_SUCCESS; @@ -273,7 +268,7 @@ static int32_t HdfAdapterStartListenIoctl(int fd) { int32_t ret = ioctl(fd, HDF_LISTEN_EVENT_START, 0); if (ret) { - HDF_LOGE("%s: fail to tell drv(%d) start %d %s", __func__, fd, errno, strerror(errno)); + HDF_LOGE("%s: failed to notify drv(%d) of start %d %s", __func__, fd, errno, strerror(errno)); return HDF_ERR_IO; } @@ -284,7 +279,7 @@ static int32_t HdfAdapterStopListenIoctl(int fd) { int32_t ret = ioctl(fd, HDF_LISTEN_EVENT_STOP, 0); if (ret) { - HDF_LOGE("%s: fail to tell drv stop %d %s", __func__, errno, strerror(errno)); + HDF_LOGE("%s: failed to notify drv(%d) of stop %d %s", __func__, fd, errno, strerror(errno)); return HDF_ERR_IO; } @@ -295,7 +290,7 @@ static int32_t HdfAdapterExitListenIoctl(int fd) { int32_t ret = ioctl(fd, HDF_LISTEN_EVENT_EXIT, 0); if (ret) { - HDF_LOGE("%s: fail to tell drv report exit %d %s", __func__, errno, strerror(errno)); + HDF_LOGE("%s: failed to notify drv(%d) of exit %d %s", __func__, fd, errno, strerror(errno)); return HDF_ERR_IO; } @@ -305,13 +300,13 @@ static int32_t HdfAdapterExitListenIoctl(int fd) static int32_t HdfDevListenerThreadDoInit(struct HdfDevListenerThread *thread) { if (OsalMutexInit(&thread->mutex) != HDF_SUCCESS) { - HDF_LOGE("%s: fail to create thread lock", __func__); + HDF_LOGE("%s: failed to create thread lock", __func__); return HDF_FAILURE; } int32_t ret = OsalThreadCreate(&thread->thread, HdfDevEventListenTask, thread); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: fail to create thread", __func__); + HDF_LOGE("%s: failed to create thread", __func__); thread->status = LISTENER_UNINITED; OsalMutexDestroy(&thread->mutex); return HDF_ERR_THREAD_CREATE_FAIL; @@ -499,7 +494,7 @@ static int32_t HdfIoServiceGroupThreadStart(struct HdfSyscallAdapterGroup *group static int32_t HdfListenThreadPollAdd(struct HdfDevListenerThread *thread, struct HdfSyscallAdapter *adapter) { - /* if thread is not bind to service group, not need to do poll add */ + /* If thread is not bound to a service group, you do not need to add a poll. */ if (thread->adapterListPtr == NULL) { return HDF_SUCCESS; } @@ -529,7 +524,7 @@ static int32_t HdfListenThreadPollAdd(struct HdfDevListenerThread *thread, struc if (headAdapter != NULL) { if (ioctl(headAdapter->fd, HDF_LISTEN_EVENT_WAKEUP, 0) != 0) { - HDF_LOGE("%s: fail to wakeup drv to add poll %d %s", __func__, errno, strerror(errno)); + HDF_LOGE("%s: failed to wakeup drv to add poll %d %s", __func__, errno, strerror(errno)); thread->pfds[index].fd = SYSCALL_INVALID_FD; ret = HDF_ERR_IO; break; @@ -568,11 +563,11 @@ static void HdfListenThreadPollDel(struct HdfDevListenerThread *thread, struct } if (HdfAdapterStopListenIoctl(adapter->fd)) { - HDF_LOGE("%s: fail to stop device report %d %s", __func__, errno, strerror(errno)); + HDF_LOGE("%s: failed to stop device report %d %s", __func__, errno, strerror(errno)); } if (ioctl(adapter->fd, HDF_LISTEN_EVENT_WAKEUP, 0) != 0) { - HDF_LOGE("%s: fail to wakeup drv to del poll %d %s", __func__, errno, strerror(errno)); + HDF_LOGE("%s: failed to wakeup drv to del poll %d %s", __func__, errno, strerror(errno)); } DListRemove(&adapter->listNode); adapter->group = NULL; @@ -580,6 +575,14 @@ static void HdfListenThreadPollDel(struct HdfDevListenerThread *thread, struct OsalMutexUnlock(&thread->mutex); } +static void HdfDevListenerThreadFree(struct HdfDevListenerThread *thread) +{ + OsalMutexDestroy(&thread->mutex); + OsalMemFree(thread->pfds); + OsalThreadDestroy(&thread->thread); + OsalMemFree(thread); +} + static void HdfDevListenerThreadDestroy(struct HdfDevListenerThread *thread) { if (thread == NULL) { @@ -648,10 +651,10 @@ static int32_t HdfSyscallAdapterDispatch(struct HdfObject *object, int32_t code, wrBuf.cmdCode = code; int32_t ret = ioctl(ioService->fd, HDF_WRITE_READ, &wrBuf); if (ret < 0) { - HDF_LOGE("dispatch serv call ioctl fail %d", errno); + HDF_LOGE("Failed to dispatch serv call ioctl %d", errno); } if (reply != NULL) { - reply->writePos = wrBuf.readConsumed; + HdfSbufSetDataSize(reply, wrBuf.readConsumed); } return ret; } @@ -660,41 +663,48 @@ struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName) { struct HdfSyscallAdapter *adapter = NULL; struct HdfIoService *ioService = NULL; - char devNodePath[PATH_MAX] = {0}; - char realPath[PATH_MAX] = {0}; + char *devNodePath = NULL; + char *realPath = NULL; const char *devPath = DEV_NODE_PATH; if (access(DEV_NODE_PATH, F_OK) != 0) { devPath = DEV_PATH; } + devNodePath = OsalMemCalloc(PATH_MAX); + realPath = OsalMemCalloc(PATH_MAX); + if (devNodePath == NULL || realPath == NULL) { + HDF_LOGE("%s: out of memory", __func__); + goto out; + } + if (sprintf_s(devNodePath, PATH_MAX - 1, "%s%s", devPath, serviceName) < 0) { - HDF_LOGE("Get node path failed"); - return NULL; + HDF_LOGE("Failed to get the node path"); + goto out; } if (realpath(devNodePath, realPath) == NULL) { if (HdfLoadDriverByServiceName(serviceName) != HDF_SUCCESS) { - HDF_LOGE("%s load %s driver failed", __func__, serviceName); - return NULL; + HDF_LOGE("%s: load %s driver failed", __func__, serviceName); + goto out; } if (realpath(devNodePath, realPath) == NULL) { - HDF_LOGE("%s file name %s is invalid", __func__, devNodePath); - return NULL; + HDF_LOGE("%s: file name %s is invalid", __func__, devNodePath); + goto out; } } adapter = (struct HdfSyscallAdapter *)OsalMemCalloc(sizeof(struct HdfSyscallAdapter)); if (adapter == NULL) { - HDF_LOGE("Alloc syscall adapter failed"); - return NULL; + HDF_LOGE("Failed to allocate SyscallAdapter"); + goto out; } DListHeadInit(&adapter->listenerList); if (OsalMutexInit(&adapter->mutex)) { - HDF_LOGE("%s: create mutex fail", __func__); + HDF_LOGE("%s: Failed to create mutex", __func__); OsalMemFree(adapter); - return NULL; + goto out; } adapter->fd = open(realPath, O_RDWR); @@ -702,13 +712,16 @@ struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName) HDF_LOGE("Open file node %s failed, (%d)%s", realPath, errno, strerror(errno)); OsalMutexDestroy(&adapter->mutex); OsalMemFree(adapter); - return NULL; + goto out; } ioService = &adapter->super; static struct HdfIoDispatcher dispatch = { .Dispatch = HdfSyscallAdapterDispatch, }; ioService->dispatcher = &dispatch; +out: + OsalMemFree(devNodePath); + OsalMemFree(realPath); return ioService; } @@ -743,7 +756,7 @@ static int32_t HdfIoServiceThreadBindLocked(struct HdfSyscallAdapter *adapter) static int32_t HdfIoServiceStartListen(struct HdfSyscallAdapter *adapter) { if (HdfIoServiceThreadBindLocked(adapter) != HDF_SUCCESS) { - HDF_LOGE("%s:adapter bind thread fail", __func__); + HDF_LOGE("%s: Failed to bind a thread to SyscallAdapter", __func__); return HDF_FAILURE; } @@ -755,7 +768,7 @@ static bool AddListenerToAdapterLocked(struct HdfSyscallAdapter *adapter, struct struct HdfDevEventlistener *it = NULL; DLIST_FOR_EACH_ENTRY(it, &adapter->listenerList, struct HdfDevEventlistener, listNode) { if (it == listener) { - HDF_LOGE("add duplicate dev-event listener"); + HDF_LOGE("Add a listener for duplicate dev-event"); return false; } } @@ -770,7 +783,7 @@ int32_t HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDe } if (listener->callBack == NULL && listener->onReceive == NULL) { - HDF_LOGE("listenr onReceive func not implement"); + HDF_LOGE("Listenr onReceive func not implemented"); return HDF_ERR_INVALID_OBJECT; } @@ -784,7 +797,7 @@ int32_t HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDe } if (adapter->group != NULL) { - /* service in group, should not bind to self hold thread and try to start group thread */ + /* Do not bind any service in a service goup to its own thread or start the group thread. */ ret = HdfIoServiceGroupThreadStart(adapter->group); OsalMutexUnlock(&adapter->mutex); return ret; @@ -806,7 +819,7 @@ int32_t HdfDeviceUnregisterEventListener(struct HdfIoService *target, struct Hdf } if (listener->listNode.next == NULL || listener->listNode.prev == NULL) { - HDF_LOGE("%s:broken listener, may double unregister", __func__); + HDF_LOGE("%s: broken listener, may double unregister", __func__); return HDF_ERR_INVALID_OBJECT; } @@ -872,7 +885,7 @@ int32_t HdfIoServiceGroupRegisterListener(struct HdfIoServiceGroup *group, struc } if (listener->callBack == NULL && listener->onReceive == NULL) { - HDF_LOGE("listenr onReceive func not implement"); + HDF_LOGE("listenr onReceive func not implemented"); return HDF_ERR_INVALID_OBJECT; } struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); @@ -891,8 +904,8 @@ int32_t HdfIoServiceGroupRegisterListener(struct HdfIoServiceGroup *group, struc struct HdfDevEventlistener *it = NULL; DLIST_FOR_EACH_ENTRY(it, &adapterGroup->listenerList, struct HdfDevEventlistener, listNode) { if (it == listener) { - HDF_LOGE("add group listener failed, repeated registration"); - ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("Failed to add group listener, repeated registration"); + ret = HDF_ERR_INVALID_PARAM; goto finish; } } @@ -917,7 +930,7 @@ static int32_t GetListenerCount(struct HdfDevListenerThread *thread) OsalMutexLock(&thread->mutex); if (thread->listenerListPtr != NULL) { - DLIST_FOR_EACH_ENTRY (listener, thread->listenerListPtr, struct HdfDevEventlistener, listNode) { + DLIST_FOR_EACH_ENTRY(listener, thread->listenerListPtr, struct HdfDevEventlistener, listNode) { count++; } } diff --git a/core/adapter/vnode/src/hdf_vnode_adapter.c b/core/adapter/vnode/src/hdf_vnode_adapter.c index 0d39bd60..f1ddc1ba 100644 --- a/core/adapter/vnode/src/hdf_vnode_adapter.c +++ b/core/adapter/vnode/src/hdf_vnode_adapter.c @@ -20,7 +20,7 @@ #define HDF_LOG_TAG hdf_vnode #define VOID_DATA_SIZE 4 #define EVENT_QUEUE_MAX 100 -#define MAX_RW_SIZE (1024*1204) // 1M +#define MAX_RW_SIZE (1024 * 1204) // 1M enum HdfVNodeClientStatus { VNODE_CLIENT_RUNNING, @@ -99,7 +99,7 @@ struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName) } svcMgr = DevSvcManagerClntGetInstance(); - if (svcMgr == NULL) { + if (svcMgr == NULL || svcMgr->devSvcMgrIf == NULL) { return NULL; } deviceObject = svcMgr->devSvcMgrIf->GetObject(svcMgr->devSvcMgrIf, serviceName); @@ -146,7 +146,7 @@ static struct HdfSBuf *HdfSbufCopyFromUser(uintptr_t data, size_t size) return NULL; } if (CopyFromUser((void*)kData, (void*)data, size) != 0) { - HDF_LOGE("%s:copy from user fail", __func__); + HDF_LOGE("%s:failed to copy from user", __func__); OsalMemFree(kData); return NULL; } @@ -172,7 +172,7 @@ static int HdfSbufCopyToUser(const struct HdfSBuf *sbuf, void *dstUser, size_t d } if (CopyToUser(dstUser, HdfSbufGetData(sbuf), sbufSize) != 0) { - HDF_LOGE("%s: copy buff data fail", __func__); + HDF_LOGE("%s: failed to copy buff data", __func__); return HDF_ERR_IO; } @@ -207,7 +207,7 @@ static int HdfVNodeAdapterServCall(const struct HdfVNodeAdapterClient *client, u return HDF_ERR_INVALID_PARAM; } if (CopyFromUser(&bwr, (void*)bwrUser, sizeof(bwr)) != 0) { - HDF_LOGE("Copy from user failed"); + HDF_LOGE("copy from user failed"); return HDF_FAILURE; } if (bwr.writeSize > MAX_RW_SIZE || bwr.readSize > MAX_RW_SIZE) { @@ -216,12 +216,12 @@ static int HdfVNodeAdapterServCall(const struct HdfVNodeAdapterClient *client, u data = HdfSbufCopyFromUser(bwr.writeBuffer, bwr.writeSize); if (data == NULL) { - HDF_LOGE("Vnode adapter bind data is null"); + HDF_LOGE("vnode adapter bind data is null"); return HDF_FAILURE; } reply = HdfSBufObtainDefaultSize(); if (reply == NULL) { - HDF_LOGE("%s:oom", __func__); + HDF_LOGE("%s: oom", __func__); HdfSBufRecycle(data); return HDF_FAILURE; } @@ -235,7 +235,7 @@ static int HdfVNodeAdapterServCall(const struct HdfVNodeAdapterClient *client, u } bwr.readConsumed = HdfSbufGetDataSize(reply); if (CopyToUser(bwrUser, &bwr, sizeof(struct HdfWriteReadBuf)) != 0) { - HDF_LOGE("%s: copy bwr fail", __func__); + HDF_LOGE("%s: fail to copy bwr", __func__); ret = HDF_FAILURE; } @@ -286,7 +286,7 @@ static int HdfVNodeAdapterReadDevEvent(struct HdfVNodeAdapterClient *client, uns } if (CopyToUser(bwrUser, &bwr, sizeof(struct HdfWriteReadBuf)) != 0) { - HDF_LOGE("%s: copy bwr fail", __func__); + HDF_LOGE("%s: failed to copy bwr", __func__); ret = HDF_ERR_IO; } if (ret == HDF_SUCCESS) { @@ -461,7 +461,6 @@ static struct HdfVNodeAdapterClient *HdfNewVNodeAdapterClient(struct HdfVNodeAda client->serv = &adapter->ioService; client->status = VNODE_CLIENT_RUNNING; client->adapter = adapter; - client->eventQueueSize = 0; client->ioServiceClient.device = (struct HdfDeviceObject *)adapter->ioService.target; client->ioServiceClient.priv = NULL; client->wakeup = 0; @@ -565,26 +564,26 @@ struct HdfIoService *HdfIoServiceAdapterPublish(const char *serviceName, uint32_ }; if ((serviceName == NULL) || (mode > MAX_MODE_SIZE)) { - HDF_LOGE("Input param is invalid, mode is %x", mode); + HDF_LOGE("input param is invalid, mode is %x", mode); return NULL; } vnodeAdapter = (struct HdfVNodeAdapter *)OsalMemCalloc(sizeof(struct HdfVNodeAdapter)); if (vnodeAdapter == NULL) { - HDF_LOGE("Alloc remote service is null"); + HDF_LOGE("alloc remote service is null"); return NULL; } nodePathLength = strlen(serviceName) + strlen(DEV_NODE_PATH) + 1; vnodeAdapter->vNodePath = (char *)OsalMemCalloc(nodePathLength); if (vnodeAdapter->vNodePath == NULL) { - HDF_LOGE("Alloc vnode path is null"); + HDF_LOGE("alloc vnode path is null"); OsalMemFree(vnodeAdapter); return NULL; } if (sprintf_s(vnodeAdapter->vNodePath, nodePathLength, "%s%s", DEV_NODE_PATH, serviceName) < 0) { - HDF_LOGE("Get node path failed"); + HDF_LOGE("failed to get node path"); OsalMemFree(vnodeAdapter->vNodePath); OsalMemFree(vnodeAdapter); return NULL; @@ -602,7 +601,7 @@ struct HdfIoService *HdfIoServiceAdapterPublish(const char *serviceName, uint32_ } ret = OsalRegisterCdev(vnodeAdapter->cdev, vnodeAdapter->vNodePath, mode, vnodeAdapter); if (ret != 0) { - HDF_LOGE("register dev node %s failed, ret is: %d", vnodeAdapter->vNodePath, ret); + HDF_LOGE("failed to register dev node %s, ret is: %d", vnodeAdapter->vNodePath, ret); OsalMutexDestroy(&vnodeAdapter->mutex); goto error; } diff --git a/core/common/include/manager/devmgr_service_start.h b/core/common/include/manager/devmgr_service_start.h index 6a2d571e..8f6f675b 100644 --- a/core/common/include/manager/devmgr_service_start.h +++ b/core/common/include/manager/devmgr_service_start.h @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#ifndef DEVICE_SERVICE_START_H -#define DEVICE_SERVICE_START_H +#ifndef DEVMGR_SERVICE_START_H +#define DEVMGR_SERVICE_START_H enum { DEV_MGR_SLOW_LOAD = 0, @@ -19,4 +19,4 @@ int DeviceManagerStartStep2(void); void DeviceManagerSetQuickLoad(int isQuickLoad); int DeviceManagerIsQuickLoad(void); -#endif /* DEVICE_SERVICE_START_H */ +#endif /* DEVMGR_SERVICE_START_H */ diff --git a/core/common/src/devmgr_service_start.c b/core/common/src/devmgr_service_start.c index 143e05cc..6dbaa074 100644 --- a/core/common/src/devmgr_service_start.c +++ b/core/common/src/devmgr_service_start.c @@ -31,8 +31,7 @@ static void GetDeviceServiceNameByClass(DeviceClass deviceClass, struct HdfSBuf return; } - reply->readPos = 0; - reply->writePos = 0; + HdfSbufFlush(reply); HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); while (HdfSListIteratorHasNext(&itHost)) { hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); @@ -78,21 +77,21 @@ int DeviceManagerDispatch(struct HdfObject *stub, int code, struct HdfSBuf *data case DEVMGR_UNLOAD_SERVICE: svcName = HdfSbufReadString(data); if (svcName == NULL) { - HDF_LOGE("%s: get svc name is null", __func__); + HDF_LOGE("%s: svc name is null", __func__); break; } ret = DevSvcManagerClntUnsubscribeService(svcName); break; case DEVMGR_GET_SERVICE: if (!HdfSbufReadInt32(data, &deviceClass)) { - HDF_LOGE("%s: get deviceClass failed", __func__); + HDF_LOGE("%s: failed to get deviceClass", __func__); break; } GetDeviceServiceNameByClass(deviceClass, reply); ret = HDF_SUCCESS; break; default: - HDF_LOGE("%s: Currently, this configuration type is not supported. the type is %d", __func__, code); + HDF_LOGE("%s: unsupported configuration type: %d", __func__, code); break; } OsalMutexUnlock(&devMgrSvc->devMgrMutex); @@ -104,17 +103,17 @@ void DeviceManagerSetQuickLoad(int loadFlag) g_isQuickLoad = loadFlag; } -int DeviceManagerIsQuickLoad() +int DeviceManagerIsQuickLoad(void) { return g_isQuickLoad; } -int DeviceManagerStart() +int DeviceManagerStart(void) { struct IDevmgrService *instance = DevmgrServiceGetInstance(); if (instance == NULL || instance->StartService == NULL) { - HDF_LOGE("Device manager start failed, service instance is null!"); + HDF_LOGE("device manager start failed, service instance is null"); return HDF_FAILURE; } struct HdfIoService *ioService = HdfIoServicePublish(DEV_MGR_NODE, DEV_MGR_NODE_PERM); @@ -131,7 +130,7 @@ int DeviceManagerStart() int DeviceManagerStartStep2() { if (DeviceManagerIsQuickLoad() == DEV_MGR_SLOW_LOAD) { - HDF_LOGW("%s device manager is not set quick load!", __func__); + HDF_LOGW("%s: device manager is not set to QuickLoad mode", __func__); return HDF_SUCCESS; } struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); diff --git a/core/common/src/hdf_attribute.c b/core/common/src/hdf_attribute.c index 1d696fab..83b609fd 100644 --- a/core/common/src/hdf_attribute.c +++ b/core/common/src/hdf_attribute.c @@ -32,6 +32,7 @@ static struct DeviceResourceNode *g_hcsTreeRoot = NULL; void HdfGetBuildInConfigData(const unsigned char **data, unsigned int *size); + static bool CreateHcsToTree(void) { uint32_t length; @@ -49,7 +50,7 @@ static bool CreateHcsToTree(void) const struct DeviceResourceNode *HcsGetRootNode(void) { if ((g_hcsTreeRoot == NULL) && !CreateHcsToTree()) { - HDF_LOGE("%s failed", __func__); + HDF_LOGE("%s: failed", __func__); return NULL; } return g_hcsTreeRoot; @@ -80,12 +81,12 @@ static bool GetHostInfo(const struct DeviceResourceNode *hostNode, struct HdfHos uint16_t readNum = 0; if ((HcsGetString(hostNode, ATTR_HOST_NAME, &hostInfo->hostName, NULL) != HDF_SUCCESS) || (strcmp(hostInfo->hostName, "") == 0)) { - HDF_LOGW("%s get host name failed", __func__); + HDF_LOGW("%s: get host name failed", __func__); return false; } if ((HcsGetUint16(hostNode, ATTR_DEV_PRIORITY, &readNum, 0) != HDF_SUCCESS) || (readNum > MAX_PRIORITY_NUM)) { - HDF_LOGW("%s get host priority failed, priority is: %d", __func__, readNum); + HDF_LOGW("%s: get host priority failed, priority is: %u", __func__, readNum); return false; } hostInfo->priority = readNum; @@ -103,7 +104,7 @@ bool HdfAttributeManagerGetHostList(struct HdfSList *hostList) hdfManagerNode = GetHdfManagerNode(HcsGetRootNode()); if (hdfManagerNode == NULL) { - HDF_LOGE("%s get hdf manager node is null", __func__); + HDF_LOGE("%s: get hdf manager node is null", __func__); return false; } @@ -112,19 +113,17 @@ bool HdfAttributeManagerGetHostList(struct HdfSList *hostList) struct HdfHostInfo *hostInfo = HdfHostInfoNewInstance(); if (hostInfo == NULL) { HdfSListFlush(hostList, HdfHostInfoDelete); - HDF_LOGE("%s new hostInfo is null", __func__); + HDF_LOGE("%s: new hostInfo is null", __func__); return false; } if (!GetHostInfo(hostNode, hostInfo)) { HdfHostInfoFreeInstance(hostInfo); - hostInfo = NULL; hostNode = hostNode->sibling; continue; } hostInfo->hostId = hostId; if (!HdfSListAddOrder(hostList, &hostInfo->node, HdfHostListCompare)) { HdfHostInfoFreeInstance(hostInfo); - hostInfo = NULL; hostNode = hostNode->sibling; continue; } @@ -149,7 +148,9 @@ static const struct DeviceResourceNode *GetHostNode(const char *inHostName) const struct DeviceResourceNode *hdfManagerNode = NULL; const struct DeviceResourceNode *hostNode = NULL; const char *hostName = NULL; - + if (inHostName == NULL) { + return NULL; + } hdfManagerNode = GetHdfManagerNode(HcsGetRootNode()); if (hdfManagerNode == NULL) { return NULL; @@ -171,17 +172,17 @@ static const struct DeviceResourceNode *GetHostNode(const char *inHostName) static bool CheckDeviceInfo(const struct HdfDeviceInfo *deviceNodeInfo) { if (deviceNodeInfo->policy > SERVICE_POLICY_PRIVATE) { - HDF_LOGE("%s policy is invalid", __func__); + HDF_LOGE("%s: policy %u is invalid", __func__, deviceNodeInfo->policy); return false; } if (deviceNodeInfo->priority > MAX_PRIORITY_NUM) { - HDF_LOGE("%s priority is invalid", __func__); + HDF_LOGE("%s: priority %u is invalid", __func__, deviceNodeInfo->priority); return false; } if (deviceNodeInfo->preload > DEVICE_PRELOAD_DISABLE) { - HDF_LOGE("%s preload is invalid", __func__); + HDF_LOGE("%s: preload %u is invalid", __func__, deviceNodeInfo->preload); return false; } @@ -193,43 +194,43 @@ static bool GetDeviceNodeInfo(const struct DeviceResourceNode *deviceNode, struc uint16_t readNum = 0; const char *readString = NULL; if (HcsGetUint16(deviceNode, ATTR_DEV_POLICY, &readNum, 0) != HDF_SUCCESS) { - HDF_LOGE("%s get policy failed", __func__); + HDF_LOGE("%s: failed to get policy", __func__); return false; } deviceNodeInfo->policy = readNum; if (HcsGetUint16(deviceNode, ATTR_DEV_PRIORITY, &readNum, 0) != HDF_SUCCESS) { - HDF_LOGE("%s get priority failed", __func__); + HDF_LOGE("%s: failed to get priority", __func__); return false; } deviceNodeInfo->priority = readNum; if (HcsGetUint16(deviceNode, ATTR_DEV_PRELOAD, &readNum, 0) != HDF_SUCCESS) { - HDF_LOGE("%s get preload failed", __func__); + HDF_LOGE("%s: failed to get preload", __func__); return false; } deviceNodeInfo->preload = readNum; if (HcsGetUint16(deviceNode, ATTR_DEV_PERMISSION, &readNum, 0) != HDF_SUCCESS) { - HDF_LOGE("%s get permission failed", __func__); + HDF_LOGE("%s: failed to get permission", __func__); return false; } deviceNodeInfo->permission = readNum; if (HcsGetString(deviceNode, ATTR_DEV_MODULENAME, &readString, NULL) != HDF_SUCCESS) { - HDF_LOGE("%s get module name failed", __func__); + HDF_LOGE("%s: failed to get module name", __func__); return false; } deviceNodeInfo->moduleName = readString; if (HcsGetString(deviceNode, ATTR_DEV_SVCNAME, &readString, NULL) != HDF_SUCCESS) { - HDF_LOGE("%s get service name failed", __func__); + HDF_LOGE("%s: failed to get service name", __func__); return false; } deviceNodeInfo->svcName = readString; if (HcsGetString(deviceNode, ATTR_DEV_MATCHATTR, &readString, NULL) != HDF_SUCCESS) { - HDF_LOGE("%s get service name failed", __func__); + HDF_LOGE("%s: failed to get matchattr name", __func__); return false; } deviceNodeInfo->deviceMatchAttr = readString; @@ -260,13 +261,13 @@ struct HdfSList *HdfAttributeManagerGetDeviceList(uint16_t hostId, const char *h deviceNodeInfo->hostId = hostId; if (!GetDeviceNodeInfo(deviceNode, deviceNodeInfo)) { HdfDeviceInfoFreeInstance(deviceNodeInfo); - HDF_LOGE("%s get device failed", __func__); + HDF_LOGE("%s: failed to get device", __func__); deviceNodeInfo = NULL; deviceNode = deviceNode->sibling; continue; } if (!HdfSListAddOrder(deviceList, &deviceNodeInfo->node, HdfDeviceListCompare)) { - HDF_LOGE("%s add device %s failed", __func__, deviceNodeInfo->svcName); + HDF_LOGE("%s: failed to add device %s", __func__, deviceNodeInfo->svcName); HdfDeviceInfoFreeInstance(deviceNodeInfo); deviceNodeInfo = NULL; deviceNode = deviceNode->sibling; @@ -323,7 +324,11 @@ bool HdfDeviceListAdd(const char *moduleName, const char *serviceName) if (svcName == NULL) { break; } - strcpy(svcName, serviceName); + if (strcpy_s(svcName, strlen(serviceName) + 1, serviceName) != EOK) { + HDF_LOGE("%s: failed to copy string", __func__); + OsalMemFree(svcName); + break; + } deviceNodeInfo->svcName = svcName; HdfSListAdd(hostClnt->deviceInfos, &deviceNodeInfo->node); hostClnt->devCount++; diff --git a/core/common/src/hdf_device_node_ext.c b/core/common/src/hdf_device_node_ext.c index 493cd51e..a8143a44 100644 --- a/core/common/src/hdf_device_node_ext.c +++ b/core/common/src/hdf_device_node_ext.c @@ -24,29 +24,29 @@ static int DeviceNodeExtDispatch(struct HdfObject *stub, int code, struct HdfSBu struct HdfDeviceNode *devNode = NULL; if (stub == NULL) { - HDF_LOGE("input ioService null"); + HDF_LOGE("device ext dispatch: stub is null"); return HDF_FAILURE; } uint64_t ioClientPtr = 0; if (!HdfSbufReadUint64(reply, &ioClientPtr) || ioClientPtr == 0) { - HDF_LOGE("input ioClient null"); + HDF_LOGE("device ext dispatch: input ioClient is null"); return HDF_FAILURE; } HdfSbufFlush(reply); devNode = CONTAINER_OF(stub, struct HdfDeviceNode, deviceObject); deviceMethod = devNode->deviceObject.service; if (deviceMethod == NULL) { - HDF_LOGE("Device service interface is null"); + HDF_LOGE("device ext dispatch: device service interface is null"); return HDF_FAILURE; } deviceInfo = devNode->deviceInfo; if (deviceInfo == NULL) { - HDF_LOGE("Device deviceInfo is null"); + HDF_LOGE("device ext dispatch: device deviceInfo is null"); return HDF_FAILURE; } if (deviceInfo->policy == SERVICE_POLICY_CAPACITY) { if (deviceMethod->Dispatch == NULL) { - HDF_LOGE("Remote service dispatch is null"); + HDF_LOGE("device ext dispatch: remote service dispatch method is null"); return HDF_FAILURE; } return deviceMethod->Dispatch((struct HdfDeviceIoClient *)((uintptr_t)ioClientPtr), code, data, reply); @@ -64,7 +64,7 @@ static int DeviceNodeExtPublishService(struct HdfDeviceNode *inst, const char *s } int ret = HdfDeviceNodePublishPublicService(inst, serviceName); if (ret != HDF_SUCCESS) { - HDF_LOGE("Device publish service failed, ret is: %d", ret); + HDF_LOGE("failed to publish device service, ret is %d", ret); return HDF_FAILURE; } diff --git a/core/common/src/load_driver_entry.c b/core/common/src/load_driver_entry.c index 39e420a4..9a42ecbd 100644 --- a/core/common/src/load_driver_entry.c +++ b/core/common/src/load_driver_entry.c @@ -15,12 +15,12 @@ static struct HdfDriverEntry *HdfDriverEntryConstruct(int32_t *driverCount) int i; *driverCount = (int32_t)(((uint8_t *)(HDF_DRIVER_END()) - (uint8_t *)(HDF_DRIVER_BEGIN())) / sizeof(size_t)); if (*driverCount <= 0) { - HDF_LOGE("%s hdf get device counts failed!", __func__); + HDF_LOGE("%s: failed to hdf get device counts", __func__); return NULL; } struct HdfDriverEntry *driverEntry = OsalMemCalloc(*driverCount * sizeof(struct HdfDriverEntry)); if (driverEntry == NULL) { - HDF_LOGE("%s hdf alloc driver entry mem failed!", __func__); + HDF_LOGE("%s: failed to alloc driver entry mem", __func__); *driverCount = 0; return NULL; } @@ -36,7 +36,7 @@ struct HdfDriverEntry *HdfDriverLoaderGetDriverEntry(const struct HdfDeviceInfo { int i; if ((deviceInfo == NULL) || (deviceInfo->moduleName == NULL) || (deviceInfo->svcName == NULL)) { - HDF_LOGE("%s hdf get device entry failed, input deviceInfo is NULL!", __func__); + HDF_LOGE("%s: failed to get device entry, input deviceInfo is NULL", __func__); return NULL; } static struct HdfDriverEntry *driverEntry = NULL; @@ -44,24 +44,24 @@ struct HdfDriverEntry *HdfDriverLoaderGetDriverEntry(const struct HdfDeviceInfo if (driverEntry == NULL) { driverEntry = HdfDriverEntryConstruct(&driverCount); if (driverEntry == NULL) { - HDF_LOGE("%s driver entry construct failed!", __func__); + HDF_LOGE("%s: failed to construct driver entry", __func__); return NULL; } } for (i = 0; i < driverCount; i++) { if (driverEntry == NULL) { - HDF_LOGE("%s driver entry is null!", __func__); + HDF_LOGE("%s: driver entry is null", __func__); return NULL; } if (driverEntry[i].moduleName == NULL) { - HDF_LOGE("%s driver entry module name is null!", __func__); - return NULL; + HDF_LOGE("%s: driver entry module name is null", __func__); + continue; } if (strcmp(deviceInfo->moduleName, driverEntry[i].moduleName) == 0) { return &driverEntry[i]; } } - HDF_LOGE("Hdf get %s device entry failed!", deviceInfo->svcName); + HDF_LOGE("failed to get device entry %s", deviceInfo->svcName); return NULL; } diff --git a/core/host/include/devhost_service.h b/core/host/include/devhost_service.h index 26d8972c..eb7347ee 100644 --- a/core/host/include/devhost_service.h +++ b/core/host/include/devhost_service.h @@ -11,20 +11,23 @@ #include "devhost_service_if.h" #include "hdf_service_observer.h" -#include "hdf_slist.h" +#include "hdf_dlist.h" #include "osal_mutex.h" +#include "osal_sysevent.h" struct DevHostService { struct IDevHostService super; uint16_t hostId; const char *hostName; - struct HdfSList devices; + struct DListHead devices; struct HdfServiceObserver observer; + struct HdfSysEventNotifyNode sysEventNotifyNode; }; void DevHostServiceConstruct(struct DevHostService *service); void DevHostServiceDestruct(struct DevHostService *service); int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo); +int DevHostServiceDelDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo); struct IDevHostService *DevHostServiceNewInstance(uint16_t hostId, const char *hostName); void DevHostServiceFreeInstance(struct IDevHostService *service); struct HdfObject *DevHostServiceCreate(void); diff --git a/core/host/include/hdf_device.h b/core/host/include/hdf_device.h index c14e9901..e15132a1 100644 --- a/core/host/include/hdf_device.h +++ b/core/host/include/hdf_device.h @@ -14,7 +14,7 @@ #include "hdf_device_desc.h" #include "hdf_object.h" #include "hdf_service_observer.h" -#include "hdf_slist.h" +#include "hdf_dlist.h" #include "osal_mutex.h" struct HdfDeviceNode; @@ -22,11 +22,12 @@ struct HdfDeviceNode; struct IHdfDevice { struct HdfObject object; int (*Attach)(struct IHdfDevice *, struct HdfDeviceNode *); + void (*Detach)(struct IHdfDevice *, struct HdfDeviceNode *); }; struct HdfDevice { struct IHdfDevice super; - struct HdfSListNode node; + struct DListHead node; struct HdfSList services; uint16_t deviceId; uint16_t hostId; diff --git a/core/host/include/hdf_device_node.h b/core/host/include/hdf_device_node.h index aee06dd2..87b9da5f 100644 --- a/core/host/include/hdf_device_node.h +++ b/core/host/include/hdf_device_node.h @@ -12,6 +12,7 @@ #include "hdf_device.h" #include "hdf_device_info.h" #include "hdf_device_desc.h" +#include "hdf_pm.h" struct HdfDeviceNode; struct DevHostService; @@ -34,7 +35,9 @@ struct HdfDeviceNode { }; int HdfDeviceNodeAddPowerStateListener( - struct HdfDeviceNode *devNode, struct IPowerEventListener *listener); + struct HdfDeviceNode *devNode, const struct IPowerEventListener *listener); +void HdfDeviceNodeRemovePowerStateListener( + struct HdfDeviceNode *devNode, const struct IPowerEventListener *listener); void HdfDeviceNodeConstruct(struct HdfDeviceNode *service); void HdfDeviceNodeDestruct(struct HdfDeviceNode *service); struct HdfDeviceNode *HdfDeviceNodeNewInstance(void); diff --git a/core/host/include/hdf_driver_loader.h b/core/host/include/hdf_driver_loader.h index e6fbb413..56048807 100644 --- a/core/host/include/hdf_driver_loader.h +++ b/core/host/include/hdf_driver_loader.h @@ -25,10 +25,12 @@ struct HdfDriverLoader { }; struct HdfObject *HdfDriverLoaderCreate(void); +void HdfDriverLoaderConstruct(struct HdfDriverLoader *inst); void HdfDriverLoaderRelease(struct HdfObject *object); struct IDriverLoader *HdfDriverLoaderGetInstance(void); struct HdfDriverEntry *HdfDriverLoaderGetDriverEntry(const struct HdfDeviceInfo *deviceInfo); struct HdfDeviceNode *HdfDriverLoaderLoadNode( struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo); +void HdfDriverLoaderUnLoadNode(struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo); #endif /* HDF_DRIVER_LOADER_H */ diff --git a/core/host/include/power_state_token.h b/core/host/include/power_state_token.h index eda268bf..f82d0a22 100644 --- a/core/host/include/power_state_token.h +++ b/core/host/include/power_state_token.h @@ -11,17 +11,19 @@ #include "hdf_sref.h" #include "power_state_token_if.h" +#include "hdf_pm.h" struct PowerStateToken { struct IPowerStateToken super; - struct IPowerEventListener *listener; + const struct IPowerEventListener *listener; struct HdfDeviceObject *deviceObject; struct HdfSRef wakeRef; HdfPowerState state; + uint32_t mode; }; struct PowerStateToken *PowerStateTokenNewInstance( - struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener); + struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener); void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken); - +int PowerStateOnSysStateChange(struct PowerStateToken *stateToken, int32_t state); #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 index 71f1ffd9..52cc5390 100644 --- a/core/host/src/devhost_service.c +++ b/core/host/src/devhost_service.c @@ -10,9 +10,7 @@ #include "devmgr_service_clnt.h" #include "devsvc_manager_clnt.h" #include "hdf_base.h" -#include "hdf_device_node_ext.h" #include "hdf_driver_loader.h" -#include "hdf_io_service.h" #include "hdf_log.h" #include "hdf_object_manager.h" #include "osal_mem.h" @@ -21,17 +19,13 @@ 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"); + HDF_LOGE("failed to find driver, 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); + DLIST_FOR_EACH_ENTRY(deviceNode, &inst->devices, struct HdfDevice, node) { if (deviceNode->deviceId == deviceId) { return deviceNode; } @@ -43,7 +37,7 @@ static void DevHostServiceFreeDevice(struct DevHostService *inst, uint16_t devic { struct HdfDevice *deviceNode = DevHostServiceFindDevice(inst, deviceId); if (deviceNode != NULL) { - HdfSListRemove(&inst->devices, &deviceNode->node); + DListRemove(&deviceNode->node); HdfDeviceFreeInstance(deviceNode); } } @@ -54,12 +48,12 @@ static struct HdfDevice *DevHostServiceGetDevice(struct DevHostService *inst, ui if (device == NULL) { device = HdfDeviceNewInstance(); if (device == NULL) { - HDF_LOGE("Dev host service create driver instance failed"); + HDF_LOGE("Dev host service failed to create driver instance"); return NULL; } device->hostId = inst->hostId; device->deviceId = deviceId; - HdfSListAdd(&inst->devices, &device->node); + DListInsertHead(&device->node, &inst->devices); } return device; } @@ -70,16 +64,16 @@ int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDevice struct HdfDevice *device = NULL; struct HdfDeviceNode *devNode = NULL; struct DevHostService *hostService = (struct DevHostService *)inst; - struct IDriverLoader *driverLoader = HdfDriverLoaderGetInstance(); + struct IDriverLoader *driverLoader = HdfDriverLoaderGetInstance(); if ((deviceInfo == NULL) || (driverLoader == NULL) || (driverLoader->LoadNode == NULL)) { - HDF_LOGE("Add device failed, input param is null"); + HDF_LOGE("failed to add device, input param is null"); return ret; } device = DevHostServiceGetDevice(hostService, deviceInfo->deviceId); - if (device == NULL || device->super.Attach == NULL) { - ret = HDF_DEV_ERR_NO_MEMORY; + if ((device == NULL) || (device->super.Attach == NULL)) { + ret = HDF_DEV_ERR_NO_DEVICE; goto error; } @@ -96,48 +90,58 @@ int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDevice return HDF_SUCCESS; error: - if (!HdfSListIsEmpty(&hostService->devices)) { - DevHostServiceFreeDevice(hostService, deviceInfo->deviceId); + if (DListIsEmpty(&hostService->devices)) { + DevHostServiceFreeDevice(hostService, hostService->hostId); } return ret; } -static int DevHostServiceDelDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo) +static struct HdfDeviceNode *DevHostServiceGetDeviceNode(struct HdfSList *deviceNodes, + const struct HdfDeviceInfo *deviceInfo) +{ + struct HdfSListIterator it; + struct HdfDeviceNode *deviceNode = NULL; + HdfSListIteratorInit(&it, deviceNodes); + while (HdfSListIteratorHasNext(&it)) { + deviceNode = HDF_SLIST_CONTAINER_OF( + struct HdfSListNode, HdfSListIteratorNext(&it), struct HdfDeviceNode, entry); + if (strcmp(deviceNode->deviceInfo->svcName, deviceInfo->svcName) == 0 && + strcmp(deviceNode->deviceInfo->moduleName, deviceInfo->moduleName) == 0) { + HdfSListRemove(deviceNodes, &deviceNode->entry); + return deviceNode; + } + } + return NULL; +} + +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"); + HDF_LOGE("failed to del device, input param is null"); return HDF_FAILURE; } device = DevHostServiceGetDevice(hostService, deviceInfo->deviceId); if (device == NULL) { - HDF_LOGW("Del device failed, device is not exist"); + HDF_LOGW("failed to del device, device is not exist"); return HDF_SUCCESS; } driverLoader->UnLoadNode(driverLoader, deviceInfo); - struct HdfSListIterator it; - struct HdfDeviceNode *deviceNode = NULL; - HdfSListIteratorInit(&it, &device->services); - while (HdfSListIteratorHasNext(&it)) { - deviceNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( - struct HdfSListNode, HdfSListIteratorNext(&it), struct HdfDeviceNode, entry); - if ((strcmp(deviceNode->deviceInfo->moduleName, deviceInfo->moduleName) == 0) && - (strcmp(deviceNode->deviceInfo->svcName, deviceInfo->svcName) == 0)) { - struct DeviceNodeExt *deviceNodeExt = (struct DeviceNodeExt *)deviceNode; - HdfSListRemove(&device->services, &deviceNode->entry); - DeviceNodeExtRelease(&deviceNodeExt->super.super.object); - } - } - - if (!HdfSListIsEmpty(&hostService->devices)) { - DevHostServiceFreeDevice(hostService, device->deviceId); + struct HdfDeviceNode *devNode = DevHostServiceGetDeviceNode(&device->services, deviceInfo); + if (device->super.Detach != NULL) { + device->super.Detach(&device->super, devNode); + } else { + HdfDeviceNodeFreeInstance(devNode); } DevSvcManagerClntRemoveService(deviceInfo->svcName); + if (HdfSListIsEmpty(&device->services)) { + DevHostServiceFreeDevice(hostService, device->deviceId); + } return HDF_SUCCESS; } @@ -145,7 +149,7 @@ static int DevHostServiceStartService(struct IDevHostService *service) { struct DevHostService *hostService = (struct DevHostService*)service; if (hostService == NULL) { - HDF_LOGE("Start device service failed, hostService is null"); + HDF_LOGE("failed to start device service, hostService is null"); return HDF_FAILURE; } return DevmgrServiceClntAttachDeviceHost(hostService->hostId, service); @@ -158,14 +162,22 @@ void DevHostServiceConstruct(struct DevHostService *service) hostServiceIf->AddDevice = DevHostServiceAddDevice; hostServiceIf->DelDevice = DevHostServiceDelDevice; hostServiceIf->StartService = DevHostServiceStartService; - HdfSListInit(&service->devices); + DListHeadInit(&service->devices); HdfServiceObserverConstruct(&service->observer); } } void DevHostServiceDestruct(struct DevHostService *service) { - HdfSListFlush(&service->devices, HdfDeviceDelete); + if (service == NULL) { + return; + } + + struct HdfDevice *device = NULL; + struct HdfDevice *tmp = NULL; + DLIST_FOR_EACH_ENTRY_SAFE(device, tmp, &service->devices, struct HdfDevice, node) { + HdfDeviceFreeInstance(device); + } HdfServiceObserverDestruct(&service->observer); } diff --git a/core/host/src/devmgr_service_clnt.c b/core/host/src/devmgr_service_clnt.c index 712e2098..378ec5f5 100644 --- a/core/host/src/devmgr_service_clnt.c +++ b/core/host/src/devmgr_service_clnt.c @@ -19,13 +19,13 @@ int DevmgrServiceClntAttachDeviceHost(uint16_t hostId, struct IDevHostService *h 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"); + HDF_LOGE("failed to attach device host, 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"); + HDF_LOGE("failed to attach device host, attach device host function is null"); return HDF_FAILURE; } return devMgrSvcIf->AttachDeviceHost(devMgrSvcIf, hostId, hostService); @@ -36,13 +36,13 @@ int DevmgrServiceClntAttachDevice(const struct HdfDeviceInfo *deviceInfo, struct 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"); + HDF_LOGE("devmgr client failed to attach device, 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"); + HDF_LOGE("devmgr client failed to attach device, dmsOps->AttachDevice is nul"); return HDF_FAILURE; } return devMgrSvcIf->AttachDevice(devMgrSvcIf, deviceInfo, deviceToken); diff --git a/core/host/src/devsvc_manager_clnt.c b/core/host/src/devsvc_manager_clnt.c index e3ae2142..7dd4aef7 100644 --- a/core/host/src/devsvc_manager_clnt.c +++ b/core/host/src/devsvc_manager_clnt.c @@ -20,13 +20,13 @@ int DevSvcManagerClntAddService(const char *svcName, struct HdfDeviceObject *ser { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to add service, client is null"); return HDF_FAILURE; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->AddService == NULL) { - HDF_LOGE("AddService function is not assigned"); + HDF_LOGE("serviceManager AddService function is null"); return HDF_FAILURE; } return serviceManager->AddService(serviceManager, svcName, service); @@ -36,13 +36,13 @@ const struct HdfObject *DevSvcManagerClntGetService(const char *svcName) { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to get service, client is null"); return NULL; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->GetService == NULL) { - HDF_LOGE("GetService function is not assigned"); + HDF_LOGE("serviceManager GetService function is null"); return NULL; } return serviceManager->GetService(serviceManager, svcName); @@ -52,13 +52,13 @@ struct HdfDeviceObject *DevSvcManagerClntGetDeviceObject(const char *svcName) { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to get device object, client is null"); return NULL; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->GetObject == NULL) { - HDF_LOGE("GetObject function is not assigned"); + HDF_LOGE("failed to get device object, method not implement"); return NULL; } return serviceManager->GetObject(serviceManager, svcName); @@ -82,10 +82,8 @@ struct HdfDeviceObject *HdfRegisterDevice(const char *moduleName, const char *se void HdfUnregisterDevice(const char *moduleName, const char *serviceName) { - int ret; - ret = DevmgrServiceUnLoadDevice(serviceName); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s unload device %s failed!", __func__, serviceName); + if (DevmgrServiceUnLoadDevice(serviceName) != HDF_SUCCESS) { + HDF_LOGE("%s:failed to unload device %s !", __func__, serviceName); } HdfDeviceListDel(moduleName, serviceName); } @@ -94,13 +92,13 @@ int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCall { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to subscribe service, client is null"); return HDF_FAILURE; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->SubscribeService == NULL) { - HDF_LOGE("SubscribeService function is not assigned"); + HDF_LOGE("failed to subscribe service, method not implement"); return HDF_FAILURE; } return serviceManager->SubscribeService(serviceManager, svcName, callback); @@ -110,13 +108,13 @@ int DevSvcManagerClntUnsubscribeService(const char *svcName) { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to unsubscribe service, client is null"); return HDF_FAILURE; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->UnsubscribeService == NULL) { - HDF_LOGE("UnsubService function is not assigned"); + HDF_LOGE("failed to unsubscribe service, method not implement"); return HDF_FAILURE; } return serviceManager->UnsubscribeService(serviceManager, svcName); @@ -126,13 +124,13 @@ void DevSvcManagerClntRemoveService(const char *svcName) { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); if (devSvcMgrClnt == NULL) { - HDF_LOGE("Get device manager client is null"); + HDF_LOGE("failed to remove service, devSvcMgrClnt is null"); return; } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; if (serviceManager == NULL || serviceManager->RemoveService == NULL) { - HDF_LOGE("Remove service function is not assigned"); + HDF_LOGE("failed to remove service, method not implement"); return; } serviceManager->RemoveService(serviceManager, svcName); @@ -157,9 +155,7 @@ struct DevSvcManagerClnt *DevSvcManagerClntGetInstance() void DevSvcManagerClntFreeInstance(struct DevSvcManagerClnt *instance) { if (instance != NULL) { - if (instance->devSvcMgrIf != NULL) { - HdfObjectManagerFreeObject((struct HdfObject *)instance->devSvcMgrIf); - } + HdfObjectManagerFreeObject((struct HdfObject *)instance->devSvcMgrIf); } } diff --git a/core/host/src/hdf_device.c b/core/host/src/hdf_device.c index b4f27d19..3fc55700 100644 --- a/core/host/src/hdf_device.c +++ b/core/host/src/hdf_device.c @@ -23,7 +23,7 @@ static int HdfDeviceAttach(struct IHdfDevice *devInst, struct HdfDeviceNode *dev 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"); + HDF_LOGE("failed to attach device, input params invalid"); return HDF_ERR_INVALID_PARAM; } HdfSListAdd(&device->services, &devNode->entry); diff --git a/core/host/src/hdf_device_node.c b/core/host/src/hdf_device_node.c index 4ccd58a1..793da0d6 100644 --- a/core/host/src/hdf_device_node.c +++ b/core/host/src/hdf_device_node.c @@ -26,12 +26,12 @@ static int HdfDeviceNodePublishLocalService( { uint32_t matchId; if ((devNode == NULL) || (deviceInfo == NULL)) { - HDF_LOGE("Publish local service failed, device is null"); + HDF_LOGE("failed to publish local service, device is null"); return HDF_FAILURE; } struct DevHostService *hostService = devNode->hostService; if (hostService == NULL) { - HDF_LOGE("Publish local service failed, host service is null"); + HDF_LOGE("failed to publish local service, host service is null"); return HDF_FAILURE; } matchId = HdfMakeHardwareId(deviceInfo->hostId, deviceInfo->deviceId); @@ -44,7 +44,8 @@ static int HdfDeviceNodePublishService( { (void)device; int status = HDF_SUCCESS; - if (deviceInfo->policy == SERVICE_POLICY_NONE) { + if ((deviceInfo->policy == SERVICE_POLICY_NONE) || + ((deviceInfo->svcName != NULL) && (strlen(deviceInfo->svcName) == 0))) { HDF_LOGI("policy is %d", SERVICE_POLICY_NONE); return status; } @@ -66,7 +67,7 @@ int HdfDeviceLaunchNode(struct HdfDeviceNode *devNode, struct IHdfDevice *devIns { struct HdfDevice *device = (struct HdfDevice *)devInst; if (device == NULL || devNode == NULL) { - HDF_LOGE("Launch service failed, device or service is null"); + HDF_LOGE("failed to launch service, device or service is null"); return HDF_ERR_INVALID_PARAM; } @@ -75,12 +76,12 @@ int HdfDeviceLaunchNode(struct HdfDeviceNode *devNode, struct IHdfDevice *devIns struct IHdfDeviceToken *deviceToken = NULL; if (deviceInfo == NULL) { - HDF_LOGE("Launch service failed, deviceInfo is null"); + HDF_LOGE("failed to launch service, deviceInfo is null"); return HDF_ERR_INVALID_PARAM; } if ((driverEntry == NULL) || (driverEntry->Init == NULL)) { - HDF_LOGE("deviceEntry or deviceEntry->Init is null"); + HDF_LOGE("failed to launch service, deviceEntry invalid"); return HDF_ERR_INVALID_PARAM; } int ret = driverEntry->Init(&devNode->deviceObject); @@ -109,21 +110,33 @@ int HdfDeviceLaunchNode(struct HdfDeviceNode *devNode, struct IHdfDevice *devIns } int HdfDeviceNodeAddPowerStateListener( - struct HdfDeviceNode *devNode, struct IPowerEventListener *listener) + struct HdfDeviceNode *devNode, const struct IPowerEventListener *listener) { if (devNode->powerToken != NULL) { return HDF_FAILURE; } - if (devNode->powerToken == NULL) { - devNode->powerToken = PowerStateTokenNewInstance(&devNode->deviceObject, listener); - } + + devNode->powerToken = PowerStateTokenNewInstance(&devNode->deviceObject, listener); return (devNode->powerToken != NULL) ? HDF_SUCCESS : HDF_FAILURE; } +void HdfDeviceNodeRemovePowerStateListener( + struct HdfDeviceNode *devNode, const struct IPowerEventListener *listener) +{ + (void)listener; + if (devNode == NULL || devNode->powerToken == NULL) { + return; + } + + PowerStateTokenFreeInstance(devNode->powerToken); + devNode->powerToken = NULL; +} + + int HdfDeviceNodePublishPublicService(struct HdfDeviceNode *devNode, const char *svcName) { if ((devNode == NULL) || (devNode->deviceObject.service == NULL)) { - HDF_LOGE("device method is null"); + HDF_LOGE("failed to publish public service: devNode is NULL"); return HDF_FAILURE; } return DevSvcManagerClntAddService(svcName, &devNode->deviceObject); diff --git a/core/host/src/hdf_device_object.c b/core/host/src/hdf_device_object.c index 2c109ac3..832b11d8 100644 --- a/core/host/src/hdf_device_object.c +++ b/core/host/src/hdf_device_object.c @@ -23,19 +23,19 @@ int32_t HdfDeviceSubscribeService( struct DevHostService *hostService = NULL; const struct HdfDeviceInfo *deviceInfo = NULL; if (deviceObject == NULL || serviceName == NULL) { - HDF_LOGE("%s input param is invalid", __func__); + HDF_LOGE("failed to subscribe service, deviceObject/serviceName is null"); 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"); + HDF_LOGE("failed to subscribe service, hostService is null"); return HDF_FAILURE; } deviceInfo = devNode->deviceInfo; if (deviceInfo == NULL) { - HDF_LOGE("Get device deviceInfo is null"); + HDF_LOGE("failed to subscribe service, deviceInfo is null"); return HDF_FAILURE; } matchId = HdfMakeHardwareId(deviceInfo->hostId, deviceInfo->deviceId); @@ -45,34 +45,43 @@ int32_t HdfDeviceSubscribeService( const char *HdfDeviceGetServiceName(const struct HdfDeviceObject *deviceObject) { if (deviceObject == NULL) { - HDF_LOGE("%s input param is invalid", __func__); + HDF_LOGE("failed to get service name, deviceObject is invalid"); 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"); + HDF_LOGE("failed to get service name, deviceInfo is null"); return NULL; } return deviceInfo->svcName; } -void HdfDeviceRegisterPowerListener(struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) +int HdfPmRegisterPowerListener(struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener) +{ + if (deviceObject == NULL) { + return HDF_ERR_INVALID_PARAM; + } + struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( + struct HdfDeviceObject, deviceObject, struct HdfDeviceNode, deviceObject); + return HdfDeviceNodeAddPowerStateListener(devNode, listener); +} + +void HdfPmUnregisterPowerListener(struct HdfDeviceObject *deviceObject, const 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); + HdfDeviceNodeRemovePowerStateListener(devNode, listener); } -void HdfDeviceAcquireWakeLock(struct HdfDeviceObject *deviceObject) +void HdfPmAcquireDevice(struct HdfDeviceObject *deviceObject) { if (deviceObject == NULL) { - HDF_LOGE("%s input param is invalid", __func__); + HDF_LOGE("%s: input param is invalid", __func__); return; } struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( @@ -83,10 +92,10 @@ void HdfDeviceAcquireWakeLock(struct HdfDeviceObject *deviceObject) } } -void HdfDeviceReleaseWakeLock(struct HdfDeviceObject *deviceObject) +void HdfPmReleaseDevice(struct HdfDeviceObject *deviceObject) { if (deviceObject == NULL) { - HDF_LOGE("%s input param is invalid", __func__); + HDF_LOGE("%s: input param is invalid", __func__); return; } struct HdfDeviceNode *devNode = (struct HdfDeviceNode *)HDF_SLIST_CONTAINER_OF( @@ -97,6 +106,20 @@ void HdfDeviceReleaseWakeLock(struct HdfDeviceObject *deviceObject) } } +void HdfPmSetMode(struct HdfDeviceObject *deviceObject, uint32_t mode) +{ + if (deviceObject == NULL || mode > HDF_POWER_MODE_MAX) { + 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 PowerStateToken *token = devNode->powerToken; + if (token != NULL) { + token->mode = mode; + } +} + bool HdfDeviceSetClass(struct HdfDeviceObject *deviceObject, DeviceClass deviceClass) { if ((deviceObject == NULL) || (deviceClass >= DEVICE_CLASS_MAX) || diff --git a/core/host/src/hdf_driver_loader.c b/core/host/src/hdf_driver_loader.c old mode 100644 new mode 100755 index ec9f7801..5ef03def --- a/core/host/src/hdf_driver_loader.c +++ b/core/host/src/hdf_driver_loader.c @@ -23,27 +23,28 @@ struct HdfDeviceNode *HdfDriverLoaderLoadNode( struct HdfDriverEntry *driverEntry = NULL; struct HdfDeviceNode *devNode = NULL; if ((loader == NULL) || (loader->GetDriverEntry == NULL)) { - HDF_LOGE("loader or loader->GetDriverEntry is null"); + HDF_LOGE("failed to load node, loader is invalid"); return NULL; } driverEntry = loader->GetDriverEntry(deviceInfo); if (driverEntry == NULL) { - HDF_LOGE("Load service failed, deviceEntry is null"); + HDF_LOGE("failed to load node, deviceEntry is null"); return NULL; } devNode = HdfDeviceNodeNewInstance(); if (devNode == NULL) { - HDF_LOGE("Load service failed, device node is null"); + HDF_LOGE("failed to load node, device node is null"); return NULL; } devNode->driverEntry = driverEntry; devNode->deviceInfo = deviceInfo; devNode->deviceObject.property = HcsGetNodeByMatchAttr(HdfGetRootNode(), deviceInfo->deviceMatchAttr); + if (devNode->deviceObject.property == NULL) { - HDF_LOGW("Get property is null, match attr is: %s", deviceInfo->deviceMatchAttr); + HDF_LOGW("failed to load node, property is null, match attr is: %s", deviceInfo->deviceMatchAttr); } if ((deviceInfo->policy == SERVICE_POLICY_PUBLIC) || (deviceInfo->policy == SERVICE_POLICY_CAPACITY)) { @@ -61,34 +62,38 @@ struct HdfDeviceNode *HdfDriverLoaderLoadNode( return devNode; } -static void HdfDriverLoaderUnLoadNode(struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo) +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"); + HDF_LOGE("failed to unload service, loader invalid"); return; } driverEntry = loader->GetDriverEntry(deviceInfo); if (driverEntry == NULL) { - HDF_LOGE("Load service failed, driverEntry is null"); + HDF_LOGE("failed to unload service, driverEntry is null"); return; } if (driverEntry->Release == NULL) { - HDF_LOGI("Device Release func is null"); + HDF_LOGI("device release func is null"); return; } deviceObject = DevSvcManagerClntGetDeviceObject(deviceInfo->svcName); - driverEntry->Release(deviceObject); + if (deviceObject != NULL) { + driverEntry->Release(deviceObject); + } } -static void HdfDriverLoaderConstruct(struct HdfDriverLoader *inst) +void HdfDriverLoaderConstruct(struct HdfDriverLoader *inst) { - struct IDriverLoader *driverLoaderIf = (struct IDriverLoader *)inst; - driverLoaderIf->LoadNode = HdfDriverLoaderLoadNode; - driverLoaderIf->UnLoadNode = HdfDriverLoaderUnLoadNode; - driverLoaderIf->GetDriverEntry = HdfDriverLoaderGetDriverEntry; + if (inst != NULL) { + struct IDriverLoader *driverLoaderIf = (struct IDriverLoader *)inst; + driverLoaderIf->LoadNode = HdfDriverLoaderLoadNode; + driverLoaderIf->UnLoadNode = HdfDriverLoaderUnLoadNode; + driverLoaderIf->GetDriverEntry = HdfDriverLoaderGetDriverEntry; + } } struct HdfObject *HdfDriverLoaderCreate() diff --git a/core/host/src/hdf_observer_record.c b/core/host/src/hdf_observer_record.c index d75f5c95..645d7d54 100644 --- a/core/host/src/hdf_observer_record.c +++ b/core/host/src/hdf_observer_record.c @@ -16,9 +16,7 @@ uint32_t HdfMakeHardwareId(uint16_t hostId, uint16_t deviceId) { - uint32_t hardwareId = hostId; - hardwareId = (hardwareId << HALF_INT_LEN) | deviceId; - return hardwareId; + return ((uint32_t)hostId << HALF_INT_LEN) | deviceId; } struct HdfServiceObserverRecord *HdfServiceObserverRecordObtain(uint32_t serviceKey) diff --git a/core/host/src/hdf_service_observer.c b/core/host/src/hdf_service_observer.c index 52bafee2..29aa1555 100644 --- a/core/host/src/hdf_service_observer.c +++ b/core/host/src/hdf_service_observer.c @@ -32,7 +32,6 @@ void HdfServiceObserverDestruct(struct HdfServiceObserver *observer) if (observer != NULL) { HdfSListFlush(&observer->services, HdfServiceObserverRecordDelete); OsalMutexDestroy(&observer->observerMutex); - observer->observerMutex.realMutex = NULL; } } @@ -51,20 +50,22 @@ int HdfServiceObserverSubscribeService(struct HdfServiceObserver *observer, if (serviceRecord == NULL) { serviceRecord = HdfServiceObserverRecordObtain(serviceKey); if (serviceRecord == NULL) { - HDF_LOGE("SubscribeService failed, serviceRecord is null"); + HDF_LOGE("failed to subscribe service, serviceRecord is null"); return HDF_FAILURE; } subscriber = HdfServiceSubscriberObtain(callback, matchId); if (subscriber == NULL) { - HDF_LOGE("SubscribeService failed, subscriber is null"); + HDF_LOGE("failed to subscribe service, subscriber is null"); HdfServiceObserverRecordRecycle(serviceRecord); return HDF_FAILURE; } + OsalMutexLock(&observer->observerMutex); HdfSListAdd(&observer->services, &serviceRecord->entry); + OsalMutexUnlock(&observer->observerMutex); } else { subscriber = HdfServiceSubscriberObtain(callback, matchId); if (subscriber == NULL) { - HDF_LOGE("SubscribeService failed, hdf search list is null, subscriber is null"); + HDF_LOGE("failed to subscribe service, subscriber obtain null"); return HDF_FAILURE; } } @@ -101,7 +102,9 @@ int HdfServiceObserverPublishService(struct HdfServiceObserver *observer, serviceRecord->publisher = service; serviceRecord->matchId = matchId; serviceRecord->policy = policy; + OsalMutexLock(&observer->observerMutex); HdfSListAdd(&observer->services, &serviceRecord->entry); + OsalMutexUnlock(&observer->observerMutex); } else { serviceRecord->publisher = service; HdfServiceObserverRecordNotifySubscribers(serviceRecord, matchId, policy); diff --git a/core/host/src/hdf_service_subscriber.c b/core/host/src/hdf_service_subscriber.c index 6307977e..efcec2f4 100644 --- a/core/host/src/hdf_service_subscriber.c +++ b/core/host/src/hdf_service_subscriber.c @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include "osal_mem.h" #include "hdf_service_subscriber.h" +#include "osal_mem.h" struct HdfServiceSubscriber *HdfServiceSubscriberObtain(struct SubscriberCallback callback, uint32_t matchId) { diff --git a/core/host/src/power_state_token.c b/core/host/src/power_state_token.c index 41702590..ab65bbf6 100644 --- a/core/host/src/power_state_token.c +++ b/core/host/src/power_state_token.c @@ -11,12 +11,110 @@ #include "hdf_device_desc.h" #include "hdf_slist.h" #include "osal_mem.h" +#include "osal_sysevent.h" -static void PowerStateTokenAcqureWakeLock(struct IPowerStateToken *token) +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) { + return; + } + + struct IDevmgrService *devMgrSvcIf = NULL; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if (inst == NULL) { + return; + } + devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; + if (devMgrSvcIf != NULL && devMgrSvcIf->AcquireWakeLock != NULL) { + devMgrSvcIf->AcquireWakeLock(devMgrSvcIf, &stateToken->super); + } + + if (stateToken->state == POWER_STATE_INACTIVE || stateToken->state == POWER_STATE_IDLE) { + const struct IPowerEventListener *listener = stateToken->listener; + 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 && stateToken->state != POWER_STATE_IDLE) { + return; + } + + struct IDevmgrService *devMgrSvcIf = NULL; + const struct IPowerEventListener *listener = stateToken->listener; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if (inst == NULL) { + return; + } + + if (stateToken->state == POWER_STATE_ACTIVE) { + devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; + if ((devMgrSvcIf != NULL) && (devMgrSvcIf->AcquireWakeLock != NULL)) { + devMgrSvcIf->ReleaseWakeLock(devMgrSvcIf, &stateToken->super); + } + } + + if ((listener != NULL) && (listener->Suspend != NULL)) { + listener->Suspend(stateToken->deviceObject); + } + stateToken->state = POWER_STATE_INACTIVE; +} + +int PowerStateOnSysStateChange(struct PowerStateToken *stateToken, int32_t state) +{ + if (stateToken == NULL || stateToken->listener == NULL || stateToken->mode != HDF_POWER_SYS_CTRL) { + return HDF_SUCCESS; + } + + switch (state) { + case KEVENT_POWER_SUSPEND: + if (stateToken->listener->Suspend != NULL) { + return stateToken->listener->Suspend(stateToken->deviceObject); + } + break; + case KEVENT_POWER_RESUME: + if (stateToken->listener->Resume != NULL) { + return stateToken->listener->Resume(stateToken->deviceObject); + } + break; + case KEVENT_POWER_DISPLAY_OFF: + if (stateToken->listener->DozeSuspend != NULL) { + return stateToken->listener->DozeSuspend(stateToken->deviceObject); + } + break; + case KEVENT_POWER_DISPLAY_ON: + if (stateToken->listener->DozeResume != NULL) { + return stateToken->listener->DozeResume(stateToken->deviceObject); + } + break; + default: + break; + } + + return HDF_SUCCESS; +} + +static void PowerStateTokenAcquireWakeLock(struct IPowerStateToken *token) { struct HdfSRef *sref = NULL; struct PowerStateToken *stateToken = (struct PowerStateToken *)token; - if (stateToken == NULL) { + if (stateToken == NULL || stateToken->mode != HDF_POWER_DYNAMIC_CTRL) { return; } sref = (struct HdfSRef *)&stateToken->wakeRef; @@ -29,79 +127,32 @@ static void PowerStateTokenReleaseWakeLock(struct IPowerStateToken *token) { struct HdfSRef *sref = NULL; struct PowerStateToken *stateToken = (struct PowerStateToken *)token; - if (stateToken == NULL) { + if (stateToken == NULL || stateToken->mode != HDF_POWER_DYNAMIC_CTRL) { return; } sref = (struct HdfSRef *)&stateToken->wakeRef; - if ((sref != NULL) && (sref->Release != NULL)) { + if ((sref == NULL) || (sref->Release == NULL)) { + return; + } + + /* Not allowed to decrease the ref count to negative */ + if (HdfSRefCount(sref) == 0) { + PowerStateTokenOnLastRelease(sref); + } else { 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 == NULL || 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) +static int32_t PowerStateTokenConstruct(struct PowerStateToken *powerStateToken, + struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener) { struct IPowerStateToken *tokenIf = &powerStateToken->super; struct IHdfSRefListener *srefListener = (struct IHdfSRefListener *)OsalMemCalloc(sizeof(struct IHdfSRefListener)); if (srefListener == NULL) { - return; + return HDF_ERR_MALLOC_FAIL; } - tokenIf->AcquireWakeLock = PowerStateTokenAcqureWakeLock; + tokenIf->AcquireWakeLock = PowerStateTokenAcquireWakeLock; tokenIf->ReleaseWakeLock = PowerStateTokenReleaseWakeLock; srefListener->OnFirstAcquire = PowerStateTokenOnFirstAcquire; @@ -111,16 +162,24 @@ static void PowerStateTokenConstruct( powerStateToken->listener = listener; powerStateToken->deviceObject = deviceObject; HdfSRefConstruct(&powerStateToken->wakeRef, srefListener); + + return HDF_SUCCESS; } struct PowerStateToken *PowerStateTokenNewInstance( - struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) + struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener) { struct PowerStateToken *stateToken = (struct PowerStateToken *)OsalMemCalloc(sizeof(struct PowerStateToken)); - if (stateToken != NULL) { - PowerStateTokenConstruct(stateToken, deviceObject, listener); + if (stateToken == NULL) { + return NULL; } + + if (PowerStateTokenConstruct(stateToken, deviceObject, listener) != HDF_SUCCESS) { + OsalMemFree(stateToken); + return NULL; + } + return stateToken; } diff --git a/core/manager/include/devhost_service_clnt.h b/core/manager/include/devhost_service_clnt.h index 3a641297..c80f3b1c 100644 --- a/core/manager/include/devhost_service_clnt.h +++ b/core/manager/include/devhost_service_clnt.h @@ -11,11 +11,13 @@ #include "devhost_service_if.h" #include "hdf_slist.h" +#include "hdf_map.h" struct DevHostServiceClnt { struct HdfSListNode node; struct HdfSList devices; struct HdfSList *deviceInfos; + Map *deviceHashMap; struct IDevHostService *hostService; uint16_t devCount; uint16_t hostId; @@ -25,7 +27,7 @@ struct DevHostServiceClnt { int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt); struct DevHostServiceClnt *DevHostServiceClntNewInstance(uint16_t hostId, const char *hostName); -void DevHostServiceClntFreeInstance(struct DevHostServiceClnt* hostClnt); +void DevHostServiceClntFreeInstance(struct DevHostServiceClnt *hostClnt); void DevHostServiceClntDelete(struct HdfSListNode *listEntry); #endif /* DEVHOST_SERVICE_CLNT_H */ diff --git a/core/manager/include/devsvc_manager.h b/core/manager/include/devsvc_manager.h index 658fd49e..b73731bc 100644 --- a/core/manager/include/devsvc_manager.h +++ b/core/manager/include/devsvc_manager.h @@ -29,4 +29,7 @@ int DevSvcManagerAddService(struct IDevSvcManager *manager, const char *svcName, struct HdfObject *DevSvcManagerGetService(struct IDevSvcManager *manager, const char *svcName); void DevSvcManagerRemoveService(struct IDevSvcManager *manager, const char *svcName); +int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback); +int DevSvcManagerClntUnsubscribeService(const char *svcName); + #endif /* DEVICE_SERVICE_MANAGER_H */ diff --git a/core/manager/include/power_state_token_clnt.h b/core/manager/include/power_state_token_clnt.h index ba700d8b..1915a985 100644 --- a/core/manager/include/power_state_token_clnt.h +++ b/core/manager/include/power_state_token_clnt.h @@ -16,7 +16,7 @@ struct PowerStateTokenClnt { struct HdfSListNode entry; HdfPowerState powerState; - struct IPowerStateToken* tokenIf; + struct IPowerStateToken *tokenIf; }; struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf); diff --git a/core/manager/src/devhost_service_clnt.c b/core/manager/src/devhost_service_clnt.c index ee31bab4..490cf040 100644 --- a/core/manager/src/devhost_service_clnt.c +++ b/core/manager/src/devhost_service_clnt.c @@ -23,7 +23,7 @@ int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt) struct HdfDeviceInfo *deviceInfo = NULL; struct IDevHostService *devHostSvcIf = NULL; if (hostClnt == NULL) { - HDF_LOGE("Install driver failed, hostClnt is null"); + HDF_LOGE("failed to install driver, hostClnt is null"); return HDF_FAILURE; } @@ -44,7 +44,7 @@ int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt) } ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); if (ret != HDF_SUCCESS) { - HDF_LOGE("Install %s driver failed, ret = %d", deviceInfo->svcName, ret); + HDF_LOGE("failed to install driver %s, ret = %d", deviceInfo->svcName, ret); } } return HDF_SUCCESS; @@ -53,6 +53,12 @@ int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt) static void DevHostServiceClntConstruct(struct DevHostServiceClnt *hostClnt) { HdfSListInit(&hostClnt->devices); + hostClnt->deviceHashMap = (Map *)OsalMemCalloc(sizeof(Map)); + if (hostClnt->deviceHashMap == NULL) { + HDF_LOGE("%s:failed to malloc deviceHashMap", __func__); + return; + } + MapInit(hostClnt->deviceHashMap); } struct DevHostServiceClnt *DevHostServiceClntNewInstance(uint16_t hostId, const char *hostName) @@ -73,6 +79,7 @@ void DevHostServiceClntFreeInstance(struct DevHostServiceClnt *hostClnt) if (hostClnt != NULL) { HdfSListFlush(&hostClnt->devices, DeviceTokenClntDelete); HdfSListFlush(hostClnt->deviceInfos, HdfDeviceInfoDelete); + OsalMemFree(hostClnt->deviceHashMap); OsalMemFree(hostClnt); } } diff --git a/core/manager/src/device_token_clnt.c b/core/manager/src/device_token_clnt.c index e912a5c8..6d50b1b2 100644 --- a/core/manager/src/device_token_clnt.c +++ b/core/manager/src/device_token_clnt.c @@ -23,7 +23,7 @@ struct DeviceTokenClnt *DeviceTokenClntNewInstance(struct IHdfDeviceToken *token { struct DeviceTokenClnt *tokenClnt = NULL; if (tokenIf == NULL) { - HDF_LOGE("New token client failed, tokenIf is null"); + HDF_LOGE("failed to create token client, tokenIf is null"); return NULL; } tokenClnt = (struct DeviceTokenClnt *)OsalMemCalloc(sizeof(struct DeviceTokenClnt)); diff --git a/core/manager/src/devmgr_service.c b/core/manager/src/devmgr_service.c index 3472cf9e..545d8675 100644 --- a/core/manager/src/devmgr_service.c +++ b/core/manager/src/devmgr_service.c @@ -17,12 +17,15 @@ #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 (devHostSvcIf == NULL) { + return HDF_FAILURE; + } + if (isLoad && (deviceInfo->preload != DEVICE_PRELOAD_ENABLE)) { int ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); if (ret == HDF_SUCCESS) { @@ -83,7 +86,7 @@ int32_t DevmgrServiceLoadLeftDriver(struct DevmgrService *devMgrSvc) if (deviceInfo->preload == DEVICE_PRELOAD_ENABLE_STEP2) { ret = DevmgrServiceActiveDevice(hostClnt, deviceInfo, true); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s load driver %s failed!", __func__, deviceInfo->moduleName); + HDF_LOGE("%s:failed to load driver %s", __func__, deviceInfo->moduleName); } } } @@ -91,7 +94,6 @@ int32_t DevmgrServiceLoadLeftDriver(struct DevmgrService *devMgrSvc) return HDF_SUCCESS; } - int DevmgrServiceLoadDevice(const char *svcName) { return DevmgrServiceFindAndActiveDevice(svcName, true); @@ -108,7 +110,7 @@ static struct DevHostServiceClnt *DevmgrServiceFindDeviceHost(struct IDevmgrServ struct DevHostServiceClnt *hostClnt = NULL; struct DevmgrService *dmService = (struct DevmgrService *)inst; if (dmService == NULL) { - HDF_LOGE("Find device host failed, dmService is null"); + HDF_LOGE("failed to find device host, dmService is null"); return NULL; } HdfSListIteratorInit(&it, &dmService->hosts); @@ -118,29 +120,49 @@ static struct DevHostServiceClnt *DevmgrServiceFindDeviceHost(struct IDevmgrServ return hostClnt; } } - HDF_LOGE("Find host failed, host id is %u", hostId); + HDF_LOGE("failed to find host, host id is %u", hostId); return NULL; } +static void DevmgrServiceUpdateStatus(struct DevHostServiceClnt *hostClnt, uint16_t deviceId, uint16_t status) +{ + struct HdfSListIterator it; + struct HdfDeviceInfo *deviceInfo = NULL; + + HdfSListIteratorInit(&it, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&it)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&it); + if (deviceInfo->deviceId == deviceId) { + deviceInfo->status = status; + HDF_LOGD("%s host:%s %u device:%s %u status:%u", __func__, hostClnt->hostName, + hostClnt->hostId, deviceInfo->svcName, deviceId, deviceInfo->status); + return; + } + } + HDF_LOGE("%s: not find device %u in host %u", __func__, hostClnt->hostId, deviceId); + return; +} + static int DevmgrServiceAttachDevice( struct IDevmgrService *inst, const struct HdfDeviceInfo *deviceInfo, struct IHdfDeviceToken *token) { if (deviceInfo == NULL) { - HDF_LOGE("deviceInfo is null"); + HDF_LOGE("failed to attach device, deviceInfo is null"); return HDF_FAILURE; } struct DevHostServiceClnt *hostClnt = DevmgrServiceFindDeviceHost(inst, deviceInfo->hostId); if (hostClnt == NULL) { - HDF_LOGE("hostClnt is null"); + HDF_LOGE("failed to attach device, hostClnt is null"); return HDF_FAILURE; } struct DeviceTokenClnt *tokenClnt = DeviceTokenClntNewInstance(token); if (tokenClnt == NULL) { - HDF_LOGE("tokenClnt is null"); + HDF_LOGE("failed to attach device, tokenClnt is null"); return HDF_FAILURE; } tokenClnt->deviceInfo = deviceInfo; + DevmgrServiceUpdateStatus(hostClnt, deviceInfo->deviceId, HDF_SERVICE_USABLE); HdfSListAdd(&hostClnt->devices, &tokenClnt->node); return HDF_SUCCESS; } @@ -150,20 +172,21 @@ static int DevmgrServiceAttachDeviceHost( { struct DevHostServiceClnt *hostClnt = DevmgrServiceFindDeviceHost(inst, hostId); if (hostClnt == NULL) { - HDF_LOGE("Attach device host failed, hostClnt is null"); + HDF_LOGE("failed to attach device host, hostClnt is null"); return HDF_FAILURE; } if (hostService == NULL) { - HDF_LOGE("Attach device host failed, hostService is null"); + HDF_LOGE("failed to attach device host, hostService is null"); return HDF_FAILURE; } + + hostClnt->hostService = hostService; hostClnt->deviceInfos = HdfAttributeManagerGetDeviceList(hostClnt->hostId, hostClnt->hostName); if (hostClnt->deviceInfos == NULL) { - HDF_LOGE("Get device list failed"); - return HDF_FAILURE; + HDF_LOGW("failed to get device list "); + return HDF_SUCCESS; } hostClnt->devCount = HdfSListCount(hostClnt->deviceInfos); - hostClnt->hostService = hostService; return DevHostServiceClntInstallDriver(hostClnt); } @@ -181,7 +204,7 @@ static int DevmgrServiceStartDeviceHosts(struct DevmgrService *inst) } HdfSListInit(&hostList); if (!HdfAttributeManagerGetHostList(&hostList)) { - HDF_LOGW("%s get host list is null", __func__); + HDF_LOGW("%s: host list is null", __func__); return HDF_SUCCESS; } HdfSListIteratorInit(&it, &hostList); @@ -189,13 +212,13 @@ static int DevmgrServiceStartDeviceHosts(struct DevmgrService *inst) hostAttr = (struct HdfHostInfo *)HdfSListIteratorNext(&it); hostClnt = DevHostServiceClntNewInstance(hostAttr->hostId, hostAttr->hostName); if (hostClnt == NULL) { - HDF_LOGW("Create new device host client failed"); + HDF_LOGW("failed to create new device host client"); 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); + HDF_LOGW("failed to start device host, host id is %u", hostAttr->hostId); HdfSListRemove(&inst->hosts, &hostClnt->node); DevHostServiceClntFreeInstance(hostClnt); } @@ -208,7 +231,7 @@ int DevmgrServiceStartService(struct IDevmgrService *inst) { struct DevmgrService *dmService = (struct DevmgrService *)inst; if (dmService == NULL) { - HDF_LOGE("Start device manager service failed, dmService is null"); + HDF_LOGE("failed to start device manager service, dmService is null"); return HDF_FAILURE; } return DevmgrServiceStartDeviceHosts(dmService); @@ -217,7 +240,7 @@ int DevmgrServiceStartService(struct IDevmgrService *inst) bool DevmgrServiceConstruct(struct DevmgrService *inst) { if (OsalMutexInit(&inst->devMgrMutex) != HDF_SUCCESS) { - HDF_LOGE("%s mutex init failed", __func__); + HDF_LOGE("%s:failed to mutex init ", __func__); return false; } struct IDevmgrService *devMgrSvcIf = (struct IDevmgrService *)inst; @@ -228,11 +251,12 @@ bool DevmgrServiceConstruct(struct DevmgrService *inst) devMgrSvcIf->AcquireWakeLock = DevmgrServiceAcquireWakeLock; devMgrSvcIf->ReleaseWakeLock = DevmgrServiceReleaseWakeLock; HdfSListInit(&inst->hosts); + return true; + } else { + return false; } - return true; } - struct HdfObject *DevmgrServiceCreate() { static bool isDevMgrServiceInit = false; diff --git a/core/manager/src/devsvc_manager.c b/core/manager/src/devsvc_manager.c index 7feac34c..1c7b765a 100644 --- a/core/manager/src/devsvc_manager.c +++ b/core/manager/src/devsvc_manager.c @@ -16,14 +16,14 @@ #define HDF_LOG_TAG devsvc_manager -struct DevSvcRecord *DevSvcManagerSearchService(struct IDevSvcManager *inst, uint32_t serviceKey) +static 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"); + HDF_LOGE("failed to search service, devSvcManager is null"); return NULL; } @@ -44,13 +44,13 @@ int DevSvcManagerAddService(struct IDevSvcManager *inst, const char *svcName, st { struct DevSvcManager *devSvcManager = (struct DevSvcManager *)inst; if ((devSvcManager == NULL) || (service == NULL) || (svcName == NULL)) { - HDF_LOGE("Add service failed, input param is null"); + HDF_LOGE("failed to add service, input param is null"); return HDF_FAILURE; } struct DevSvcRecord *record = DevSvcRecordNewInstance(); if (record == NULL) { - HDF_LOGE("Add service failed, record is null"); + HDF_LOGE("failed to add service , record is null"); return HDF_FAILURE; } @@ -94,6 +94,7 @@ void DevSvcManagerRemoveService(struct IDevSvcManager *inst, const char *svcName HdfSListRemove(&devSvcManager->services, &serviceRecord->entry); OsalMutexUnlock(&devSvcManager->mutex); } + DevSvcRecordFreeInstance(serviceRecord); } struct HdfDeviceObject *DevSvcManagerGetObject(struct IDevSvcManager *inst, const char *svcName) @@ -134,7 +135,7 @@ bool DevSvcManagerConstruct(struct DevSvcManager *inst) devSvcMgrIf->GetObject = DevSvcManagerGetObject; HdfSListInit(&inst->services); if (OsalMutexInit(&inst->mutex) != HDF_SUCCESS) { - HDF_LOGE("Device service manager create mutex failed!"); + HDF_LOGE("failed to create device service manager mutex"); return false; } return true; @@ -171,4 +172,3 @@ struct IDevSvcManager *DevSvcManagerGetInstance() } return instance; } - diff --git a/core/manager/src/hdf_driver_installer.c b/core/manager/src/hdf_driver_installer.c index df91b52a..4071b2ee 100644 --- a/core/manager/src/hdf_driver_installer.c +++ b/core/manager/src/hdf_driver_installer.c @@ -23,7 +23,7 @@ static int DriverInstallerStartDeviceHost(uint32_t devHostId, const char *devHos } int ret = hostServiceIf->StartService(hostServiceIf); if (ret != HDF_SUCCESS) { - HDF_LOGE("Start host service failed, ret is: %d", ret); + HDF_LOGE("failed to start host service, ret: %d", ret); DevHostServiceFreeInstance(hostServiceIf); } return ret; diff --git a/core/manager/src/power_state_manager.c b/core/manager/src/power_state_manager.c index 99e02f50..29dcc7b1 100644 --- a/core/manager/src/power_state_manager.c +++ b/core/manager/src/power_state_manager.c @@ -62,7 +62,6 @@ static void PowerStateManagerReleaseWakeLock( static void PowerStateManagerConstruct(struct PowerStateManager *inst) { - // not support system acquire and release static struct IHdfSRefListener wakeLockRefListener = { .OnFirstAcquire = NULL, .OnLastRelease = NULL, diff --git a/core/manager/test/unittest/common/hdf_ioservice_test.cpp b/core/manager/test/unittest/common/hdf_ioservice_test.cpp index 75830ecf..9057d7be 100644 --- a/core/manager/test/unittest/common/hdf_ioservice_test.cpp +++ b/core/manager/test/unittest/common/hdf_ioservice_test.cpp @@ -72,12 +72,12 @@ int IoServiceTest::OnDevEventReceived(struct HdfDevEventlistener *listener, stru { OsalTimespec time; OsalGetTime(&time); - HDF_LOGE("%s received event[%d] from %s at %llu.%llu", (char *)listener->priv, eventCount++, (char *)service->priv, + HDF_LOGE("%s: received event[%d] from %s at %llu.%llu", (char *)listener->priv, eventCount++, (char *)service->priv, time.sec, time.usec); const char *string = HdfSbufReadString(data); if (string == nullptr) { - HDF_LOGE("fail to read string in event data"); + HDF_LOGE("failed to read string in event data"); return 0; } struct Eventlistener *l = CONTAINER_OF(listener, struct Eventlistener, listener); @@ -140,7 +140,7 @@ static int SendEvent(struct HdfIoService *serv, const char *eventData) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService001, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService001, TestSize.Level0) { struct HdfIoService *testServ = HdfIoServiceBind(testSvcName); ASSERT_NE(testServ, nullptr); @@ -149,11 +149,11 @@ HWTEST_F(IoServiceTest, HdfIoService001, TestSize.Level1) /* * * @tc.name: HdfIoService002 - * @tc.desc: service group linten test + * @tc.desc: service group listen test * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService002, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService002, TestSize.Level0) { struct HdfIoService *serv = HdfIoServiceBind(testSvcName); ASSERT_NE(serv, nullptr); @@ -203,7 +203,7 @@ HWTEST_F(IoServiceTest, HdfIoService002, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService003, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService003, TestSize.Level0) { struct HdfIoService *serv = HdfIoServiceBind(testSvcName); ASSERT_NE(serv, nullptr); @@ -258,7 +258,7 @@ HWTEST_F(IoServiceTest, HdfIoService003, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService004, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService004, TestSize.Level0) { struct HdfIoService *serv1 = HdfIoServiceBind(testSvcName); ASSERT_NE(serv1, nullptr); @@ -283,7 +283,7 @@ HWTEST_F(IoServiceTest, HdfIoService004, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService005, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService005, TestSize.Level0) { struct HdfIoService *serv = HdfIoServiceBind(testSvcName); ASSERT_NE(serv, nullptr); @@ -467,7 +467,7 @@ HWTEST_F(IoServiceTest, HdfIoService008, TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService009, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService009, TestSize.Level0) { struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); ASSERT_NE(group, nullptr); @@ -504,7 +504,7 @@ HWTEST_F(IoServiceTest, HdfIoService009, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService010, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService010, TestSize.Level0) { struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); ASSERT_NE(group, nullptr); @@ -544,7 +544,7 @@ HWTEST_F(IoServiceTest, HdfIoService010, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService011, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService011, TestSize.Level0) { struct HdfIoService *serv = HdfIoServiceBind(testSvcName); ASSERT_NE(serv, nullptr); @@ -573,7 +573,7 @@ HWTEST_F(IoServiceTest, HdfIoService011, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(IoServiceTest, HdfIoService012, TestSize.Level1) +HWTEST_F(IoServiceTest, HdfIoService012, TestSize.Level0) { struct HdfIoService *serv = HdfIoServiceBind(testSvcName); ASSERT_NE(serv, nullptr); diff --git a/core/manager/test/unittest/common/hdf_lite_manager_test.cpp b/core/manager/test/unittest/common/hdf_lite_manager_test.cpp index 8af642b1..623e4eb4 100644 --- a/core/manager/test/unittest/common/hdf_lite_manager_test.cpp +++ b/core/manager/test/unittest/common/hdf_lite_manager_test.cpp @@ -84,19 +84,19 @@ HWTEST_F(HdfManagerTest, HdfRegisterDevice001, TestSize.Level0) int32_t ret = HDF_FAILURE; struct HdfSBuf *data = NULL; struct HdfIoService *ioService = HdfIoServiceBind(SAMPLE_SERVICE); - ASSERT_TRUE(ioService != NULL); + EXPECT_TRUE(ioService != NULL); data = HdfSBufObtainDefaultSize(); - ASSERT_TRUE(data != NULL); + EXPECT_TRUE(data != NULL); EXPECT_TRUE(HdfSbufWriteString(data, "sample_driver")); EXPECT_TRUE(HdfSbufWriteString(data, "sample_service1")); - int64_t timeBefore = OsalGetSysTimeMs(); + uint64_t timeBefore = OsalGetSysTimeMs(); ret = ioService->dispatcher->Dispatch(&ioService->object, SAMPLE_DRIVER_REGISTER_DEVICE, data, NULL); EXPECT_TRUE(ret == HDF_SUCCESS); - int64_t timeAfter = OsalGetSysTimeMs(); + uint64_t timeAfter = OsalGetSysTimeMs(); EXPECT_TRUE((timeAfter - timeBefore) < 100); struct HdfIoService *ioService1 = HdfIoServiceBind("sample_service1"); - ASSERT_TRUE(ioService1 != NULL); + EXPECT_TRUE(ioService1 != NULL); HdfIoServiceRecycle(ioService1); ret = ioService->dispatcher->Dispatch(&ioService->object, SAMPLE_DRIVER_UNREGISTER_DEVICE, data, NULL); diff --git a/core/manager/test/unittest/common/hdf_sbuf_test.cpp b/core/manager/test/unittest/common/hdf_sbuf_test.cpp index 3f8fe8fe..4b5a9795 100644 --- a/core/manager/test/unittest/common/hdf_sbuf_test.cpp +++ b/core/manager/test/unittest/common/hdf_sbuf_test.cpp @@ -21,7 +21,7 @@ static const int DEFAULT_LOOP_COUNT = 500; static const int DEFAULT_BIG_LOOP_COUNT = 1000; static const int DATA_MOD = 26; -class SBufTest : public ::testing::Test { +class HdfSBufTest : public ::testing::Test { protected: void SetUp() override {} @@ -243,7 +243,7 @@ protected: * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestObtain001, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestObtain001, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtain(DEFAULT_SBUF_SIZE); ASSERT_NE(sBuf, nullptr); @@ -256,7 +256,7 @@ HWTEST_F(SBufTest, SbufTestObtain001, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestWriteUint64002, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestWriteUint64002, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -271,7 +271,7 @@ HWTEST_F(SBufTest, SbufTestWriteUint64002, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestWriteUint64Loop003, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestWriteUint64Loop003, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -288,7 +288,7 @@ HWTEST_F(SBufTest, SbufTestWriteUint64Loop003, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestReadUint64Loop004, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestReadUint64Loop004, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -297,7 +297,7 @@ HWTEST_F(SBufTest, SbufTestReadUint64Loop004, TestSize.Level1) auto ret = HdfSbufWriteInt64(sBuf, INT64_MAX); ASSERT_EQ(ret, true); } - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); uint64_t val = 0; for (int j = 0; j < loop; ++j) { @@ -318,7 +318,7 @@ HWTEST_F(SBufTest, SbufTestReadUint64Loop004, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestInt8005, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestInt8005, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -331,7 +331,7 @@ HWTEST_F(SBufTest, SbufTestInt8005, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); int8_t val = 0; @@ -351,7 +351,7 @@ HWTEST_F(SBufTest, SbufTestInt8005, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestInt16006, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestInt16006, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -364,7 +364,7 @@ HWTEST_F(SBufTest, SbufTestInt16006, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); int16_t val = 0; @@ -384,7 +384,7 @@ HWTEST_F(SBufTest, SbufTestInt16006, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestInt32007, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestInt32007, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -397,7 +397,7 @@ HWTEST_F(SBufTest, SbufTestInt32007, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); int32_t val = 0; @@ -417,7 +417,7 @@ HWTEST_F(SBufTest, SbufTestInt32007, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestInt64008, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestInt64008, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -430,7 +430,7 @@ HWTEST_F(SBufTest, SbufTestInt64008, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint64_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); int64_t val = 0; @@ -450,7 +450,7 @@ HWTEST_F(SBufTest, SbufTestInt64008, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestUInt32009, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestUInt32009, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -463,7 +463,7 @@ HWTEST_F(SBufTest, SbufTestUInt32009, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); uint32_t val = 0; @@ -483,7 +483,7 @@ HWTEST_F(SBufTest, SbufTestUInt32009, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestUInt16010, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestUInt16010, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -496,7 +496,7 @@ HWTEST_F(SBufTest, SbufTestUInt16010, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); uint16_t val = 0; @@ -516,7 +516,7 @@ HWTEST_F(SBufTest, SbufTestUInt16010, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestUInt8011, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestUInt8011, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -529,7 +529,7 @@ HWTEST_F(SBufTest, SbufTestUInt8011, TestSize.Level1) size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); uint8_t val = 0; @@ -549,7 +549,7 @@ HWTEST_F(SBufTest, SbufTestUInt8011, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestString012, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestString012, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -561,12 +561,11 @@ HWTEST_F(SBufTest, SbufTestString012, TestSize.Level1) ASSERT_EQ(ret, true); } - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); for (int j = 0; j < loop; ++j) { const char *readStr = HdfSbufReadString(readBuf); - ASSERT_NE(readStr, nullptr); ASSERT_EQ(std::string(readStr), str); } HdfSBufRecycle(readBuf); @@ -579,7 +578,7 @@ HWTEST_F(SBufTest, SbufTestString012, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestNullString013, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestNullString013, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -589,7 +588,7 @@ HWTEST_F(SBufTest, SbufTestNullString013, TestSize.Level1) ASSERT_EQ(true, ret); size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_NE((size_t)0, dataSize); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); auto val = HdfSbufReadString(readBuf); ASSERT_EQ(nullptr, val); @@ -607,7 +606,7 @@ HWTEST_F(SBufTest, SbufTestNullString013, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestBuffer014, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestBuffer014, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -619,7 +618,7 @@ HWTEST_F(SBufTest, SbufTestBuffer014, TestSize.Level1) ASSERT_EQ(ret, true); } - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); for (int j = 0; j < loop; ++j) { @@ -640,7 +639,7 @@ HWTEST_F(SBufTest, SbufTestBuffer014, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestNullBuffer015, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestNullBuffer015, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -650,7 +649,7 @@ HWTEST_F(SBufTest, SbufTestNullBuffer015, TestSize.Level1) ASSERT_EQ(true, ret); size_t dataSize = HdfSbufGetDataSize(sBuf); ASSERT_NE((size_t)0, dataSize); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); const uint8_t *buffVal = nullptr; uint32_t buffLen = 0; @@ -673,7 +672,7 @@ HWTEST_F(SBufTest, SbufTestNullBuffer015, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestRandomDataSeq016, TestSize.Level0) +HWTEST_F(HdfSBufTest, SbufTestRandomDataSeq016, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -683,7 +682,7 @@ HWTEST_F(SBufTest, SbufTestRandomDataSeq016, TestSize.Level0) bool ret = PushDataSequence(sBuf); ASSERT_EQ(true, ret); - HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)HdfSbufGetData(sBuf), HdfSbufGetDataSize(sBuf)); ASSERT_NE(readBuf, nullptr); ret = PullDataSequence(readBuf); @@ -698,7 +697,7 @@ HWTEST_F(SBufTest, SbufTestRandomDataSeq016, TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestRandomRWDataSeq017, TestSize.Level0) +HWTEST_F(HdfSBufTest, SbufTestRandomRWDataSeq017, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -731,7 +730,7 @@ HWTEST_F(SBufTest, SbufTestRandomRWDataSeq017, TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestSbufMove018, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestSbufMove018, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); @@ -768,7 +767,7 @@ HWTEST_F(SBufTest, SbufTestSbufMove018, TestSize.Level1) * @tc.type: FUNC * @tc.require: AR000F869B */ -HWTEST_F(SBufTest, SbufTestSbufMoveHalf019, TestSize.Level1) +HWTEST_F(HdfSBufTest, SbufTestSbufMoveHalf019, TestSize.Level1) { HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); ASSERT_NE(sBuf, nullptr); diff --git a/core/sec/include/hdf_sec.h b/core/sec/include/hdf_sec.h new file mode 100644 index 00000000..90e3fd73 --- /dev/null +++ b/core/sec/include/hdf_sec.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_SEC_H +#define HDF_SEC_H + +#if defined(__KERNEL__) +#include +#include +#else +#include +#include +#include +#endif + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define DEVICE_HDF_SECURE_NAME "hdf_secure" +#define HDF_SECURE_MAGIC 'S' + +/* event commands */ +#define HDF_SECURE_SET_INFO _IO(HDF_SECURE_MAGIC, 0x1) +#define HDF_SECURE_SET_CURRENT_ID _IO(HDF_SECURE_MAGIC, 0x2) +#define HDF_SECURE_DELETE_INFO _IO(HDF_SECURE_MAGIC, 0x3) + +#define HDF_DECLARE_BITMAP(name, bits) \ + uint64_t name[HDF_BITS_TO_LONGS(bits)] +#define HDF_BITS_TO_LONGS(nr) HDF_DIV_ROUND_UP(nr, HDF_BITS_PER_BYTE * sizeof(uint64_t)) +#define HDF_DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) +#define HDF_BITS_PER_BYTE 8 + +#define SECMAP_MAX_SIZE 64 +#define ID_MAX_SIZE 65 + +struct SecInfo { + char secId[ID_MAX_SIZE]; + HDF_DECLARE_BITMAP(secMap, SECMAP_MAX_SIZE); +}; +uint32_t hdf_permission_check(uint8_t type); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* HDF_SEC_H */ diff --git a/core/shared/include/hdf_device_info.h b/core/shared/include/hdf_device_info.h old mode 100644 new mode 100755 index a5fa7812..de2f2984 --- a/core/shared/include/hdf_device_info.h +++ b/core/shared/include/hdf_device_info.h @@ -12,9 +12,21 @@ #include "hdf_device_desc.h" #include "hdf_slist.h" +enum { + HDF_SERVICE_UNUSABLE, + HDF_SERVICE_USABLE, +}; + +enum { + HDF_DEV_LOCAL_SERVICE, + HDF_DEV_REMOTE_SERVICE, +}; + struct HdfDeviceInfo { struct HdfSListNode node; bool isDynamic; + uint16_t status; + uint16_t deviceType; uint16_t hostId; uint16_t deviceId; uint16_t policy; diff --git a/core/shared/include/hdf_io_service.h b/core/shared/include/hdf_io_service.h index 6887fa61..2fcdf3d8 100644 --- a/core/shared/include/hdf_io_service.h +++ b/core/shared/include/hdf_io_service.h @@ -20,8 +20,8 @@ extern "C" { #define DEV_MGR_NODE "dev_mgr" #define MAX_MODE_SIZE 0777 #define DEV_NODE_PATH_MODE 0755 -#define HDF_WRITE_READ _IOWR('b', 1, struct HdfSBuf) -#define HDF_READ_DEV_EVENT _IOR('b', 2, struct HdfSBuf) +#define HDF_WRITE_READ _IOWR('b', 1, struct HdfSBuf*) +#define HDF_READ_DEV_EVENT _IOR('b', 2, struct HdfSBuf*) #define HDF_LISTEN_EVENT_START _IO('b', 3) #define HDF_LISTEN_EVENT_STOP _IO('b', 4) #define HDF_LISTEN_EVENT_WAKEUP _IO('b', 5) diff --git a/core/shared/src/hdf_device_info.c b/core/shared/src/hdf_device_info.c old mode 100644 new mode 100755 index d30bb3fb..9228d56f --- a/core/shared/src/hdf_device_info.c +++ b/core/shared/src/hdf_device_info.c @@ -19,6 +19,8 @@ void HdfDeviceInfoConstruct(struct HdfDeviceInfo *deviceInfo) } deviceInfo->isDynamic = false; deviceInfo->hostId = 0; + deviceInfo->status = HDF_SERVICE_UNUSABLE; + deviceInfo->deviceType = HDF_DEV_LOCAL_SERVICE; deviceInfo->deviceId = 0; deviceInfo->policy = SERVICE_POLICY_INVALID; deviceInfo->priority = 0; diff --git a/core/shared/src/hdf_service_record.c b/core/shared/src/hdf_service_record.c index 269fcd7e..ebc9c389 100644 --- a/core/shared/src/hdf_service_record.c +++ b/core/shared/src/hdf_service_record.c @@ -27,4 +27,3 @@ void DevSvcRecordDelete(struct HdfSListNode *listEntry) OsalMemFree(listEntry); } } - diff --git a/figures/architecture-of-the-hdf.png b/figures/architecture-of-the-hdf.png index 2bd6a1d8..f4eb8c3c 100644 Binary files a/figures/architecture-of-the-hdf.png and b/figures/architecture-of-the-hdf.png differ diff --git a/include/config/device_resource_if.h b/include/config/device_resource_if.h index 4bc009ff..4775bd84 100644 --- a/include/config/device_resource_if.h +++ b/include/config/device_resource_if.h @@ -10,12 +10,12 @@ * @addtogroup DriverConfig * @{ * - * @brief Defines an API for HDF driver developers to read driver configuration information. + * @brief Defines APIs 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. + * the bytecodes into a configuration tree and provides APIs for developers to query the tree. * * @since 1.0 * @version 1.0 @@ -24,7 +24,7 @@ /** * @file device_resource_if.h * - * @brief Declares the API for querying the configuration tree. + * @brief Declares the APIs for querying the configuration tree. * * @since 1.0 * @version 1.0 @@ -142,7 +142,7 @@ struct DeviceResourceIface { 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. + * @brief Obtains the value 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. @@ -443,5 +443,5 @@ struct DeviceResourceIface *DeviceResourceGetIfaceInstance(DeviceResourceType ty #endif #endif /* __cplusplus */ -#endif // DEVICE_RESOURCE_IF_H +#endif /* DEVICE_RESOURCE_IF_H */ /** @} */ diff --git a/include/core/hdf_device_desc.h b/include/core/hdf_device_desc.h index 9c55e21c..367949cb 100644 --- a/include/core/hdf_device_desc.h +++ b/include/core/hdf_device_desc.h @@ -10,7 +10,7 @@ * @addtogroup Core * @{ * - * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * @brief Provides Hardware 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. @@ -177,21 +177,6 @@ struct SubscriberCallback { 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. * diff --git a/include/core/hdf_object.h b/include/core/hdf_object.h index d73da125..adfbbe72 100644 --- a/include/core/hdf_object.h +++ b/include/core/hdf_object.h @@ -10,7 +10,7 @@ * @addtogroup Core * @{ * - * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * @brief Provides Hardware 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. diff --git a/include/core/hdf_pm.h b/include/core/hdf_pm.h new file mode 100644 index 00000000..fbf6e3af --- /dev/null +++ b/include/core/hdf_pm.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ +#ifndef HDF_POWER_MANAGEMENT_H +#define HDF_POWER_MANAGEMENT_H + +#include "hdf_device_desc.h" +#include "osal_sysevent.h" + +enum PowerManagementMode { + HDF_POWER_SYS_CTRL, + HDF_POWER_DYNAMIC_CTRL, + HDF_POWER_MODE_MAX, +}; + +/** + * @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 { + int (*DozeResume)(struct HdfDeviceObject *deviceObject); + int (*DozeSuspend)(struct HdfDeviceObject *deviceObject); + /** Wakes up the driver device. The driver developer implements the operation. */ + int (*Resume)(struct HdfDeviceObject *deviceObject); + /** Hibernates the driver device. The driver developer implements the operation. */ + int (*Suspend)(struct HdfDeviceObject *deviceObject); +}; + +static inline bool HdfPmIsWakeEvent(int sysEvent) +{ + return sysEvent >= KEVENT_POWER_RESUME && sysEvent <= KEVENT_POWER_DISPLAY_ON; +} + +int HdfPmRegisterPowerListener(struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener); +void HdfPmUnregisterPowerListener(struct HdfDeviceObject *deviceObject, const struct IPowerEventListener *listener); +void HdfPmAcquireDevice(struct HdfDeviceObject *deviceObject); +void HdfPmReleaseDevice(struct HdfDeviceObject *deviceObject); +void HdfPmSetMode(struct HdfDeviceObject *deviceObject, uint32_t mode); +#endif /* HDF_POWER_MANAGEMENT_H */ diff --git a/include/osal/osal_firmware.h b/include/osal/osal_firmware.h index 6053643a..2c82c5f4 100644 --- a/include/osal/osal_firmware.h +++ b/include/osal/osal_firmware.h @@ -87,6 +87,23 @@ struct OsalFwBlock { */ int32_t OsalRequestFirmware(struct OsalFirmware *fw, const char *fwName, void *device); +/** + * @brief Sets the offset for reading a firmware file to implement random access to the firmware file. + * + * @param fw Indicates the pointer to the firmware file {@link OsalFirmware}. + * @param offset Indicates the offset where the firmware content is to read. + * + * @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 OsalSeekFirmware(struct OsalFirmware *fw, uint32_t offset); + /** * @brief Reads a firmware file. * @@ -103,7 +120,7 @@ int32_t OsalRequestFirmware(struct OsalFirmware *fw, const char *fwName, void *d * @since 1.0 * @version 1.0 */ -int32_t OsalSeekFirmware(struct OsalFirmware *fw, uint32_t offset); +int32_t OsalReadFirmware(struct OsalFirmware *fw, struct OsalFwBlock *block); /** * @brief Releases a firmware file. @@ -122,15 +139,6 @@ int32_t OsalSeekFirmware(struct OsalFirmware *fw, uint32_t offset); * @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 diff --git a/include/osal/osal_sem.h b/include/osal/osal_sem.h index 80409757..eb36b185 100644 --- a/include/osal/osal_sem.h +++ b/include/osal/osal_sem.h @@ -37,6 +37,8 @@ extern "C" { #endif /* __cplusplus */ +#define OSAL_WAIT_FOREVER 0xFFFFFFFF + /** * @brief Describes a semaphore. */ diff --git a/include/utils/hdf_dlist.h b/include/utils/hdf_dlist.h index cc243f40..369cb089 100644 --- a/include/utils/hdf_dlist.h +++ b/include/utils/hdf_dlist.h @@ -194,6 +194,12 @@ static inline void DListMerge(struct DListHead *list, struct DListHead *head) &(pos)->member != (head); \ (pos) = CONTAINER_OF((pos)->member.next, type, member)) + +#define DLIST_FOR_EACH_ENTRY_REVERSE(pos, head, type, member) \ + for ((pos) = CONTAINER_OF((head)->prev, type, member); \ + &(pos)->member != (head); \ + (pos) = CONTAINER_OF((pos)->member.prev, 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. diff --git a/include/wifi/hdf_wifi_event.h b/include/wifi/hdf_wifi_event.h index a1c68fc8..cfae47b1 100644 --- a/include/wifi/hdf_wifi_event.h +++ b/include/wifi/hdf_wifi_event.h @@ -32,8 +32,8 @@ * @version 1.0 */ -#ifndef __HDF_WIFI_EVENT_H__ -#define __HDF_WIFI_EVENT_H__ +#ifndef HDF_WIFI_EVENT_H +#define HDF_WIFI_EVENT_H #include "hdf_wifi_cmd.h" #include "wifi_mac80211_ops.h" @@ -52,7 +52,7 @@ extern "C" { * @version 1.0 */ struct RateInfo { - uint8_t flags; /**< Flag field, used to indicate a specific rate transmission type of 802.11n */ + uint8_t flags; /**< Flag, 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) */ @@ -268,7 +268,7 @@ struct Ieee80211Mgmt { 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 */ + uint8_t array[2]; /**< Reserved */ uint32_t mgmtLen; /**< Management frame length */ struct Ieee80211Mgmt *mgmt; /**< Start address of the management frame */ }; @@ -482,5 +482,5 @@ int32_t HdfWifiEventResetResult(const uint8_t chipId, int32_t resetStatus); #endif #endif -#endif /* __HDF_WIFI_EVENT_H__ */ +#endif /* HDF_WIFI_EVENT_H */ /** @} */ diff --git a/include/wifi/hdf_wifi_product.h b/include/wifi/hdf_wifi_product.h index 1007523c..40bf8842 100644 --- a/include/wifi/hdf_wifi_product.h +++ b/include/wifi/hdf_wifi_product.h @@ -113,7 +113,7 @@ struct WifiModule* HdfWlanGetModule(void); struct HdfWlanDevice *HdfWlanGetWlanDevice(uint8_t chipId); /** - * @brief Send broadcast event. + * @brief Sends a broadcast event. * * @param id Indicates the ID of the event to send. * @param data Indicates the pointer to the event information. diff --git a/include/wifi/net_device.h b/include/wifi/net_device.h index d13adb0f..9b1b5963 100644 --- a/include/wifi/net_device.h +++ b/include/wifi/net_device.h @@ -387,7 +387,7 @@ struct TcpHeader { uint16_t sPort; /**< Source port number */ uint16_t dPort; /**< Destination port number */ uint32_t seqNum; /**< Sequence number */ - uint32_t ackNum; /**< Acknowledgement number */ + uint32_t ackNum; /**< Acknowledgment number */ uint8_t offset; /**< Header length */ uint8_t flags; /**< Flags */ uint16_t window; /**< Window size */ @@ -465,7 +465,7 @@ typedef struct NetDevice { 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} */ + unsigned 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 */ @@ -496,12 +496,12 @@ struct NetDeviceInterFace { 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, NetBuf *netBuff); /**< Sends data. */ + NetDevTxResult (*xmit)(struct NetDevice *netDev, 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, NetBuf *netBuff);/**< Selects a priority queue. */ + uint16_t (*selectQueue)(struct NetDevice *netDev, 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. @@ -658,7 +658,7 @@ int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, * @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}. + * @param status Indicates the network port state, as enumerated in {@link NetIfSatus}. * @param status Indicates the network port state, as enumerated in {@link NetIfSatus}. * * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. diff --git a/include/wifi/wifi_inc.h b/include/wifi/wifi_inc.h index f1ec5336..5e25c080 100644 --- a/include/wifi/wifi_inc.h +++ b/include/wifi/wifi_inc.h @@ -62,7 +62,7 @@ struct BusDev; * @version 1.0 */ enum WifiMainFeatureType { - HDF_WIFI_FEATURE_AP, /**< AP */ + HDF_WIFI_FEATURE_AP, /**< Access point (AP) */ HDF_WIFI_FEATURE_STA, /**< Station */ HDF_WIFI_FEATURE_P2P, /**< Peer-to-peer (P2P) */ HDF_WIFI_FEATURE_NAN, /**< Neighbor Awareness Networking (NAN) */ diff --git a/include/wifi/wifi_mac80211_ops.h b/include/wifi/wifi_mac80211_ops.h index eb498f91..4e1244bf 100644 --- a/include/wifi/wifi_mac80211_ops.h +++ b/include/wifi/wifi_mac80211_ops.h @@ -32,8 +32,8 @@ * @version 1.0 */ -#ifndef _WIFI_MAC80211_OPS_H_ -#define _WIFI_MAC80211_OPS_H_ +#ifndef WIFI_MAC80211_OPS_H +#define WIFI_MAC80211_OPS_H #include "net_device.h" #include "hdf_wifi_cmd.h" @@ -440,9 +440,9 @@ struct WlanAPConf { struct WlanHwCapability { void (*Release)(struct WlanHwCapability *self); /**< Function for releasing the hardware capability */ struct WlanBand *bands[IEEE80211_NUM_BANDS]; /**< Frequency bands */ - uint16_t htCapability; /**< High-throughput (HT) capability */ - uint16_t supportedRateCount;/**< Number of supported rates */ - uint16_t *supportedRates; /**< An array of supported rates in 100 kbit/s */ + uint16_t htCapability; /**< High-throughput (HT) capability */ + uint16_t supportedRateCount; /**< Number of supported rates */ + uint16_t *supportedRates; /**< An array of supported rates in 100 kbit/s */ }; /** @@ -767,5 +767,5 @@ struct HdfMac80211APOps { int32_t (*GetAssociatedStasInfo)(NetDevice *netDev, WifiStaInfo *staInfo, uint32_t num); }; -#endif // _WIFI_MAC80211_OPS_H_ +#endif // WIFI_MAC80211_OPS_H /** @} */ diff --git a/include/wifi/wifi_module.h b/include/wifi/wifi_module.h index f58b04dd..6bb836c2 100644 --- a/include/wifi/wifi_module.h +++ b/include/wifi/wifi_module.h @@ -206,7 +206,7 @@ int16_t InitWifiModule(struct WifiModule *module, const struct HdfConfigWlanModu #define RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipOps, opsName) \ do { \ - if ((chipOps) == NULL ||(chipOps)->opsName == NULL) { \ + if ((chipOps) == NULL || (chipOps)->opsName == NULL) { \ HDF_LOGE("macOps" #opsName "not implement"); \ return HDF_ERR_INVALID_OBJECT; \ } \ diff --git a/model/display/driver/hdf_disp.c b/model/display/driver/hdf_disp.c index 910d5ffe..49470eb9 100644 --- a/model/display/driver/hdf_disp.c +++ b/model/display/driver/hdf_disp.c @@ -13,133 +13,141 @@ #define OFFSET_TWO_BYTE 16 -struct DispOperations *g_dispOps = NULL; +static struct PlatformOps *g_platformOps = NULL; -int32_t DispRegister(struct DispOperations *ops) +int32_t PlatformRegister(struct PlatformOps *ops) { - if (g_dispOps == NULL) { - g_dispOps = ops; + if (g_platformOps == NULL) { + g_platformOps = ops; HDF_LOGI("%s: disp ops register success", __func__); return HDF_SUCCESS; } - HDF_LOGD("%s: disp ops registered", __func__); + HDF_LOGD("%s: success", __func__); return HDF_FAILURE; } +static struct PlatformOps *GetPlatformOps(void) +{ + return g_platformOps; +} + +static int32_t InitDisp(uint32_t devId); +static int32_t DispOn(uint32_t devId); +static int32_t DispOff(uint32_t devId); +static int32_t SetDispBacklight(uint32_t devId, uint32_t level); +static int32_t GetDispInfo(uint32_t devId, struct DispInfo *info); + struct DispOperations *GetDispOps(void) { - return g_dispOps; + static struct DispOperations dispOps = { + .init = InitDisp, + .on = DispOn, + .off = DispOff, + .setBacklight = SetDispBacklight, + .getDispInfo = GetDispInfo, + }; + return &dispOps; +} + +#ifdef __KERNEL__ +EXPORT_SYMBOL(GetDispOps); +#endif + +static int32_t InitDisp(uint32_t devId) +{ + return 0; } static int32_t DispOn(uint32_t devId) { - int32_t ret; - struct DispOperations *ops = NULL; + int32_t ret = HDF_FAILURE; + struct PlatformOps *ops = NULL; - ops = GetDispOps(); - if (ops == NULL) { - HDF_LOGE("%s: ops is null", __func__); - return HDF_FAILURE; - } - if (ops->on != NULL) { + ops = GetPlatformOps(); + if (ops && ops->on) { ret = ops->on(devId); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: ops on failed", __func__); - return HDF_FAILURE; - } } - return HDF_SUCCESS; + return ret; } static int32_t DispOff(uint32_t devId) { - int32_t ret; - struct DispOperations *ops = NULL; + int32_t ret = HDF_FAILURE; + struct PlatformOps *ops = NULL; - ops = GetDispOps(); - if (ops == NULL) { - HDF_LOGE("%s: ops is null", __func__); - return HDF_FAILURE; - } - if (ops->off != NULL) { + ops = GetPlatformOps(); + if (ops && ops->off) { ret = ops->off(devId); + } + return ret; +} + +static int32_t SetDispBacklight(uint32_t devId, uint32_t level) +{ + int32_t ret = HDF_FAILURE; + struct PanelStatus *panelStatus = NULL; + + struct PanelInfo *info = GetPanelInfo(devId); + if (info == NULL) { + HDF_LOGE("%s:GetPanelInfo failed", __func__); + return HDF_FAILURE; + } + if (level > info->blk.maxLevel) { + level = info->blk.maxLevel; + } else if (level < info->blk.minLevel && level != 0) { + level = info->blk.minLevel; + } + struct PlatformOps *ops = GetPlatformOps(); + if (ops == NULL) { + HDF_LOGE("%s: ops is null", __func__); + return HDF_FAILURE; + } + if (ops->setBacklight != NULL) { + ret = ops->setBacklight(devId, level); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: ops off failed", __func__); + HDF_LOGE("%s: setBacklight failed", __func__); return HDF_FAILURE; } } + if (ret == HDF_SUCCESS) { + panelStatus = GetPanelStatus(devId); + if (!panelStatus) { + HDF_LOGE("%s: panelStatus is null", __func__); + return HDF_FAILURE; + } + panelStatus->currLevel = level; + } + HDF_LOGI("%s:level = %u", __func__, level); return HDF_SUCCESS; } -static int32_t DispInit(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +static int32_t GetDispInfo(uint32_t devId, struct DispInfo *info) { - (void)device; - (void)rspData; - int32_t ret; - uint32_t devId = 0; + struct PlatformOps *ops = NULL; - if (reqData == NULL) { - return HDF_ERR_INVALID_PARAM; - } - if (!HdfSbufReadUint32(reqData, &devId)) { - HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + if (info == NULL) { + HDF_LOGE("%s:info is null", __func__); return HDF_FAILURE; } - - struct DispOperations *ops = NULL; - ops = GetDispOps(); + ops = GetPlatformOps(); if (ops == NULL) { HDF_LOGE("%s: ops is null", __func__); return HDF_FAILURE; } - if (ops->init != NULL) { - ret = ops->init(devId); - if (ret) { - HDF_LOGE("%s: init failed", __func__); - return HDF_FAILURE; - } - } - return HDF_SUCCESS; -} - -static int32_t GetDispInfo(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) -{ - (void)device; - (void)rspData; - uint32_t devId = 0; - struct DispInfo info; - struct DispOperations *ops = NULL; - - if (reqData == NULL) { - return HDF_ERR_INVALID_PARAM; - } - if (!HdfSbufReadUint32(reqData, &devId)) { - HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); - return HDF_FAILURE; - } - - ops = GetDispOps(); - if (ops == NULL) { - HDF_LOGE("%s: ops is null", __func__); - return HDF_FAILURE; - } - (void)memset_s(&info, sizeof(struct DispInfo), 0, sizeof(struct DispInfo)); if (ops->getDispInfo != NULL) { - if (ops->getDispInfo(devId, &info)) { + if (ops->getDispInfo(devId, info)) { HDF_LOGE("%s: getDispInfo failed", __func__); return HDF_FAILURE; } } - if (!HdfSbufWriteBuffer(rspData, &info, sizeof(struct DispInfo)) != 0) { - HDF_LOGE("%s: copy info failed", __func__); - return HDF_FAILURE; - } return HDF_SUCCESS; } -static int32_t SetPowerMode(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +static int32_t SetPowerStatus(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) { uint32_t para = 0; + int32_t ret = HDF_FAILURE; + struct PanelStatus *panelStatus = NULL; (void)device; (void)rspData; @@ -151,20 +159,58 @@ static int32_t SetPowerMode(struct HdfDeviceObject *device, struct HdfSBuf *reqD return HDF_FAILURE; } uint32_t devId = (para >> OFFSET_TWO_BYTE) & 0xffff; - uint32_t mode = para & 0xffff; - if (mode == DISP_ON) { - return DispOn(devId); + uint32_t powerStatus = para & 0xffff; + switch (powerStatus) { + case POWER_STATUS_ON: + ret = DispOn(devId); + break; + case POWER_STATUS_OFF: + ret = DispOff(devId); + break; + default: + HDF_LOGE("%s: not support powerStatus: %d", __func__, powerStatus); + break; } - if (mode == DISP_OFF) { - return DispOff(devId); + if (ret == HDF_SUCCESS) { + panelStatus = GetPanelStatus(devId); + if (panelStatus == NULL) { + HDF_LOGE("%s: panelStatus is null", __func__); + return HDF_FAILURE; + } + panelStatus->powerStatus = powerStatus; } - HDF_LOGE("not support mode:%u", mode); - return HDF_FAILURE; + return ret; +} + +static int32_t GetPowerStatus(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + uint32_t devId = 0; + struct PanelStatus *panelStatus = NULL; + + (void)device; + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(reqData, &devId)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + return HDF_FAILURE; + } + panelStatus = GetPanelStatus(devId); + if (!panelStatus) { + HDF_LOGE("%s: panelStatus is null", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteUint32(rspData, panelStatus->powerStatus)) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; } static int32_t SetBacklight(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) { int32_t ret; + (void)device; (void)rspData; if (reqData == NULL) { @@ -177,37 +223,67 @@ static int32_t SetBacklight(struct HdfDeviceObject *device, struct HdfSBuf *reqD } uint32_t devId = (para >> OFFSET_TWO_BYTE) & 0xffff; uint32_t level = para & 0xffff; - struct PanelInfo *info = GetPanelInfo(devId); - if (info == NULL) { - HDF_LOGE("%s:GetPanelInfo failed", __func__); + ret = SetDispBacklight(devId, level); + return ret; +} + +static int32_t GetBacklight(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + uint32_t devId = 0; + struct PanelStatus *panelStatus = NULL; + + (void)device; + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(reqData, &devId)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); return HDF_FAILURE; } - if (level > info->blk.maxLevel) { - level = info->blk.maxLevel; - } else if (level < info->blk.minLevel && level != 0) { - level = info->blk.minLevel; - } - struct DispOperations *ops = GetDispOps(); - if (ops == NULL) { - HDF_LOGE("%s: ops is null", __func__); + panelStatus = GetPanelStatus(devId); + if (!panelStatus) { + HDF_LOGE("%s: panelStatus is null", __func__); return HDF_FAILURE; } - if (ops->setBacklight != NULL) { - ret = ops->setBacklight(devId, level); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: setBacklight failed", __func__); - return HDF_FAILURE; - } + if (!HdfSbufWriteUint32(rspData, panelStatus->currLevel)) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t GetInfo(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)device; + (void)rspData; + uint32_t devId = 0; + struct DispInfo info; + + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(reqData, &devId)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + return HDF_FAILURE; + } + (void)memset_s(&info, sizeof(struct DispInfo), 0, sizeof(struct DispInfo)); + if (GetDispInfo(devId, &info) != HDF_SUCCESS) { + HDF_LOGE("%s: GetDispInfo failed", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteBuffer(rspData, &info, sizeof(struct DispInfo)) != 0) { + HDF_LOGE("%s: copy info failed", __func__); + return HDF_FAILURE; } - HDF_LOGI("%s:level = %u", __func__, level); return HDF_SUCCESS; } DispCmdHandle g_dispCmdHandle[] = { - DispInit, - GetDispInfo, - SetPowerMode, + GetPowerStatus, + GetInfo, + SetPowerStatus, SetBacklight, + GetBacklight, }; static int32_t DispCmdProcess(struct HdfDeviceObject *device, int32_t cmd, struct HdfSBuf *reqData, @@ -253,10 +329,27 @@ static int HdfDispBind(struct HdfDeviceObject *dev) static int32_t HdfDispEntryInit(struct HdfDeviceObject *object) { + int32_t ret; + int32_t i; + struct PlatformOps *ops = GetPlatformOps(); + if (object == NULL) { HDF_LOGE("%s: object is null!", __func__); return HDF_FAILURE; } + if (ops == NULL) { + HDF_LOGE("%s: ops is null", __func__); + return HDF_FAILURE; + } + if (ops->init != NULL) { + for (i = 0; i < g_numRegisteredPanel; i++) { + ret = ops->init(i); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: init failed", __func__); + return HDF_FAILURE; + } + } + } return HDF_SUCCESS; } diff --git a/model/display/driver/hdf_disp.h b/model/display/driver/hdf_disp.h index c2acd9a4..7a8a5015 100644 --- a/model/display/driver/hdf_disp.h +++ b/model/display/driver/hdf_disp.h @@ -45,11 +45,20 @@ struct DispOperations { int32_t (*getDispInfo)(uint32_t devId, struct DispInfo *info); }; +struct PlatformOps { + int32_t (*init)(uint32_t devId); + int32_t (*on)(uint32_t devId); + int32_t (*off)(uint32_t devId); + int32_t (*setBacklight)(uint32_t devId, uint32_t level); + int32_t (*getDispInfo)(uint32_t devId, struct DispInfo *info); +}; + enum PowerMode { DISP_ON, DISP_OFF, }; -int32_t DispRegister(struct DispOperations *ops); +int32_t PlatformRegister(struct PlatformOps *ops); struct PanelInfo *GetPanelInfo(int32_t index); +struct PanelStatus *GetPanelStatus(int32_t index); #endif /* HDF_DISP_H */ diff --git a/model/display/driver/hi35xx_disp.c b/model/display/driver/hi35xx_disp.c index 18a31425..44665b15 100644 --- a/model/display/driver/hi35xx_disp.c +++ b/model/display/driver/hi35xx_disp.c @@ -6,6 +6,7 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "hi35xx_disp.h" #include #include "hdf_base.h" #include "hdf_device_desc.h" @@ -14,7 +15,6 @@ #include "lcd_abs_if.h" #include "osal_io.h" #include "pwm_if.h" -#include "hi35xx_disp.h" #define TRANSFORM_KILO 1000 #define TRANSFORM_MILL 1000000 @@ -186,10 +186,13 @@ static uint32_t CalcDataRate(struct PanelInfo *info) } else { bitClk = bitNum / TRANSFORM_MILL + 1; } + if (!info->mipi.lane) { + return HDF_FAILURE; + } if ((bitClk % info->mipi.lane) == 0) { return bitClk / info->mipi.lane; } - return bitClk / info->mipi.lane + 1; + return (bitClk / info->mipi.lane) + 1; } static int32_t MipiDsiInit(struct PanelInfo *info) @@ -225,7 +228,7 @@ static int32_t MipiDsiInit(struct PanelInfo *info) HDF_LOGE("%s:MipiDsiSetCfg failed", __func__); } MipiDsiClose(mipiHandle); - HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d", __func__, cfg.pixelClk, cfg.phyDataRate); + HDF_LOGI("%s:pixelClk = %d, phyDataRate = %u", __func__, cfg.pixelClk, cfg.phyDataRate); return ret; } @@ -425,7 +428,7 @@ static int32_t Hi35xxSetBacklight(uint32_t devId, uint32_t level) return HDF_SUCCESS; } -struct DispOperations g_hi35xxOps = { +struct PlatformOps g_hi35xxOps = { .init = Hi35xxInit, .on = Hi35xxOn, .off = Hi35xxOff, @@ -439,7 +442,7 @@ static int32_t Hi35xxEntryInit(struct HdfDeviceObject *object) HDF_LOGE("%s: param is null!", __func__); return HDF_FAILURE; } - return DispRegister(&g_hi35xxOps); + return PlatformRegister(&g_hi35xxOps); } struct HdfDriverEntry g_hi35xxDevEntry = { diff --git a/model/display/driver/lcd_abs_if.c b/model/display/driver/lcd_abs_if.c index d414c216..c95d2e50 100644 --- a/model/display/driver/lcd_abs_if.c +++ b/model/display/driver/lcd_abs_if.c @@ -6,15 +6,15 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "lcd_abs_if.h" #include #include "hdf_device_desc.h" #include "osal.h" -#include "lcd_abs_if.h" /* support max panel number */ #define PANEL_MAX 2 static struct PanelData *g_panelData[PANEL_MAX]; -static int32_t numRegisteredPanel; +int32_t g_numRegisteredPanel; int32_t PanelDataRegister(struct PanelData *data) { @@ -24,10 +24,10 @@ int32_t PanelDataRegister(struct PanelData *data) HDF_LOGE("%s: panel data is null", __func__); return HDF_ERR_INVALID_PARAM; } - if (numRegisteredPanel == PANEL_MAX) { + if (g_numRegisteredPanel == PANEL_MAX) { return HDF_FAILURE; } - numRegisteredPanel++; + g_numRegisteredPanel++; for (i = 0; i < PANEL_MAX; i++) { if (g_panelData[i] == NULL) { break; @@ -60,3 +60,13 @@ struct PanelInfo *GetPanelInfo(int32_t index) return g_panelData[index]->info; } +struct PanelStatus *GetPanelStatus(const int32_t index) +{ + if ((index >= PANEL_MAX) || index < 0) { + return NULL; + } + if (g_panelData[index] == NULL) { + return NULL; + } + return g_panelData[index]->status; +} diff --git a/model/display/driver/lcd_abs_if.h b/model/display/driver/lcd_abs_if.h index e35ce204..04ed31ae 100644 --- a/model/display/driver/lcd_abs_if.h +++ b/model/display/driver/lcd_abs_if.h @@ -26,7 +26,7 @@ enum BacklightType { BLK_MIPI, }; -/* output timming */ +/* output timing */ enum IntfSync { OUTPUT_USER = 0, /* User timing */ OUTPUT_PAL, /* PAL standard */ @@ -85,6 +85,14 @@ struct MipiDsiDesc { enum DsiOutFormat format; }; +enum PowerStatus { + POWER_STATUS_ON, /* The power status is on */ + POWER_STATUS_STANDBY, /* The power status is standby */ + POWER_STATUS_SUSPEND, /* The power status is suspend */ + POWER_STATUS_OFF, /* The power status is off */ + POWER_STATUS_BUTT +}; + struct BlkDesc { uint32_t type; uint32_t minLevel; @@ -114,14 +122,21 @@ struct PanelInfo { struct PwmCfg pwm; }; +struct PanelStatus { + enum PowerStatus powerStatus; + uint32_t currLevel; +}; struct PanelData { struct PanelInfo *info; + struct PanelStatus *status; int32_t (*init)(void); int32_t (*on)(void); int32_t (*off)(void); int32_t (*setBacklight)(uint32_t level); }; +extern int32_t g_numRegisteredPanel; + int32_t PanelDataRegister(struct PanelData *data); #endif /* LCD_ABS_IF_H */ diff --git a/model/display/driver/lcdkit/lcdkit_parse_config.c b/model/display/driver/lcdkit/lcdkit_parse_config.c index 89a66d49..64c3d3b8 100644 --- a/model/display/driver/lcdkit/lcdkit_parse_config.c +++ b/model/display/driver/lcdkit/lcdkit_parse_config.c @@ -45,6 +45,8 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, return HDF_FAILURE; } int32_t ret; + int32_t i; + int32_t num = 0; cmd->count = count; cmd->dsiCmd = dsiCmd; uint8_t *tmpArray = array; @@ -56,6 +58,9 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, tmpCmd->payload = (uint8_t *)OsalMemCalloc(tmpCmd->dataLen * sizeof(uint8_t)); if (tmpCmd->payload == NULL) { HDF_LOGE("%s: OsalMemCalloc failed", __func__); + for (i = 0; i < num; i++) { + OsalMemFree(dsiCmd[i]->payload); + } OsalMemFree(array); OsalMemFree(dsiCmd); cmd->dsiCmd = NULL; @@ -63,9 +68,12 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, return HDF_FAILURE; } - ret = memcpy_s(tmpCmd->payload, tmpCmd->dataLen, &tmpArray[DSI_CMD_HEAD], tmpCmd->dataLen); + ret = memcpy_s(tmpCmd->payload, tmpCmd->dataLen, &tmpArray[DSI_CMD_HEAD], DSI_CMD_HEAD); if (ret != EOK) { HDF_LOGE("%s: memcpy_s failed, ret %d", __func__, ret); + for (i = 0; i < num; i++) { + OsalMemFree(dsiCmd[i]->payload); + } OsalMemFree(array); OsalMemFree(dsiCmd); cmd->dsiCmd = NULL; @@ -76,6 +84,7 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, tmpArray += DSI_CMD_HEAD + tmpCmd->dataLen; tmpCmd++; count--; + num++; len -= DSI_CMD_HEAD + tmpCmd->dataLen; } OsalMemFree(array); diff --git a/model/display/driver/lcdkit/lite_lcdkit.c b/model/display/driver/lcdkit/lite_lcdkit.c index 219543a6..c7db0d7b 100644 --- a/model/display/driver/lcdkit/lite_lcdkit.c +++ b/model/display/driver/lcdkit/lite_lcdkit.c @@ -48,7 +48,7 @@ static int32_t LcdkitInit(void) struct PanelConfig *panelCfg = GetPanelCfg(); if (panelCfg->info.intfType != MIPI_DSI) { - HDF_LOGE("%s:not support intf: %d", __func__, panelCfg->info.intfType); + HDF_LOGE("%s:not support intf: %u", __func__, panelCfg->info.intfType); return HDF_FAILURE; } ret = PowerInit(); @@ -65,6 +65,8 @@ static int32_t LcdkitInit(void) if (panelCfg->info.blk.type == BLK_PWM) { panelCfg->pwmHandle = PwmOpen(panelCfg->info.pwm.dev); if (panelCfg->pwmHandle == NULL) { + MipiDsiClose(panelCfg->dsiHandle); + panelCfg->dsiHandle = NULL; HDF_LOGE("%s: PwmOpen failed", __func__); return HDF_FAILURE; } @@ -222,8 +224,8 @@ static int32_t SetBacklightByMipi(uint32_t level) { int32_t ret; struct PanelConfig *panelCfg = GetPanelCfg(); - uint8_t payLoad[] = { 0x51, 0x00 }; - struct DsiCmdDesc bklCmd = { 0x15, 0, sizeof(payLoad), payLoad }; + uint8_t payLoad[] = { 0x51, 0x00 }; // panel backlight cmd + struct DsiCmdDesc bklCmd = { 0x15, 0, sizeof(payLoad), payLoad }; // dsi backlight cmd if (panelCfg->dsiHandle == NULL) { HDF_LOGE("%s: dsiHandle is null", __func__); diff --git a/model/display/driver/panel/mipi_icn9700.c b/model/display/driver/panel/mipi_icn9700.c index d63f207f..311e4c60 100644 --- a/model/display/driver/panel/mipi_icn9700.c +++ b/model/display/driver/panel/mipi_icn9700.c @@ -28,12 +28,12 @@ #define HORIZONTAL_BACK_PORCH 20 #define HORIZONTAL_FRONT_PORCH 20 #define HORIZONTAL_SYNC_WIDTH 10 -#define VERTIACL_BACK_PORCH 14 -#define VERTIACL_FRONT_PORCH 16 -#define VERTIACL_SYNC_WIDTH 2 +#define VERTICAL_BACK_PORCH 14 +#define VERTICAL_FRONT_PORCH 16 +#define VERTICAL_SYNC_WIDTH 2 #define FRAME_RATE 60 -/* panel on commond payload */ +/* panel on command payload */ static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A }; static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 }; static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B }; @@ -84,7 +84,7 @@ struct DsiCmdDesc g_OnCmd[] = { { 0x05, 120, sizeof(g_payLoad20), g_payLoad20 }, }; -/* panel off commond payload */ +/* panel off command payload */ static uint8_t g_offPayLoad0[] = { 0x28 }; static uint8_t g_offPayLoad1[] = { 0x10 }; struct DsiCmdDesc g_offCmd[] = { @@ -257,12 +257,12 @@ static struct PanelInfo g_panelInfo = { .hbp = HORIZONTAL_BACK_PORCH, /* horizontal back porch */ .hfp = HORIZONTAL_FRONT_PORCH, /* horizontal front porch */ .hsw = HORIZONTAL_SYNC_WIDTH, /* horizontal sync width */ - .vbp = VERTIACL_BACK_PORCH, /* vertiacl back porch */ - .vfp = VERTIACL_FRONT_PORCH, /* vertiacl front porch */ - .vsw = VERTIACL_SYNC_WIDTH, /* vertiacl sync width */ + .vbp = VERTICAL_BACK_PORCH, /* vertical back porch */ + .vfp = VERTICAL_FRONT_PORCH, /* vertical front porch */ + .vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */ .frameRate = FRAME_RATE, /* frame rate */ .intfType = MIPI_DSI, /* panel interface type */ - .intfSync = OUTPUT_USER, /* output timming type */ + .intfSync = OUTPUT_USER, /* output timing type */ /* mipi config info */ .mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT }, /* backlight config info */ @@ -270,8 +270,14 @@ static struct PanelInfo g_panelInfo = { .pwm = { BLK_PWM1, PWM_MAX_PERIOD }, }; +static struct PanelStatus g_panelStatus = { + .powerStatus = POWER_STATUS_OFF, + .currLevel = MIN_LEVEL, +}; + static struct PanelData g_panelData = { .info = &g_panelInfo, + .status = &g_panelStatus, .init = Icn9700Init, .on = Icn9700On, .off = Icn9700Off, diff --git a/model/display/driver/panel/ssp_st7789.c b/model/display/driver/panel/ssp_st7789.c index e19a625b..7dec843a 100644 --- a/model/display/driver/panel/ssp_st7789.c +++ b/model/display/driver/panel/ssp_st7789.c @@ -124,24 +124,24 @@ static int32_t LcdResetOn(void) ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioSetDir failed, ret:%d", ret); + HDF_LOGE("set lcd reset dir failed, ret:%d", ret); return HDF_FAILURE; } ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioWrite failed, ret:%d", ret); + HDF_LOGE("set lcd reset hi failed, ret:%d", ret); return HDF_FAILURE; } ret = GpioWrite(RESET_GPIO, GPIO_VAL_LOW); if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioWrite failed, ret:%d", ret); + HDF_LOGE("set lcd reset how failed, ret:%d", ret); return HDF_FAILURE; } /* delay 10ms */ OsalMSleep(10); ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioWrite failed, ret:%d", ret); + HDF_LOGE("set lcd reset hi after delay failed, ret:%d", ret); return HDF_FAILURE; } /* delay 120ms */ diff --git a/model/display/driver/panel/ssp_st7789.h b/model/display/driver/panel/ssp_st7789.h index 22f2356e..b80cebe9 100644 --- a/model/display/driver/panel/ssp_st7789.h +++ b/model/display/driver/panel/ssp_st7789.h @@ -16,7 +16,6 @@ #define BITS_PER_BYTE 8 #define BITS_PER_WORD 9 #define SPI_MAX_SPEED 115200 -#define SYS_WRITEL(addr, value) ((*(volatile unsigned int *)(addr)) = (value)) struct LcdCmd { uint8_t cmd; diff --git a/model/input/driver/event_hub.c b/model/input/driver/event_hub.c index 3c11bc4c..264e63c7 100644 --- a/model/input/driver/event_hub.c +++ b/model/input/driver/event_hub.c @@ -26,6 +26,12 @@ void PushOnePackage(InputDevice *inputDev, uint32_t type, uint32_t code, int32_t { OsalTimespec time; EventPackage package = {0}; + + if (inputDev == NULL) { + HDF_LOGE("%s: parm is null", __func__); + return; + } + package.type = type; package.code = code; package.value = value; diff --git a/model/input/driver/hdf_hid.c b/model/input/driver/hdf_hid.c deleted file mode 100755 index 5cd3ee27..00000000 --- a/model/input/driver/hdf_hid.c +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. - * - * HDF is dual licensed: you can use it either under the terms of - * the GPL, or the BSD license, at your option. - * See the LICENSE file in the root of this repository for complete details. - */ - -#include -#include "hdf_device_desc.h" -#include "hdf_log.h" - -static int32_t HdfHIDDriverInit(struct HdfDeviceObject *device) -{ - (void)device; - return HDF_SUCCESS; -} - -static int32_t HdfHIDDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) -{ - (void)cmd; - if (client == NULL || data == NULL || reply == NULL) { - HDF_LOGE("%s: param is null", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t HdfHIDDriverBind(struct HdfDeviceObject *device) -{ - if (device == NULL) { - return HDF_ERR_INVALID_PARAM; - } - static struct IDeviceIoService hidService = { - .Dispatch = HdfHIDDispatch, - }; - device->service = &hidService; - return HDF_SUCCESS; -} - -struct HdfDriverEntry g_hdfHIDEntry = { - .moduleVersion = 1, - .moduleName = "HDF_HID", - .Bind = HdfHIDDriverBind, - .Init = HdfHIDDriverInit, -}; - -HDF_INIT(g_hdfHIDEntry); \ No newline at end of file diff --git a/model/input/driver/hdf_hid_adapter.c b/model/input/driver/hdf_hid_adapter.c new file mode 100644 index 00000000..b6e2218d --- /dev/null +++ b/model/input/driver/hdf_hid_adapter.c @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include +#include "hdf_device_desc.h" +#include "osal_mem.h" +#include "hdf_log.h" +#include "event_hub.h" +#include "hdf_input_device_manager.h" +#include "hdf_hid_adapter.h" + +InputDevice *cachedHid[MAX_INPUT_DEV_NUM]; + +static bool HaveHidCache(void) +{ + if (cachedHid[0] == NULL) { + return false; + } + return true; +} + +static void LoadCachedHid(void) +{ + int32_t i = 0; + int32_t ret; + if (!HaveHidCache()) { + HDF_LOGI("%s: exit", __func__); + return; + } + while (i < MAX_INPUT_DEV_NUM && cachedHid[i] != NULL) { + ret = RegisterInputDevice(cachedHid[i]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: add %s failed", __func__, cachedHid[i]->devName); + } + cachedHid[i] = NULL; + i++; + } +} + +static InputDevice* HidConstructInputDev(HidInfo info) +{ + InputDevice *inputDev = (InputDevice *)OsalMemAlloc(sizeof(InputDevice)); + if (inputDev == NULL) { + HDF_LOGE("%s: instance input device failed", __func__); + return NULL; + } + (void)memset_s(inputDev, sizeof(InputDevice), 0, sizeof(InputDevice)); + + inputDev->devType = info.devType; + inputDev->devName = info.devName; + return inputDev; +} + +static InputDevice* DoRegisterInputDev(InputDevice* inputDev) +{ + int32_t ret; + + ret = RegisterInputDevice(inputDev); + if (ret == HDF_SUCCESS) { + return inputDev; + } else { + OsalMemFree(inputDev); + inputDev = NULL; + return NULL; + } +} + +static InputDevice* CacheHid(InputDevice* inputDev) +{ + int32_t i = 0; + while ((i < MAX_INPUT_DEV_NUM) && (cachedHid[i] != NULL)) { + i++; + } + if (i < MAX_INPUT_DEV_NUM) { + cachedHid[i] = inputDev; + return inputDev; + } + return NULL; +} + +static bool InputDriverLoaded(void) +{ + InputManager* g_inputManager = GetInputManager(); + if ((g_inputManager != NULL) && (g_inputManager->initialized != false)) { + return true; + } + return false; +} + +void* HidRegisterHdfInputDev(HidInfo info) +{ + InputDevice* inputDev = HidConstructInputDev(info); + if (inputDev == NULL) { + HDF_LOGE("%s: hid construct input Dev failed", __func__); + return NULL; + } + + if (InputDriverLoaded()) { + return DoRegisterInputDev(inputDev); + } else { + return CacheHid(inputDev); + } +} + +void HidUnregisterHdfInputDev(const void *inputDev) +{ + if (inputDev == NULL) { + HDF_LOGE("%s: inputDev is null", __func__); + } + UnregisterInputDevice((InputDevice *)inputDev); + inputDev = NULL; +} + +void HidReportEvent(const void *inputDev, uint32_t type, uint32_t code, int32_t value) +{ + PushOnePackage((InputDevice *)inputDev, type, code, value); +} + +static int32_t HdfHIDDriverInit(struct HdfDeviceObject *device) +{ + (void)device; + static bool cachedHidRegistered = false; + if (!cachedHidRegistered) { + cachedHidRegistered = true; + LoadCachedHid(); + } + return HDF_SUCCESS; +} + +static int32_t HdfHIDDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)cmd; + if (client == NULL || data == NULL || reply == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t HdfHIDDriverBind(struct HdfDeviceObject *device) +{ + if (device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + static struct IDeviceIoService hidService = { + .Dispatch = HdfHIDDispatch, + }; + device->service = &hidService; + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_hdfHIDEntry = { + .moduleVersion = 1, + .moduleName = "HDF_HID", + .Bind = HdfHIDDriverBind, + .Init = HdfHIDDriverInit, +}; + +HDF_INIT(g_hdfHIDEntry); \ No newline at end of file diff --git a/model/input/driver/hdf_hid_adapter.h b/model/input/driver/hdf_hid_adapter.h new file mode 100644 index 00000000..fc2aac7b --- /dev/null +++ b/model/input/driver/hdf_hid_adapter.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_HID_ADAPTER_H +#define HDF_HID_ADAPTER_H +typedef struct HidInformation { + uint32_t devType; + const char *devName; +} HidInfo; + +enum HidType { + HID_TYPE_BEGIN_POS = 33, /* HID type start position */ + HID_TYPE_MOUSE, /* Mouse */ + HID_TYPE_KEYBOARD, /* Keyboard */ + HID_TYPE_UNKNOWN, /* Unknown input device type */ +}; + +void* HidRegisterHdfInputDev(HidInfo dev); +void HidUnregisterHdfInputDev(const void *inputDev); +void HidReportEvent(const void *inputDev, uint32_t type, uint32_t code, int32_t value); + +#endif \ No newline at end of file diff --git a/model/input/driver/hdf_input_device_manager.c b/model/input/driver/hdf_input_device_manager.c index ef2d4a91..975bdf3d 100644 --- a/model/input/driver/hdf_input_device_manager.c +++ b/model/input/driver/hdf_input_device_manager.c @@ -16,22 +16,25 @@ #include "hdf_input_device_manager.h" #define NODE_MODE 0660 -#define SERVICE_NAME_LEN 16 +#define SERVICE_NAME_LEN 24 #define INPUT_DEV_EXIST 1 #define INPUT_DEV_NOT_EXIST 0 -#define MOUSE_DEV_ID 2 -#define MAX_INPUT_DEV_NUM 32 #define INPUTDEV_FIRST_ID 1 #define FILLER_FLAG 1 +#define PLACEHOLDER_LENGTH 2 +#define PLACEHOLDER_LIMIT 10 -InputManager *g_inputManager; +static InputManager *g_inputManager; + +InputManager* GetInputManager(void) +{ + return g_inputManager; +} #ifndef __KERNEL__ int32_t TouchIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg); uint32_t TouchPoll(struct file *filep, InputDevice *inputDev, poll_table *wait); -#endif -#ifndef __KERNEL__ static int32_t InputDevIoctl(struct file *filep, int32_t cmd, unsigned long arg) { int32_t ret; @@ -106,7 +109,7 @@ static const struct file_operations_vfs inputDevOps = { static bool IsHidDevice(uint32_t devType) { - if (devType == INDEV_TYPE_MOUSE) { + if ((devType > INDEV_TYPE_HID_BEGIN_POS) && (devType < INDEV_TYPE_UNKNOWN)) { return true; } return false; @@ -117,7 +120,10 @@ static struct HdfDeviceObject *HidRegisterHdfDevice(InputDevice *inputDev) char svcName[SERVICE_NAME_LEN] = {0}; const char *moduleName = "HDF_HID"; struct HdfDeviceObject *hdfDev = NULL; - int32_t ret = snprintf_s(svcName, SERVICE_NAME_LEN, strlen("event") + 1, "%s%u", "event", MOUSE_DEV_ID); + + int32_t len = (inputDev->devId < PLACEHOLDER_LIMIT) ? 1 : PLACEHOLDER_LENGTH; + int32_t ret = snprintf_s(svcName, SERVICE_NAME_LEN, strlen("hdf_input_event") + len, "%s%u", + "hdf_input_event", inputDev->devId); if (ret < 0) { HDF_LOGE("%s: snprintf_s failed", __func__); return NULL; @@ -131,6 +137,33 @@ static struct HdfDeviceObject *HidRegisterHdfDevice(InputDevice *inputDev) return hdfDev; } +static void HotPlugNotify(const InputDevice *inputDev, bool status) +{ + struct HdfSBuf *sbuf = NULL; + HotPlugEvent event = {0}; + int32_t ret; + + sbuf = HdfSBufObtain(sizeof(HotPlugEvent)); + if (sbuf == NULL) { + HDF_LOGE("%s: obtain buffer failed", __func__); + return; + } + event.devId = inputDev->devId; + event.devType = inputDev->devType; + event.status = status; + + if (!HdfSbufWriteBuffer(sbuf, &event, sizeof(HotPlugEvent))) { + HDF_LOGE("%s: write buffer failed", __func__); + goto EXIT; + } + ret = HdfDeviceSendEvent(g_inputManager->hdfDevObj, 0, sbuf); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: send event failed", __func__); + } +EXIT: + HdfSBufRecycle(sbuf); +} + static int32_t CreateDeviceNode(InputDevice *inputDev) { if (IsHidDevice(inputDev->devType)) { @@ -139,13 +172,14 @@ static int32_t CreateDeviceNode(InputDevice *inputDev) if (inputDev->hdfDevObj == NULL) { return HDF_DEV_ERR_NO_DEVICE; } - inputDev->devId = MOUSE_DEV_ID; } #ifndef __KERNEL__ - char devNode[INPUT_DEV_PATH_LEN] = {0}; - int32_t ret = snprintf_s(devNode, INPUT_DEV_PATH_LEN, strlen("/dev/input/event") + 1, - "%s%u", "/dev/input/event", inputDev->devId); + char *devNode = (char *)malloc(INPUT_DEV_PATH_LEN); + (void)memset_s(devNode, INPUT_DEV_PATH_LEN, 0, INPUT_DEV_PATH_LEN); + + int32_t ret = snprintf_s(devNode, INPUT_DEV_PATH_LEN, strlen("/dev/input/hdf_input_event") + 1, + "%s%u", "/dev/input/hdf_input_event", inputDev->devId); if (ret < 0) { HDF_LOGE("%s: snprintf_s failed", __func__); return HDF_FAILURE; @@ -168,7 +202,10 @@ static void DeleteDeviceNode(InputDevice *inputDev) if (IsHidDevice(inputDev->devType)) { char svcName[SERVICE_NAME_LEN] = {0}; const char *moduleName = "HDF_HID"; - int32_t ret = snprintf_s(svcName, SERVICE_NAME_LEN, strlen("event") + 1, "%s%u", "event", MOUSE_DEV_ID); + + int32_t len = (inputDev->devId < PLACEHOLDER_LIMIT) ? 1 : PLACEHOLDER_LENGTH; + int32_t ret = snprintf_s(svcName, SERVICE_NAME_LEN, strlen("hdf_input_event") + len, "%s%u", + "hdf_input_event", inputDev->devId); if (ret < 0) { HDF_LOGE("%s: snprintf_s failed", __func__); return; @@ -178,18 +215,12 @@ static void DeleteDeviceNode(InputDevice *inputDev) } #ifndef __KERNEL__ - char devNode[INPUT_DEV_PATH_LEN] = {0}; - int32_t ret = snprintf_s(devNode, INPUT_DEV_PATH_LEN, strlen("/dev/input/event") + 1, "%s%u", - "/dev/input/event", inputDev->devId); - if (ret < 0) { - HDF_LOGE("%s: snprintf_s failed", __func__); - return; - } - inputDev->devNode = devNode; - ret = unregister_driver(inputDev->devNode); + int32_t ret = unregister_driver(inputDev->devNode); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: delete dev node failed, ret %d", __func__, ret); } + free((void *)inputDev->devNode); + inputDev->devNode = NULL; #endif HDF_LOGI("%s: delete node succ, devId is %d", __func__, inputDev->devId); } @@ -212,6 +243,7 @@ static void AddInputDevice(InputDevice *inputDev) } } g_inputManager->devCount++; + HotPlugNotify(inputDev, ONLINE); } static int32_t CheckInputDevice(InputDevice *inputDev) @@ -258,12 +290,14 @@ static int32_t DeleteInputDevice(InputDevice *inputDev) EXIT: g_inputManager->devCount--; + HotPlugNotify(inputDev, OFFLINE); return HDF_SUCCESS; } #define DEFAULT_TOUCH_BUF_PKG_NUM 50 #define DEFAULT_KEY_BUF_PKG_NUM 10 #define DEFAULT_MOUSE_BUF_PKG_NUM 30 +#define DEFAULT_KEYBOARD_BUF_PKG_NUM 20 #define DEFAULT_CROWN_BUF_PKG_NUM 20 #define DEFAULT_ENCODER_BUF_PKG_NUM 20 @@ -280,6 +314,9 @@ static int32_t AllocPackageBuffer(InputDevice *inputDev) case INDEV_TYPE_MOUSE: pkgNum = DEFAULT_MOUSE_BUF_PKG_NUM; break; + case INDEV_TYPE_KEYBOARD: + pkgNum = DEFAULT_KEYBOARD_BUF_PKG_NUM; + break; case INDEV_TYPE_CROWN: pkgNum = DEFAULT_CROWN_BUF_PKG_NUM; break; @@ -313,14 +350,12 @@ static uint32_t AllocDeviceID(InputDevice *inputDev) tmpDev = tmpDev->next; } for (id = INPUTDEV_FIRST_ID; id < MAX_INPUT_DEV_NUM + 1; id++) { - if (id == MOUSE_DEV_ID) { - continue; - } if (idList[id] == 0) { inputDev->devId = id; return HDF_SUCCESS; } } + HDF_LOGE("%s: alloc device id failed", __func__); return HDF_FAILURE; } @@ -334,7 +369,7 @@ int32_t RegisterInputDevice(InputDevice *inputDev) return HDF_ERR_INVALID_PARAM; } - if (g_inputManager == NULL || g_inputManager->initialized == false) { + if ((g_inputManager == NULL) || (g_inputManager->initialized == false)) { HDF_LOGE("%s: dev manager is null or initialized failed", __func__); return HDF_FAILURE; } @@ -366,18 +401,18 @@ EXIT: return ret; } -int32_t UnregisterInputDevice(InputDevice *inputDev) +void UnregisterInputDevice(InputDevice *inputDev) { - int ret = HDF_FAILURE; + int32_t ret; HDF_LOGI("%s: enter", __func__); if (inputDev == NULL) { HDF_LOGE("%s: inputdev is null", __func__); - return HDF_ERR_INVALID_PARAM; + return; } - if (g_inputManager == NULL || g_inputManager->initialized == false) { + if ((g_inputManager == NULL) || (g_inputManager->initialized == false)) { HDF_LOGE("%s: dev manager is null or initialized failed", __func__); - return HDF_FAILURE; + return; } OsalMutexLock(&g_inputManager->mutex); @@ -393,14 +428,15 @@ int32_t UnregisterInputDevice(InputDevice *inputDev) if (ret != HDF_SUCCESS) { goto EXIT; } - + OsalMemFree(inputDev); + inputDev = NULL; OsalMutexUnlock(&g_inputManager->mutex); HDF_LOGI("%s: exit succ, devCount is %d", __func__, g_inputManager->devCount); - return HDF_SUCCESS; + return; EXIT: OsalMutexUnlock(&g_inputManager->mutex); - return ret; + return; } static uint32_t GetDeviceCount(void) @@ -409,6 +445,40 @@ static uint32_t GetDeviceCount(void) return g_inputManager->devCount; } +static int32_t ScanAllDev(struct HdfSBuf *reply) +{ + DevDesc sta; + InputDevice *tmpDev = g_inputManager->inputDevList; + while (tmpDev != NULL) { + sta.devType = tmpDev->devType; + sta.devId = tmpDev->devId; + + if (!HdfSbufWriteBuffer(reply, &sta, sizeof(DevDesc))) { + HDF_LOGE("%s: HdfSbufWriteBuffer failed", __func__); + return HDF_FAILURE; + } + tmpDev = tmpDev->next; + } + HdfSbufWriteBuffer(reply, NULL, 0); // end flag + return HDF_SUCCESS; +} + +static int32_t ScanDevice(struct HdfDeviceIoClient *client, int32_t cmd, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)cmd; + int32_t ret; + if ((client == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + ret = ScanAllDev(reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: scan all dev failed", __func__); + } + return ret; +} + static int32_t HdfInputManagerBind(struct HdfDeviceObject *device) { if (device == NULL) { @@ -418,6 +488,7 @@ static int32_t HdfInputManagerBind(struct HdfDeviceObject *device) static IInputManagerService managerService = { .getDeviceCount = GetDeviceCount, + .ioService.Dispatch = ScanDevice, }; device->service = &managerService.ioService; diff --git a/model/input/driver/hdf_input_device_manager.h b/model/input/driver/hdf_input_device_manager.h index 93c54049..41798661 100644 --- a/model/input/driver/hdf_input_device_manager.h +++ b/model/input/driver/hdf_input_device_manager.h @@ -19,7 +19,10 @@ #endif #define HDF_LOG_TAG HDF_INPUT_DRV #define INPUT_DEV_PATH_LEN 64 +#define MAX_INPUT_DEV_NUM 32 #define DEV_NAME_LEN 16 +#define ONLINE 0 +#define OFFLINE 1 #define CHECK_RETURN_VALUE(ret) do { \ if ((ret) != HDF_SUCCESS) { \ @@ -27,6 +30,17 @@ } \ } while (0) +typedef struct { + uint32_t devId; + uint32_t devType; +} DevDesc; + +typedef struct { + uint32_t devId; + uint32_t devType; + uint32_t status; +} HotPlugEvent; + typedef struct { struct IDeviceIoService ioService; uint32_t (*getDeviceCount)(void); @@ -55,14 +69,15 @@ typedef struct { } InputManager; enum InputDevType { - INDEV_TYPE_TOUCH, /* Touchscreen */ - INDEV_TYPE_KEY, /* Physical key */ - INDEV_TYPE_KEYBOARD, /* Keyboard */ - INDEV_TYPE_MOUSE, /* Mouse */ - INDEV_TYPE_BUTTON, /* Virtual button */ - INDEV_TYPE_CROWN, /* Watch crown */ - INDEV_TYPE_ENCODER, /* Customized type of a specific function or event */ - INDEV_TYPE_UNKNOWN, /* Unknown input device type */ + INDEV_TYPE_TOUCH, /* Touchscreen */ + INDEV_TYPE_KEY, /* Physical key */ + INDEV_TYPE_BUTTON, /* Virtual button */ + INDEV_TYPE_CROWN, /* Watch crown */ + INDEV_TYPE_ENCODER, /* Customized type of a specific function or event */ + INDEV_TYPE_HID_BEGIN_POS = 33, /* HID type start position */ + INDEV_TYPE_MOUSE, /* Mouse */ + INDEV_TYPE_KEYBOARD, /* Keyboard */ + INDEV_TYPE_UNKNOWN, /* Unknown input device type */ }; enum InputIOsvcCmdId { @@ -89,8 +104,8 @@ enum TouchIoctlCmd { INPUT_IOCTL_RUN_CAPACITANCE_TEST, INPUT_IOCTL_RUN_EXTRA_CMD, }; - +InputManager* GetInputManager(void); int32_t RegisterInputDevice(InputDevice *device); -int32_t UnregisterInputDevice(InputDevice *device); +void UnregisterInputDevice(InputDevice *device); #endif \ No newline at end of file diff --git a/model/input/driver/hdf_key.c b/model/input/driver/hdf_key.c index 8b07dacd..154df2df 100644 --- a/model/input/driver/hdf_key.c +++ b/model/input/driver/hdf_key.c @@ -14,8 +14,8 @@ #include "event_hub.h" #include "hdf_key.h" -#define CHECK_PARSER_RET(ret, str) do { \ - if (ret != HDF_SUCCESS) { \ +#define CHECK_PARSER_RET(ret, str) do { \ + if ((ret) != HDF_SUCCESS) { \ HDF_LOGE("%s: %s failed, ret = %d!", __func__, str, ret); \ return HDF_FAILURE; \ } \ @@ -40,7 +40,10 @@ static int32_t IoctlReadKeyEvent(KeyDriver *driver, unsigned long arg) int32_t KeyIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg) { - int32_t ret; + int32_t ret = HDF_FAILURE; + if (inputdev == NULL) { + return ret; + } KeyDriver *driver = (KeyDriver *)inputdev->pvtData; switch (cmd) { case INPUT_IOCTL_GET_EVENT_DATA: @@ -58,7 +61,13 @@ int32_t KeyIrqHandle(uint16_t intGpioNum, void *data) { uint16_t gpioValue; KeyDriver *driver = (KeyDriver *)data; + if (driver == NULL) { + return HDF_FAILURE; + } KeyEventData *event = &driver->eventData; + if (event == NULL) { + return HDF_FAILURE; + } int32_t ret = GpioDisableIrq(intGpioNum); if (ret != HDF_SUCCESS) { diff --git a/model/input/driver/hdf_touch.c b/model/input/driver/hdf_touch.c index edb8fcf3..b129da73 100644 --- a/model/input/driver/hdf_touch.c +++ b/model/input/driver/hdf_touch.c @@ -6,13 +6,13 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "hdf_touch.h" #include "gpio_if.h" #include "hdf_device_desc.h" #include "hdf_log.h" #include "osal_mem.h" #include "osal_io.h" #include "event_hub.h" -#include "hdf_touch.h" #define I2C_TYPE 0 #define SPI_TYPE 1 @@ -79,7 +79,10 @@ static int32_t IoctlGetChipName(TouchDriver *driver, unsigned long arg) int32_t TouchIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg) { - int32_t ret; + int32_t ret = HDF_FAILURE; + if (inputdev == NULL || inputdev->pvtData == NULL) { + return ret; + } ChipDevice *device = (ChipDevice *)inputdev->pvtData; TouchDriver *driver = device->driver; switch (cmd) { @@ -104,6 +107,9 @@ int32_t TouchIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg) uint32_t TouchPoll(FAR struct file *filep, InputDevice *inputDev, poll_table *wait) { uint32_t pollMask = 0; + if (filep == NULL || filep->f_vnode == NULL) { + return pollMask; + } InputDevice *inputdev = (InputDevice *)((struct drv_data*)filep->f_vnode->data)->priv; if (inputdev == NULL) { HDF_LOGE("%s: inputdev is null", __func__); @@ -124,7 +130,7 @@ uint32_t TouchPoll(FAR struct file *filep, InputDevice *inputDev, poll_table *wa static int32_t SetGpioDirAndLevel(int gpio, int dir, int level) { int32_t ret; - if (dir == GPIO_DIR_IN || dir == GPIO_DIR_OUT) { + if ((dir == GPIO_DIR_IN) || (dir == GPIO_DIR_OUT)) { ret = GpioSetDir(gpio, dir); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: set gpio%d to %d dir failed, ret %d", __func__, gpio, dir, ret); @@ -132,7 +138,7 @@ static int32_t SetGpioDirAndLevel(int gpio, int dir, int level) } } - if (level == GPIO_VAL_LOW || level == GPIO_VAL_HIGH) { + if ((level == GPIO_VAL_LOW) || (level == GPIO_VAL_HIGH)) { ret = GpioWrite(gpio, level); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: pull gpio%d to %d level failed, ret %d", __func__, gpio, level, ret); @@ -161,15 +167,20 @@ static int32_t SetGpio(uint16_t gpio, uint32_t dir, uint32_t status) return HDF_SUCCESS; } -int32_t HandlePowerEvent(ChipDevice *chipDev, uint32_t *timing) +static int32_t HandlePowerEvent(ChipDevice *chipDev, uint32_t *timing, uint32_t length) { int32_t ret = 0; uint16_t gpio; + + if (length <= PWR_DELAY_INDEX) { + HDF_LOGE("%s: invalid param", __func__); + return HDF_FAILURE; + } uint32_t type = timing[PWR_TYPE_INDEX]; uint32_t status = timing[PWR_STATUS_INDEX]; uint32_t dir = timing[PWR_DIR_INDEX]; uint32_t delay = timing[PWR_DELAY_INDEX]; - HDF_LOGD("%s: type = %d, status = %d, dir = %d, delay = %d", __func__, type, status, dir, delay); + HDF_LOGD("%s: type = %u, status = %u, dir = %u, delay = %u", __func__, type, status, dir, delay); switch (type) { case TYPE_VCC: @@ -253,7 +264,7 @@ static int32_t SetPowerOnTiming(ChipDevice *chipDev) } for (i = 0; i < pwrOnTiming.count / PWR_CELL_LEN; i++) { - ret = HandlePowerEvent(chipDev, pwrOnTiming.buf); + ret = HandlePowerEvent(chipDev, pwrOnTiming.buf, PWR_CELL_LEN); CHECK_RETURN_VALUE(ret); pwrOnTiming.buf = pwrOnTiming.buf + PWR_CELL_LEN; } @@ -273,12 +284,13 @@ static void EventHandle(TouchDriver *driver, ChipDevice *chipDev) } } -int32_t IrqHandle(uint16_t intGpioNum, void *data) +static int32_t IrqHandle(uint16_t intGpioNum, void *data) { TouchDriver *driver = (TouchDriver *)data; int ret = GpioDisableIrq(intGpioNum); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: disable irq failed, ret %d", __func__, ret); + return HDF_FAILURE; } EventHandle(driver, driver->device); @@ -286,6 +298,7 @@ int32_t IrqHandle(uint16_t intGpioNum, void *data) ret = GpioEnableIrq(intGpioNum); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: enable irq failed, ret %d", __func__, ret); + return HDF_FAILURE; } return HDF_SUCCESS; } @@ -302,6 +315,7 @@ static void InputFrameReport(TouchDriver *driver) input_report_abs(dev, ABS_MT_POSITION_X, frame->fingers[i].x); input_report_abs(dev, ABS_MT_POSITION_Y, frame->fingers[i].y); input_report_abs(dev, ABS_MT_TRACKING_ID, frame->fingers[i].trackId); + input_mt_sync(dev); } } @@ -320,8 +334,12 @@ static int32_t SetupChipIrq(ChipDevice *chipDev) uint16_t intGpioNum = chipDev->boardCfg->pins.intGpio; uint16_t irqFlag = chipDev->chipCfg->bus.chipI2c.irqFlag; + if (chipDev->driver == NULL) { + HDF_LOGE("%s: invalid param", __func__); + return HDF_FAILURE; + } irqFlag |= GPIO_IRQ_USING_THREAD; - HDF_LOGD("%s: gpioNum = %d, irqFlag = %d", __func__, intGpioNum, irqFlag); + HDF_LOGD("%s: gpioNum = %u, irqFlag = %u", __func__, intGpioNum, irqFlag); ret = GpioSetIrq(intGpioNum, irqFlag, IrqHandle, chipDev->driver); if (ret != 0) { HDF_LOGE("%s: register irq failed, ret %d", __func__, ret); @@ -349,6 +367,10 @@ static int32_t ChipDriverInit(ChipDevice *chipDev) CHECK_RETURN_VALUE(ret); HDF_LOGI("%s: chipDetect succ, ret = %d ", __func__, ret); + ret = chipDev->ops->UpdateFirmware(chipDev); + CHECK_RETURN_VALUE(ret); + HDF_LOGI("%s: update firmware success", __func__); + ret = SetupChipIrq(chipDev); CHECK_RETURN_VALUE(ret); return HDF_SUCCESS; @@ -377,12 +399,12 @@ static int32_t ChipMatchCheck(const ChipDevice *chipDev, const TouchDriver *driv const struct DeviceResourceNode *boardNode = driver->boardCfg->boardNode; const struct DeviceResourceNode *chipNode = chipDev->chipCfg->chipNode; - if (boardNode == NULL || boardNode->parent == NULL) { + if ((boardNode == NULL) || (boardNode->parent == NULL)) { HDF_LOGE("%s: board node or upper node is null", __func__); return HDF_FAILURE; } - if (chipNode == NULL || chipNode->parent == NULL || chipNode->parent->parent == NULL) { + if ((chipNode == NULL) || (chipNode->parent == NULL) || (chipNode->parent->parent == NULL)) { HDF_LOGE("%s: chip node or upper node is null ", __func__); return HDF_FAILURE; } @@ -410,7 +432,7 @@ static int32_t DeviceBindDriver(ChipDevice *chipDev) } } - if (ret == HDF_FAILURE || driver == NULL) { + if ((ret == HDF_FAILURE) || (driver == NULL)) { return HDF_FAILURE; } @@ -462,7 +484,7 @@ EXIT: static int32_t TouchGetDevType(TouchDriver *driver, struct HdfSBuf *reply) { uint32_t devType = driver->devType; - HDF_LOGI("%s: enter, devType is %d", __func__, devType); + HDF_LOGI("%s: enter, devType is %u", __func__, devType); bool ret = HdfSbufWriteUint32(reply, devType); if (!ret) { HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); @@ -480,7 +502,7 @@ static int32_t TouchSetPowerStatus(TouchDriver *driver, struct HdfSBuf *data) return HDF_FAILURE; } driver->pwrStatus = pwrStatus; - HDF_LOGI("%s: set power status is %d", __func__, pwrStatus); + HDF_LOGI("%s: set power status is %u", __func__, pwrStatus); return HDF_SUCCESS; } @@ -492,14 +514,14 @@ static int32_t TouchGetPowerStatus(TouchDriver *driver, struct HdfSBuf *reply) HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); return HDF_FAILURE; } - HDF_LOGI("%s: get power status is %d", __func__, pwrStatus); + HDF_LOGI("%s: get power status is %u", __func__, pwrStatus); return HDF_SUCCESS; } static int32_t TouchGetDeviceInfo(TouchDriver *driver, int32_t cmd, struct HdfSBuf *reply) { - const char *info; - if (driver->device == NULL || driver->device->chipCfg == NULL) { + const char *info = NULL; + if ((driver->device == NULL) || (driver->device->chipCfg == NULL)) { HDF_LOGE("%s: parameter invalid", __func__); return HDF_ERR_INVALID_PARAM; } @@ -537,7 +559,7 @@ static int32_t TouchSetGestureMode(TouchDriver *driver, struct HdfSBuf *data) return HDF_FAILURE; } driver->gestureMode = gestureMode; - HDF_LOGD("%s: set gesture mode is %d", __func__, gestureMode); + HDF_LOGD("%s: set gesture mode is %u", __func__, gestureMode); return HDF_SUCCESS; } @@ -560,7 +582,7 @@ static int32_t TouchSelfCapacitance(TouchDriver *driver, struct HdfSBuf *data, s HDF_LOGE("%s: HdfSbufWriteString failed", __func__); return HDF_FAILURE; } - HDF_LOGD("%s: capac test type is %d, test result is %s", __func__, capacTest.testType, capacTest.testResult); + HDF_LOGD("%s: capac test type is %u, test result is %s", __func__, capacTest.testType, capacTest.testResult); return HDF_SUCCESS; } @@ -585,10 +607,9 @@ static int32_t TouchRunExtraCmd(TouchDriver *driver, struct HdfSBuf *data) static int32_t HdfTouchDispatch(struct HdfDeviceIoClient *client, int32_t cmd, struct HdfSBuf *data, struct HdfSBuf *reply) { - (void)cmd; int32_t ret; TouchDriver *touchDriver = NULL; - if (client == NULL || client->device == NULL || data == NULL || reply == NULL) { + if ((client == NULL) || (client->device == NULL) || (data == NULL) || (reply == NULL)) { HDF_LOGE("%s: param is null", __func__); return HDF_FAILURE; } @@ -809,8 +830,7 @@ static void HdfTouchDriverRelease(struct HdfDeviceObject *device) } if (inputDev != NULL) { - (void)UnregisterInputDevice(inputDev); - OsalMemFree(inputDev); + UnregisterInputDevice(inputDev); driver->inputDev = NULL; } diff --git a/model/input/driver/hdf_touch.h b/model/input/driver/hdf_touch.h index 18f31a0f..968f8201 100644 --- a/model/input/driver/hdf_touch.h +++ b/model/input/driver/hdf_touch.h @@ -96,6 +96,7 @@ struct TouchChipOps { int32_t (*Resume)(ChipDevice *device); int32_t (*Suspend)(ChipDevice *device); int32_t (*DataHandle)(ChipDevice *device); + int32_t (*UpdateFirmware)(ChipDevice *device); }; typedef struct { diff --git a/model/input/driver/input_config_parser.c b/model/input/driver/input_config_parser.c index d6fb06e8..f6c49eba 100644 --- a/model/input/driver/input_config_parser.c +++ b/model/input/driver/input_config_parser.c @@ -20,6 +20,8 @@ #define DEFAULT_I2C_SPEED 400 #define DEFAULT_SPI_SPEED 10000 +#define I2C 0 +#define SPI 1 int32_t ParseKeyConfig(const struct DeviceResourceNode *node, KeyChipCfg *config) { @@ -71,7 +73,7 @@ static int32_t ParseBus(struct DeviceResourceIface *parser, const struct DeviceR ret = parser->GetUint8(busNode, "busType", &bus->busType, 0); CHECK_PARSER_RET(ret, "GetUint8"); - if (bus->busType == 0) { + if (bus->busType == I2C) { ret = parser->GetUint8(busNode, "busNum", &bus->i2c.busNum, 0); CHECK_PARSER_RET(ret, "GetUint8"); ret = parser->GetUint16(busNode, "clkGpio", &bus->i2c.clkGpio, 0); @@ -82,7 +84,7 @@ static int32_t ParseBus(struct DeviceResourceIface *parser, const struct DeviceR CHECK_PARSER_RET(ret, "GetUint32Array"); ret = parser->GetUint32Array(busNode, "i2cDataIomux", bus->i2c.i2cDataReg, REG_CONFIG_LEN, 0); CHECK_PARSER_RET(ret, "GetUint32Array"); - } else if (bus->busType == 1) { + } else if (bus->busType == SPI) { ret = parser->GetUint8(busNode, "busNum", &bus->spi.busNum, 0); CHECK_PARSER_RET(ret, "GetUint8"); ret = parser->GetUint16(busNode, "clkGpio", &bus->spi.clkGpio, 0); @@ -274,7 +276,7 @@ int32_t ParseTouchChipConfig(const struct DeviceResourceNode *node, TouchChipCfg CHECK_PARSER_RET(ret, "GetUint16"); ret = parser->GetUint8(node, "busType", &config->bus.busType, 0); CHECK_PARSER_RET(ret, "GetUint8"); - if (config->bus.busType == 0) { + if (config->bus.busType == I2C) { ret = parser->GetUint16(node, "irqFlag", &config->bus.chipI2c.irqFlag, 0); CHECK_PARSER_RET(ret, "GetUint16"); ret = parser->GetUint32(node, "deviceAddr", &config->bus.chipI2c.commAddr, 0); diff --git a/model/input/driver/touchscreen/touch_ft6336.c b/model/input/driver/touchscreen/touch_ft6336.c index cf99b79b..87a006fb 100644 --- a/model/input/driver/touchscreen/touch_ft6336.c +++ b/model/input/driver/touchscreen/touch_ft6336.c @@ -41,7 +41,7 @@ static int32_t ChipDetect(ChipDevice *device) CHIP_CHECK_RETURN(ret); ret = InputI2cRead(i2cClient, ®Addr, 1, ®Value, 1); CHIP_CHECK_RETURN(ret); - HDF_LOGI("%s: Report rate is %d * 10", __func__, regValue); + HDF_LOGI("%s: Report rate is %u * 10", __func__, regValue); regAddr = FTS_REG_FW_VER; ret = InputI2cWrite(i2cClient, ®Addr, 1); @@ -55,7 +55,7 @@ static int32_t ChipDetect(ChipDevice *device) CHIP_CHECK_RETURN(ret); ret = InputI2cRead(i2cClient, ®Addr, 1, ®Value, 1); CHIP_CHECK_RETURN(ret); - HDF_LOGI("%s: Chip ID is %d", __func__, regValue); + HDF_LOGI("%s: Chip ID is %u", __func__, regValue); (void)ChipInit(device); (void)ChipResume(device); diff --git a/model/input/driver/touchscreen/touch_gt911.c b/model/input/driver/touchscreen/touch_gt911.c index 04edebf4..9736112e 100644 --- a/model/input/driver/touchscreen/touch_gt911.c +++ b/model/input/driver/touchscreen/touch_gt911.c @@ -80,6 +80,8 @@ static int ChipCleanBuffer(InputI2cClient *i2cClient) return ret; } +#define X_OFFSET 1 + static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum) { int32_t chipVer = device->chipCfg->chipVersion; @@ -89,10 +91,15 @@ static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, u for (i = 0; i < pointNum; i++) { if (chipVer == 0) { // chipversion A:gt911_zsj5p5 + frame->fingers[i].trackId = buf[GT_POINT_SIZE * i + GT_TRACK_ID]; frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); frame->fingers[i].x = (buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); + if (frame->fingers[i].x == 0) { + frame->fingers[i].x = X_OFFSET; + } + HDF_LOGD("%s: x = %d, y = %d", __func__, frame->fingers[i].x, frame->fingers[i].y); } else if (chipVer == 1) { // chipversion B:gt911_zsj4p0 frame->fingers[i].x = resX - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); @@ -137,7 +144,7 @@ static int32_t ChipDataHandle(ChipDevice *device) reg[1] = GT_X_LOW_BYTE_BASE & ONE_BYTE_MASK; pointNum = touchStatus & GT_FINGER_NUM_MASK; if (pointNum == 0 || pointNum > MAX_SUPPORT_POINT) { - HDF_LOGE("%s: pointNum is invalid, %d", __func__, pointNum); + HDF_LOGE("%s: pointNum is invalid, %u", __func__, pointNum); (void)ChipCleanBuffer(i2cClient); OsalMutexUnlock(&device->driver->mutex); return HDF_FAILURE; @@ -155,12 +162,25 @@ EXIT: return HDF_SUCCESS; } +static int32_t UpdateFirmware(ChipDevice *device) +{ + int32_t ret; + InputI2cClient *i2cClient = &device->driver->i2cClient; + ret = InputI2cWrite(i2cClient, firmWareParm, FIRMWARE_LEN); + if (ret < 0) { + return HDF_FAILURE; + } + HDF_LOGI("%s: update firmware success\n", __func__); + return HDF_SUCCESS; +} + static struct TouchChipOps g_gt911ChipOps = { .Init = ChipInit, .Detect = ChipDetect, .Resume = ChipResume, .Suspend = ChipSuspend, .DataHandle = ChipDataHandle, + .UpdateFirmware = UpdateFirmware, }; static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device) diff --git a/model/input/driver/touchscreen/touch_gt911.h b/model/input/driver/touchscreen/touch_gt911.h index c89a344d..ebb3abf0 100644 --- a/model/input/driver/touchscreen/touch_gt911.h +++ b/model/input/driver/touchscreen/touch_gt911.h @@ -10,20 +10,21 @@ #define TOUCH_GT911_H /* the macro defines of GT911 */ -#define MAX_SUPPORT_POINT 10 +#define MAX_SUPPORT_POINT 5 #define ONE_BYTE_MASK 0xFF #define ONE_BYTE_OFFSET 8 #define GT_EVENT_UP 0x80 #define GT_EVENT_INVALID 0 #define GT_POINT_SIZE 8 -#define GT_X_LOW 0 -#define GT_X_HIGH 1 -#define GT_Y_LOW 2 -#define GT_Y_HIGH 3 +#define GT_TRACK_ID 0 +#define GT_X_LOW 1 +#define GT_X_HIGH 2 +#define GT_Y_LOW 3 +#define GT_Y_HIGH 4 #define GT_ADDR_LEN 2 #define GT_BUF_STATE_ADDR 0x814E -#define GT_X_LOW_BYTE_BASE 0x8150 +#define GT_X_LOW_BYTE_BASE 0x814F #define GT_FINGER_NUM_MASK 0x0F #define GT_CLEAN_DATA_LEN 3 #define GT_REG_HIGH_POS 0 @@ -43,5 +44,23 @@ #define GT_SOLU_X_HIGH 7 #define GT_SOLU_Y_LOW 8 #define GT_SOLU_Y_HIGH 9 +#define FIRMWARE_LEN 188 + +uint8_t firmWareParm[FIRMWARE_LEN] = { + 0x80, 0x47, 0x45, 0xC0, 0x03, 0xE0, 0x01, 0x05, 0x3D, 0x00, 0x01, 0x08, 0x28, 0x0F, + 0x50, 0x32, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x1A, 0x1E, + 0x14, 0x86, 0x26, 0x08, 0x55, 0x57, 0xB2, 0x04, 0x00, 0x00, 0x00, 0x42, 0x02, 0x11, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x78, 0x94, + 0xD5, 0x02, 0x07, 0x00, 0x00, 0x04, 0x97, 0x40, 0x00, 0x8A, 0x4A, 0x00, 0x80, 0x55, + 0x00, 0x77, 0x61, 0x00, 0x6F, 0x70, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x0E, 0x0C, 0x0A, 0x08, 0x06, 0x04, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x22, 0x21, 0x20, 0x1F, 0x1E, 0x1D, 0x00, 0x02, 0x04, 0x06, + 0x08, 0x0A, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x5C, 0x01 +}; #endif \ No newline at end of file diff --git a/model/network/common/netdevice/net_device.c b/model/network/common/netdevice/net_device.c index da504d16..2a336b30 100644 --- a/model/network/common/netdevice/net_device.c +++ b/model/network/common/netdevice/net_device.c @@ -17,12 +17,12 @@ static struct NetDeviceImpl *g_netDeviceImplTable[MAX_NETDEVICE_COUNT] = {NULL}; -static bool FindAvailableTable(int32_t *index) +static bool FindAvailableTable(uint32_t *index) { - int32_t i; + uint32_t i; if (index == NULL) { - HDF_LOGE("Find Available table index error!"); + HDF_LOGE("%s Find Available table index error!", __func__); return false; } for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { @@ -34,7 +34,7 @@ static bool FindAvailableTable(int32_t *index) return false; } -static bool AddNetDeviceImplToTable(int32_t index, struct NetDeviceImpl *netDeviceImpl) +static bool AddNetDeviceImplToTable(uint32_t index, struct NetDeviceImpl *netDeviceImpl) { if (index >= MAX_NETDEVICE_COUNT) { HDF_LOGE("%s error because of not enough space!", __func__); @@ -68,7 +68,6 @@ static struct NetDeviceImpl *InitNetDeviceImpl(NetDevice *nd, NetIfCategory ifCa HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); return NULL; } - (void)memset_s(ndImpl, sizeof(struct NetDeviceImpl), 0, sizeof(struct NetDeviceImpl)); ndImpl->netDevice = nd; if (RegisterNetDeviceImpl(ndImpl) != HDF_SUCCESS) { @@ -100,6 +99,7 @@ static void DeInitNetDeviceImpl(struct NetDeviceImpl *netDeviceImpl) /* last release netDeviceImpl */ OsalMemFree(netDeviceImpl); + netDeviceImpl = NULL; HDF_LOGI("%s success!", __func__); return; } @@ -117,7 +117,7 @@ static struct NetDeviceImpl *GetImplByNetDevice(const struct NetDevice *netDevic } } } - HDF_LOGE("Don't Get Impl by netdevice"); + HDF_LOGE("%s Get Impl by netdevice failed", __func__); return ndImpl; } @@ -125,7 +125,7 @@ struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory { NetDevice *netDevice = NULL; struct NetDeviceImpl *ndImpl = NULL; - int32_t index = 0; + uint32_t index = 0; int32_t ret; if ((ifName == NULL) || (strlen(ifName) != len) || (strlen(ifName) > IFNAMSIZ - 1)) { @@ -137,9 +137,8 @@ struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory 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__); + if (strcpy_s(netDevice->name, IFNAMSIZ, ifName) != EOK) { + HDF_LOGE("%s fail: strcpy_s fail!", __func__); OsalMemFree(netDevice); return NULL; } @@ -318,7 +317,7 @@ static int32_t NetIfRxImpl(const struct NetDevice *netDevice, NetBuf *buff, Rece ProcessingResult ret = PROCESSING_CONTINUE; if (ndImpl == NULL || ndImpl->interFace == NULL || ndImpl->interFace->receive == NULL) { - HDF_LOGE("NetIfRxImpl fail : netdevice not exist!"); + HDF_LOGE("%s: NetIfRxImpl fail : netdevice not exist!", __func__); return HDF_ERR_INVALID_PARAM; } @@ -333,7 +332,7 @@ static int32_t NetIfRxImpl(const struct NetDevice *netDevice, NetBuf *buff, Rece HDF_LOGI("NetIfRxImpl specialEtherType Process not need TCP/IP stack!"); return HDF_SUCCESS; } else { - HDF_LOGE("NetIfRxImpl specialEtherType Process error"); + HDF_LOGE("%s: NetIfRxImpl specialEtherType Process error", __func__); return HDF_FAILURE; } } diff --git a/model/network/wifi/core/compoments/eapol/eapol.c b/model/network/wifi/core/components/eapol/eapol.c similarity index 98% rename from model/network/wifi/core/compoments/eapol/eapol.c rename to model/network/wifi/core/components/eapol/eapol.c index f1e02bbc..43811b22 100644 --- a/model/network/wifi/core/compoments/eapol/eapol.c +++ b/model/network/wifi/core/components/eapol/eapol.c @@ -75,7 +75,7 @@ static int32_t GetEapol(const struct NetDevice *netDevice, struct EapolRx *buff) p = NetBufGetAddress(netBuff, E_DATA_BUF); len = NetBufGetDataLen(netBuff); if (len > eapolRx->len) { - HDF_LOGE("%s fail : eapolRx->len too small! netBuff->len(%d) > eapolRx->len(%d).", + HDF_LOGE("%s fail : eapolRx->len too small! netBuff->len(%u) > eapolRx->len(%u).", __func__, netBuff->len, eapolRx->len); NetBufFree(netBuff); return HDF_FAILURE; @@ -158,7 +158,7 @@ static void HandleEapolQueue(struct EapolData *eapol) 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); + HDF_LOGE("%s discard pre netbuf : eapol->count(%u) = maxCount(%u).", __func__, eapol->count, maxCount); } eapol->count--; eapol->enqueueTime = currentTime; diff --git a/model/network/wifi/core/compoments/eapol/eapol.h b/model/network/wifi/core/components/eapol/eapol.h similarity index 97% rename from model/network/wifi/core/compoments/eapol/eapol.h rename to model/network/wifi/core/components/eapol/eapol.h index d82b6c69..bebfdf9a 100644 --- a/model/network/wifi/core/compoments/eapol/eapol.h +++ b/model/network/wifi/core/components/eapol/eapol.h @@ -16,7 +16,7 @@ #define EAPOL_MAX_ENQUEUE_TIME 300 /* 300 Second */ struct EapolData { - bool regFlag; /* is already regstered */ + bool regFlag; /* is already registered */ uint16_t count; /* eapol frame count in NetBuffQueue. */ uint16_t maxCount; int64_t enqueueTime; /* record eapol frame time for dfx. */ diff --git a/model/network/wifi/core/compoments/softap/ap.c b/model/network/wifi/core/components/softap/ap.c similarity index 99% rename from model/network/wifi/core/compoments/softap/ap.c rename to model/network/wifi/core/components/softap/ap.c index 21daac1a..d685abed 100644 --- a/model/network/wifi/core/compoments/softap/ap.c +++ b/model/network/wifi/core/components/softap/ap.c @@ -72,7 +72,7 @@ static int32_t StartAp(struct NetDevice *netDev, WifiApSetting *apSettings) RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, ConfigAp); ret = chipDriver->apOps->ConfigAp(netDev, &apConf); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:ConfigAp failed!ret=%d", ret); + HDF_LOGE("%s:ConfigAp failed!ret=%d", __func__, ret); return HDF_FAILURE; } @@ -378,7 +378,6 @@ static int32_t WifiCmdGetAssociatedStas(const RequestContext *context, struct Hd ret = GetAssociatedStas(netdev, num, rspData); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: fail to GetAssociatedStas,%d", __func__, ret); - return ret; } return ret; } diff --git a/model/network/wifi/core/compoments/softap/ap.h b/model/network/wifi/core/components/softap/ap.h similarity index 100% rename from model/network/wifi/core/compoments/softap/ap.h rename to model/network/wifi/core/components/softap/ap.h diff --git a/model/network/wifi/core/compoments/sta/sta.c b/model/network/wifi/core/components/sta/sta.c similarity index 100% rename from model/network/wifi/core/compoments/sta/sta.c rename to model/network/wifi/core/components/sta/sta.c diff --git a/model/network/wifi/core/compoments/sta/sta.h b/model/network/wifi/core/components/sta/sta.h similarity index 100% rename from model/network/wifi/core/compoments/sta/sta.h rename to model/network/wifi/core/components/sta/sta.h diff --git a/model/network/wifi/core/hdf_wifi_core.c b/model/network/wifi/core/hdf_wifi_core.c index 32179061..75c26ae9 100644 --- a/model/network/wifi/core/hdf_wifi_core.c +++ b/model/network/wifi/core/hdf_wifi_core.c @@ -39,13 +39,13 @@ int32_t HdfWifiGetBusIdx(void) * @brief as for now, we just support one wlan module in one board cause driver binds to wlan featere * due to that reason, once we detected one chip, we stop rescan. */ -int HdfWlanSdioScan(struct HdfWlanDevice *data, struct HdfConfigWlanBus *busConfig) +int32_t HdfWlanSdioScan(struct HdfWlanDevice *data, struct HdfConfigWlanBus *busConfig) { /* get config vendId, deviceId and chip-name which used in detect match process */ HdfWlanGetSdioTableByConfig(); HdfWlanSdioScanTriggerByBusIndex(busConfig->busIdx); - int ret = HdfWlanGetDetectedChip(data, busConfig); + int32_t ret = HdfWlanGetDetectedChip(data, busConfig); HdfWlanSdioDriverUnReg(); if (ret != HDF_SUCCESS) { return ret; @@ -54,7 +54,7 @@ int HdfWlanSdioScan(struct HdfWlanDevice *data, struct HdfConfigWlanBus *busConf return HDF_SUCCESS; } -static int HdfWifiDriverBind(struct HdfDeviceObject *dev) +static int32_t HdfWifiDriverBind(struct HdfDeviceObject *dev) { ErrorCode errCode; static struct IDeviceIoService wifiService = { @@ -179,7 +179,7 @@ static struct HdfChipDriverFactory *HdfWlanGetDriverFactory(const char *driverNa static int32_t HdfWlanDeinitInterface(struct HdfWlanDevice *device, const char *ifName, struct HdfChipDriverFactory *factory) { - int ret; + int32_t ret; struct NetDevice *netdev = NULL; struct HdfChipDriver *chipDriver = NULL; @@ -369,7 +369,7 @@ static struct HdfWlanDevice *ProbeDevice(struct HdfConfigWlanDevInst *deviceConf return device; } -int32_t DeinitDevice(struct HdfWlanDevice *device) +int32_t HdfWifiDeinitDevice(struct HdfWlanDevice *device) { struct HdfChipDriverFactory *chipDriverFact = NULL; int32_t ret; @@ -394,7 +394,7 @@ int32_t DeinitDevice(struct HdfWlanDevice *device) return HDF_SUCCESS; } -int32_t InitDevice(struct HdfWlanDevice *device) +int32_t HdfWifiInitDevice(struct HdfWlanDevice *device) { int32_t ret; struct HdfChipDriverFactory *chipDriverFact = NULL; @@ -424,7 +424,7 @@ int32_t InitDevice(struct HdfWlanDevice *device) /* thread callback function */ static int32_t HdfWlanInitThread(void *para) { - const uint32_t initDelaySec = 5; + const uint32_t initDelaySec = 15; struct HdfDeviceObject *device = (struct HdfDeviceObject *)para; struct SubscriberCallback callback = { NULL }; struct HdfConfigWlanDeviceList *devList = NULL; @@ -465,7 +465,7 @@ static int32_t HdfWlanInitThread(void *para) // Load chip driver (void)DevSvcManagerClntSubscribeService(wlanDevice->driverName, callback); - (void)InitDevice(wlanDevice); + (void)HdfWifiInitDevice(wlanDevice); } HDF_LOGV("%s:finished.", __func__); diff --git a/model/network/wifi/core/hdf_wifi_core.h b/model/network/wifi/core/hdf_wifi_core.h index c171fd61..78134dc5 100644 --- a/model/network/wifi/core/hdf_wifi_core.h +++ b/model/network/wifi/core/hdf_wifi_core.h @@ -17,9 +17,9 @@ extern "C" { #endif int32_t HdfWifiGetBusIdx(void); -int32_t DeinitDevice(struct HdfWlanDevice *device); +int32_t HdfWifiDeinitDevice(struct HdfWlanDevice *device); -int32_t InitDevice(struct HdfWlanDevice *device); +int32_t HdfWifiInitDevice(struct HdfWlanDevice *device); #ifdef __cplusplus } diff --git a/model/network/wifi/core/module/wifi_base.c b/model/network/wifi/core/module/wifi_base.c index 072e10b7..6f291138 100644 --- a/model/network/wifi/core/module/wifi_base.c +++ b/model/network/wifi/core/module/wifi_base.c @@ -374,7 +374,7 @@ static int32_t WifiCmdEnableEapol(const RequestContext *context, struct HdfSBuf } eapol.callback = (void *)HdfWifiEventEapolRecv; - eapol.contex = NULL; + eapol.context = NULL; return EnableEapol(netdev, &eapol); } @@ -486,19 +486,19 @@ static int32_t WifiFillHwFeature(struct NetDevice *netdev, WifiHwFeatureData *fe do { uint32_t loop; if (capability->supportedRateCount > MAX_SUPPORTED_RATE) { - HDF_LOGE("%s: bitrates %d out of range", __func__, capability->supportedRateCount); + HDF_LOGE("%s: bitrates %u out of range", __func__, capability->supportedRateCount); ret = HDF_FAILURE; break; } for (loop = 0; loop < capability->supportedRateCount; ++loop) { - HDF_LOGV("%s: supported rate %d", __func__, capability->supportedRates[loop]); + HDF_LOGV("%s: supported rate %u", __func__, capability->supportedRates[loop]); featureData->bitrate[loop] = capability->supportedRates[loop]; } if (capability->bands[IEEE80211_BAND_2GHZ] != NULL) { struct WlanBand *band = capability->bands[IEEE80211_BAND_2GHZ]; if (band->channelCount > WIFI_24G_CHANNEL_NUM) { - HDF_LOGE("%s: channels %d out of range", __func__, band->channelCount); + HDF_LOGE("%s: channels %u out of range", __func__, band->channelCount); ret = HDF_FAILURE; break; } @@ -630,13 +630,10 @@ static int32_t SetNetIfInfo(struct NetDevice *netdev, uint32_t type) static int32_t UnsetNetIfInfo(struct NetDevice *netdev) { - int ret; - (void)netdev->netDeviceIf->stop(netdev); (void)NetIfDhcpStop(netdev); (void)NetIfDhcpsStop(netdev); - ret = NetIfSetStatus(netdev, NETIF_DOWN); - return ret; + return NetIfSetStatus(netdev, NETIF_DOWN); } static void SetNetworkAddr(struct NetDevice *netdev, uint32_t type) @@ -646,13 +643,13 @@ static void SetNetworkAddr(struct NetDevice *netdev, uint32_t type) IpV4Addr gw; if (type == WIFI_IFTYPE_STATION) { - ip.addr = 0x00000000UL; // 0, 0, 0, 0 - netmask.addr = 0x00000000UL; // 0, 0, 0, 0 - gw.addr = 0x00000000UL; // 0, 0, 0, 0 + ip.addr = 0x00000000UL; + netmask.addr = 0x00000000UL; + gw.addr = 0x00000000UL; } else { - ip.addr = 0x010ca8c0UL; // 192, 168, 12, 1 - netmask.addr = 0x00ffffffUL; // 255, 255, 255, 0 - gw.addr = 0x010ca8c0UL; // 192, 168, 12, 1 + ip.addr = 0x010ca8c0UL; + netmask.addr = 0x00ffffffUL; + gw.addr = 0x010ca8c0UL; } if (netdev != NULL) { @@ -662,9 +659,9 @@ static void SetNetworkAddr(struct NetDevice *netdev, uint32_t type) static void UnsetNetworkAddr(struct NetDevice *netdev) { - IpV4Addr ip = { 0x00000000UL }; // 0, 0, 0, 0 - IpV4Addr netmask = { 0x00000000UL }; // 0, 0, 0, 0 - IpV4Addr gw = { 0x00000000UL }; // 0, 0, 0, 0 + IpV4Addr ip = { 0x00000000UL }; + IpV4Addr netmask = { 0x00000000UL }; + IpV4Addr gw = { 0x00000000UL }; if (netdev != NULL) { NetIfSetAddr(netdev, &ip, &netmask, &gw); @@ -1058,9 +1055,7 @@ static int32_t WifiCmdGetIfNamesByChipId(const RequestContext *context, struct H break; } } while (false); - if (ifNames != NULL) { - OsalMemFree(ifNames); - } + OsalMemFree(ifNames); return ret; } @@ -1135,12 +1130,12 @@ static int32_t WifiCmdDoResetChip(const RequestContext *context, struct HdfSBuf } wlanDevice = HdfWlanGetWlanDevice(chipId); - if (wlanDevice == NULL) { - HDF_LOGE("%s: wlanDevice is NULL, not found!", __func__); + if (wlanDevice == NULL || wlanDevice->reset == NULL) { + HDF_LOGE("%s: wlanDevice or wlanDevice->reset is NULL!", __func__); return HDF_FAILURE; } - ret = DeinitDevice(wlanDevice); + ret = HdfWifiDeinitDevice(wlanDevice); if (ret != HDF_SUCCESS) { return ret; } @@ -1152,7 +1147,7 @@ static int32_t WifiCmdDoResetChip(const RequestContext *context, struct HdfSBuf return ERR_POWER_RESET_FAIL; } - ret = InitDevice(wlanDevice); + ret = HdfWifiInitDevice(wlanDevice); return ret; } @@ -1190,6 +1185,10 @@ static int32_t WifiCmdResetDriver(const RequestContext *context, struct HdfSBuf } struct HdfSBuf *data = HdfSBufCopy(reqData); + if (data == NULL) { + HDF_LOGE("%s: sbuf copy fail", __func__); + return HDF_FAILURE; + } ret = g_baseService->SendAsyncMessage(g_baseService, BASE_SERVICE_ID, CMD_BASE_DO_RESET_PRIVATE, data, SendMessageResetDriverCallBack); diff --git a/model/network/wifi/include/hdf_wifi_cmd.h b/model/network/wifi/include/hdf_wifi_cmd.h index aee3f941..9f0f17c0 100644 --- a/model/network/wifi/include/hdf_wifi_cmd.h +++ b/model/network/wifi/include/hdf_wifi_cmd.h @@ -278,7 +278,7 @@ typedef struct { typedef struct { void *callback; - void *contex; + void *context; } WifiEnableEapol; typedef struct { diff --git a/model/network/wifi/platform/include/hdf_wlan_services.h b/model/network/wifi/platform/include/hdf_wlan_services.h index e419062d..cbc7e5fb 100644 --- a/model/network/wifi/platform/include/hdf_wlan_services.h +++ b/model/network/wifi/platform/include/hdf_wlan_services.h @@ -29,7 +29,6 @@ enum BaseCommands { CMD_BASE_GET_ADDR, CMD_BASE_SET_MODE, CMD_BASE_GET_HW_FEATURE = 10, -// CMD_BASE_SCAN, CMD_BASE_SET_NETDEV, CMD_BASE_SEND_ACTION, CMD_BASE_SET_CLIENT, diff --git a/model/network/wifi/platform/include/message/message_config.h b/model/network/wifi/platform/include/message/message_config.h index 1a301bcb..cc2d47ea 100644 --- a/model/network/wifi/platform/include/message/message_config.h +++ b/model/network/wifi/platform/include/message/message_config.h @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#ifndef __MESSAGE_CONFIG_H__ -#define __MESSAGE_CONFIG_H__ +#ifndef MESSAGE_CONFIG_H +#define MESSAGE_CONFIG_H #include "message_types.h" #ifndef MESSAGE_ENGINE_MAX_SERVICE diff --git a/model/network/wifi/platform/include/message/message_types.h b/model/network/wifi/platform/include/message/message_types.h index 32dce6f5..b973d4c6 100644 --- a/model/network/wifi/platform/include/message/message_types.h +++ b/model/network/wifi/platform/include/message/message_types.h @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#ifndef __MESSAGE_TYPES_H__ -#define __MESSAGE_TYPES_H__ +#ifndef MESSAGE_TYPES_H +#define MESSAGE_TYPES_H #include "hdf_base.h" typedef uint8_t NodeId; diff --git a/model/network/wifi/platform/include/message/sidecar.h b/model/network/wifi/platform/include/message/sidecar.h index 4e1d7f59..10155c11 100644 --- a/model/network/wifi/platform/include/message/sidecar.h +++ b/model/network/wifi/platform/include/message/sidecar.h @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#ifndef __SIDECAR_H__ -#define __SIDECAR_H__ +#ifndef SIDECAR_H +#define SIDECAR_H #include "hdf_base.h" #include "hdf_device_desc.h" #include "osal/osal_sem.h" @@ -29,7 +29,7 @@ enum MessageType { uint8_t senderId; \ uint8_t receiverId; \ uint8_t requestType; \ - bool corssNode; \ + bool crossNode; \ struct HdfDeviceIoClient *client #define RESERVED_SERVICE_ID 0 diff --git a/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c b/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c index 63a47e9c..85580e6b 100644 --- a/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c +++ b/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c @@ -46,13 +46,13 @@ int32_t HdfWlanRegChipDriver(struct HdfChipDriverFactory *obj) return HDF_ERR_INVALID_PARAM; } if (HdfWlanGetChipDriverByName(obj->driverName) != NULL) { - HDF_LOGW("%s: chipdriver factory is already registed.name=%s", __func__, obj->driverName); + HDF_LOGW("%s: chipdriver factory is already registered.name=%s", __func__, obj->driverName); return HDF_SUCCESS; } for (index = 0; index < MAX_CHIPDRIVER_COUNT; index++) { if (g_wlanChipDriverManagerFactory[index] == NULL) { g_wlanChipDriverManagerFactory[index] = obj; - HDF_LOGI("%s:Chip driver %s registed.", __func__, obj->driverName); + HDF_LOGI("%s:Chip driver %s registered.", __func__, obj->driverName); return HDF_SUCCESS; } } diff --git a/model/network/wifi/platform/src/hdf_wlan_config_parser.c b/model/network/wifi/platform/src/hdf_wlan_config_parser.c index b55b3935..d32facbb 100644 --- a/model/network/wifi/platform/src/hdf_wlan_config_parser.c +++ b/model/network/wifi/platform/src/hdf_wlan_config_parser.c @@ -35,7 +35,7 @@ static int32_t ParseWlanStaConfig(const struct DeviceResourceNode *node, struct HDF_LOGE("%s: GetUint8 fail!", __func__); return HDF_FAILURE; } - HDF_LOGD("%s: name=%s, mode=%d!", __func__, staConfig->name, staConfig->mode); + HDF_LOGD("%s: name=%s, mode=%u!", __func__, staConfig->name, staConfig->mode); return HDF_SUCCESS; } @@ -73,7 +73,7 @@ static int32_t ParseWlanApConfig(const struct DeviceResourceNode *node, struct H HDF_LOGE("%s: get userResNum fail!", __func__); return HDF_FAILURE; } - HDF_LOGD("%s: name=%s, mode=%d, vapResNum=%d, userResNum=%d!", __func__, apConfig->name, apConfig->mode, + HDF_LOGD("%s: name=%s, mode=%u, vapResNum=%u, userResNum=%u!", __func__, apConfig->name, apConfig->mode, apConfig->vapResNum, apConfig->userResNum); return HDF_SUCCESS; } @@ -102,7 +102,7 @@ static int32_t ParseWlanP2PConfig(const struct DeviceResourceNode *node, struct HDF_LOGE("%s: mode fail!", __func__); return HDF_FAILURE; } - HDF_LOGD("%s: name=%s, mode=%d", __func__, p2pConfig->name, p2pConfig->mode); + HDF_LOGD("%s: name=%s, mode=%u", __func__, p2pConfig->name, p2pConfig->mode); return HDF_SUCCESS; } @@ -125,7 +125,7 @@ static int32_t ParseWlanMac80211Config(const struct DeviceResourceNode *node, st HDF_LOGE("%s: mode fail!", __func__); return HDF_FAILURE; } - HDF_LOGD("%s: mode=%d", __func__, macConfig->mode); + HDF_LOGD("%s: mode=%u", __func__, macConfig->mode); return HDF_SUCCESS; } @@ -211,10 +211,11 @@ static int32_t ParseWlanModuleConfig(const struct DeviceResourceNode *node, stru return HDF_SUCCESS; } /* BEGIN for WLAN2.1 : Added by hdf-wlan */ -static int32_t ParseWlanPowerConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanPower *masterPowerConfig) +static int32_t ParseWlanPowerConfig(const struct DeviceResourceNode *node, + struct HdfConfigWlanPower *primaryPowerConfig) { struct DeviceResourceIface *drsOps = NULL; - if (node == NULL || masterPowerConfig == NULL) { + if (node == NULL || primaryPowerConfig == NULL) { HDF_LOGE("%s: one of the input para is NULL!", __func__); return HDF_FAILURE; } @@ -224,21 +225,21 @@ static int32_t ParseWlanPowerConfig(const struct DeviceResourceNode *node, struc return HDF_FAILURE; } - if (drsOps->GetUint8(node, "powerSeqDelay", &masterPowerConfig->powerSeqDelay, 0) != HDF_SUCCESS) { + if (drsOps->GetUint8(node, "powerSeqDelay", &primaryPowerConfig->powerSeqDelay, 0) != HDF_SUCCESS) { HDF_LOGE("%s: powersSeqDelay fail!", __func__); return HDF_FAILURE; } - if (drsOps->GetUint8(node, "powerType", &masterPowerConfig->powerType, 0) != HDF_SUCCESS) { + if (drsOps->GetUint8(node, "powerType", &primaryPowerConfig->powerType, 0) != HDF_SUCCESS) { HDF_LOGE("%s: powerType fail!", __func__); return HDF_FAILURE; } - if (drsOps->GetUint8(node, "gpioId", &masterPowerConfig->gpioId, 0) != HDF_SUCCESS) { + if (drsOps->GetUint8(node, "gpioId", &primaryPowerConfig->gpioId, 0) != HDF_SUCCESS) { HDF_LOGE("%s: gpioId fail!", __func__); return HDF_FAILURE; } - if (drsOps->GetUint8(node, "activeLevel", &masterPowerConfig->activeLevel, 0) != HDF_SUCCESS) { + if (drsOps->GetUint8(node, "activeLevel", &primaryPowerConfig->activeLevel, 0) != HDF_SUCCESS) { HDF_LOGE("%s: activeLevel fail!", __func__); return HDF_FAILURE; } @@ -269,7 +270,7 @@ static int32_t ParseWlanPowersConfig(const struct DeviceResourceNode *node, stru } const struct DeviceResourceNode *secPowerNode = drsOps->GetChildNode(node, "power1"); - if (fstPowerNode == NULL) { + if (secPowerNode == NULL) { HDF_LOGE("%s: get power1 config fail!", __func__); return HDF_FAILURE; } @@ -451,7 +452,6 @@ static int32_t ParseWlanChipSdioConfig(const struct DeviceResourceNode *node, st HDF_LOGE("%s: deviceId fail!", __func__); return HDF_FAILURE; } - HDF_LOGI("%s: SDIO vendor=%u, device=%u", __func__, sdioArgs->vendorId, sdioArgs->deviceId[0]); return HDF_SUCCESS; } diff --git a/model/network/wifi/platform/src/hdf_wlan_power_manager.c b/model/network/wifi/platform/src/hdf_wlan_power_manager.c index 09494aba..50592e73 100644 --- a/model/network/wifi/platform/src/hdf_wlan_power_manager.c +++ b/model/network/wifi/platform/src/hdf_wlan_power_manager.c @@ -16,13 +16,13 @@ /* power manager begin */ enum PowerType { - PowerNotManaged = 0, - PowerManagedByGPIO = 1 + POWER_NOT_MANAGED = 0, + POWER_MANAGED_BY_GPIO = 1 }; enum GPIOActiveLevel { - ActiveLow = 0, - ActiveHigh + ACTIVE_LOW = 0, + ACTIVE_HIGH }; /* powerCount=1 single power source */ @@ -44,7 +44,7 @@ static int32_t HdfWlanSinglePowerActive(struct HdfConfigWlanPower* powerDate) HDF_LOGE("%s:powerDate is NULL", __func__); return HDF_FAILURE; } - if (powerDate->powerType != PowerNotManaged) { + if (powerDate->powerType != POWER_NOT_MANAGED) { HDF_LOGI("%s:power type is always on", __func__); return HDF_SUCCESS; } @@ -64,14 +64,14 @@ static int32_t HdfWlanSinglePowerActive(struct HdfConfigWlanPower* powerDate) static int32_t HdfWlanSingleDeActive(struct HdfConfigWlanPower* powerDate) { int32_t ret; - uint8_t deActicve; + uint8_t deActive; if (powerDate == NULL) { HDF_LOGE("%s: powerDate is NULL", __func__); return HDF_FAILURE; } - deActicve = !powerDate->activeLevel; - if (powerDate->powerType == PowerNotManaged) { + deActive = !powerDate->activeLevel; + if (powerDate->powerType == POWER_NOT_MANAGED) { HDF_LOGE("%s:power type is not supported in current version", __func__); return HDF_FAILURE; } @@ -80,7 +80,7 @@ static int32_t HdfWlanSingleDeActive(struct HdfConfigWlanPower* powerDate) HDF_LOGE("%s:set dir fail! ret:%d\n", __func__, ret); return ret; } - ret = GpioWrite(powerDate->gpioId, deActicve); + ret = GpioWrite(powerDate->gpioId, deActive); return HDF_SUCCESS; } @@ -138,7 +138,7 @@ int32_t HdfWlanPowerMgrRelease(struct PowerManager* powerMgr) return HDF_SUCCESS; } /** - * @brief create powers manager accoding to the powers config + * @brief create powers manager according to the powers config */ struct PowerManager* HdfWlanCreatePowerManager(const struct HdfConfWlanPowers *configPowers) { diff --git a/model/network/wifi/platform/src/hdf_wlan_product.c b/model/network/wifi/platform/src/hdf_wlan_product.c index 6c75f2ba..3a50385d 100644 --- a/model/network/wifi/platform/src/hdf_wlan_product.c +++ b/model/network/wifi/platform/src/hdf_wlan_product.c @@ -90,12 +90,15 @@ struct WifiModule *HdfWlanGetModule(void) struct HdfDeviceObject *HdfWlanGetDevice(void) { + if (g_hdfWlanProductData == NULL) { + return NULL; + } return g_hdfWlanProductData->device; } struct HdfWlanDevice *HdfWlanGetWlanDevice(uint8_t chipId) { - if (chipId >= MAX_WLAN_DEVICE) { + if (chipId >= MAX_WLAN_DEVICE || g_hdfWlanProductData == NULL) { return NULL; } return g_hdfWlanProductData->wlanDevice[chipId]; diff --git a/model/network/wifi/platform/src/hdf_wlan_reset_manager.c b/model/network/wifi/platform/src/hdf_wlan_reset_manager.c index 188950b8..595db575 100644 --- a/model/network/wifi/platform/src/hdf_wlan_reset_manager.c +++ b/model/network/wifi/platform/src/hdf_wlan_reset_manager.c @@ -18,8 +18,8 @@ * @brief constant reset manage type */ enum ResetType { - ResetAlwaysOn = 0, - ResetManagedByGPIO = 1 + RESET_ALWAYS_ON = 0, + RESET_MANAGED_BY_GPIO = 1 }; struct HdfWlanResetData { @@ -44,7 +44,7 @@ int32_t HdfChipReset(struct ResetManager *resetManager) return HDF_FAILURE; } resetMgrImpl = (struct ResetManagerImpl*)resetManager; - if (resetMgrImpl->resetData.resetCfg.resetType == ResetAlwaysOn) { + if (resetMgrImpl->resetData.resetCfg.resetType == RESET_ALWAYS_ON) { HDF_LOGE("%s: the reset type is not managed", __func__); return HDF_FAILURE; } @@ -62,7 +62,7 @@ int32_t HdfChipReset(struct ResetManager *resetManager) ret = GpioWrite(resetMgrImpl->resetData.resetCfg.gpioId, !resetMgrImpl->resetData.resetCfg.activeLevel); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: write deactive fail! ret=%d", __func__, ret); + HDF_LOGE("%s: write deactivate fail! ret=%d", __func__, ret); return ret; } OsalMSleep(resetMgrImpl->resetData.bootUpHoldTime); diff --git a/model/network/wifi/platform/src/hdf_wlan_utils.c b/model/network/wifi/platform/src/hdf_wlan_utils.c index 8309ceb8..cc92c61e 100644 --- a/model/network/wifi/platform/src/hdf_wlan_utils.c +++ b/model/network/wifi/platform/src/hdf_wlan_utils.c @@ -72,7 +72,7 @@ int32_t RenewNetDevice(NetDevice **netDev) NetDevice *result = NULL; struct HdfWifiNetDeviceData *data = NULL; int32_t ret; - if (netDev == NULL) { + if (netDev == NULL || *netDev == NULL) { HDF_LOGE("%s:NULL ptr!", __func__); return HDF_FAILURE; } @@ -160,7 +160,6 @@ struct NetDevice *AllocPlatformNetDevice(struct HdfWlanDevice *device) ret = GetPlatformIfName(id, ifName, IFNAMSIZ); if (ret != HDF_SUCCESS) { - OsalMemFree(data); break; } #ifdef _PRE_HDF_LINUX @@ -254,7 +253,7 @@ char *HdfWlanGetIfNames(const uint8_t chipId, uint8_t *ifNameCount) return NULL; } - if (ifNameCount == 0) { + if (*ifNameCount == 0) { return ifNames; } diff --git a/model/network/wifi/platform/src/message/message_dispatcher.c b/model/network/wifi/platform/src/message/message_dispatcher.c index 97d5747a..23056b80 100644 --- a/model/network/wifi/platform/src/message/message_dispatcher.c +++ b/model/network/wifi/platform/src/message/message_dispatcher.c @@ -36,7 +36,7 @@ void ReleaseMessageContext(MessageContext *context) context->rspData = NULL; } - if (context->corssNode || + if (context->crossNode || (context->requestType != MESSAGE_TYPE_SYNC_REQ && context->requestType != MESSAGE_TYPE_SYNC_RSP)) { // Sync request message may use stack mem.Memory is managed by user if (context->reqData != NULL) { @@ -104,7 +104,7 @@ ErrorCode AppendToLocalDispatcher(MessageDispatcher *dispatcher, const uint8_t p void SetToResponse(MessageContext *context) { if (context->requestType != MESSAGE_TYPE_ASYNC_REQ && context->requestType != MESSAGE_TYPE_SYNC_REQ) { - HDF_LOGE("Only sync and async message can send response!type=%d", context->requestType); + HDF_LOGE("Only sync and async message can send response!type=%u", context->requestType); return; } ServiceId senderId = context->senderId; @@ -124,7 +124,6 @@ static void HandleAsyncResponse(MessageContext *context) } ReleaseMessageContext(context); - context = NULL; } static void HandleSyncResponse(MessageContext *context) @@ -135,7 +134,7 @@ static void HandleSyncResponse(MessageContext *context) } HDF_STATUS status = OsalSemPost(&context->rspSemaphore); if (status != HDF_SUCCESS) { - HDF_LOGE("Send semaphore failed!CMD=%d,Sender=%d,Receiver=%d", context->commandId, context->senderId, + HDF_LOGE("Send semaphore failed!CMD=%u,Sender=%u,Receiver=%u", context->commandId, context->senderId, context->receiverId); } return; @@ -148,13 +147,13 @@ static void HandleRequestMessage(MessageContext *context) RemoteService *rspService = NULL; do { if (targetService == NULL) { - HDF_LOGE("%s:Service %d is not available!", __func__, context->receiverId); + HDF_LOGE("%s:Service %u is not available!", __func__, context->receiverId); errCode = ME_ERROR_NULL_PTR; break; } if (targetService->ExecRequestMsg == NULL) { - HDF_LOGE("%s:Service %d has no ExecMsg method!", __func__, context->receiverId); + HDF_LOGE("%s:Service %u has no ExecMsg method!", __func__, context->receiverId); errCode = ME_ERROR_NULL_PTR; break; } @@ -214,7 +213,7 @@ static void HandleMessage(MessageContext *context) HandleAsyncResponse(context); break; default: - HDF_LOGE("Unsupported message type %d", context->requestType); + HDF_LOGE("Unsupported message type %u", context->requestType); } } } @@ -323,12 +322,7 @@ static ErrorCode StartDispatcher(MessageDispatcher *dispatcher) do { OsalMSleep(1); } while (dispatcher->status == ME_STATUS_STARTTING); - - if (dispatcher->status == ME_STATUS_RUNNING) { - return ME_SUCCESS; - } else { - return ME_ERROR_WRONG_STATUS; - } + return (dispatcher->status == ME_STATUS_RUNNING) ? ME_SUCCESS : ME_ERROR_WRONG_STATUS; } static void ShutdownDispatcher(MessageDispatcher *dispatcher) diff --git a/model/network/wifi/platform/src/message/message_router.c b/model/network/wifi/platform/src/message/message_router.c index ab77a65d..3776a3e6 100644 --- a/model/network/wifi/platform/src/message/message_router.c +++ b/model/network/wifi/platform/src/message/message_router.c @@ -6,6 +6,7 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "message_router.h" #include "hdf_base.h" #ifdef USERSPACE_CLIENT_SUPPORT #include @@ -14,7 +15,6 @@ #include "utils/hdf_log.h" #include "osal/osal_mutex.h" #include "securec.h" -#include "message_router.h" #include "message_router_inner.h" #include "message_dispatcher.h" @@ -25,7 +25,7 @@ #endif #ifndef UINT8_MAX -#define UINT8_MAX 256 +#define UINT8_MAX 255 #endif #if MESSAGE_ENGINE_MAX_DISPATCHER > UINT8_MAX @@ -71,7 +71,7 @@ static void ReleaseRemoteService(RemoteService *service) static MessageDispatcher *RefDispatcherInner(const DispatcherId dispatcherId, bool requireLock) { if (dispatcherId >= MESSAGE_ENGINE_MAX_DISPATCHER) { - HDF_LOGE("%s:Input ID is too big.input=%d", __func__, dispatcherId); + HDF_LOGE("%s:Input ID is too big.input=%u", __func__, dispatcherId); return NULL; } @@ -106,7 +106,7 @@ static MessageDispatcher *RefDispatcherInner(const DispatcherId dispatcherId, bo static ErrorCode RegDispatcher(DispatcherId dispatcherId, MessageDispatcher *dispatcher) { if (dispatcherId >= MESSAGE_ENGINE_MAX_DISPATCHER) { - HDF_LOGE("%s:dispatcher id is too big!id=%d", __func__, dispatcherId); + HDF_LOGE("%s:dispatcher id is too big!id=%u", __func__, dispatcherId); return ME_ERROR_PARA_WRONG; } @@ -122,7 +122,7 @@ static ErrorCode RegDispatcher(DispatcherId dispatcherId, MessageDispatcher *dis break; } if (g_dispatchers[dispatcherId] != NULL) { - HDF_LOGE("%s:DispatcherId conflict!ID=%d", __func__, dispatcherId); + HDF_LOGE("%s:DispatcherId conflict!ID=%u", __func__, dispatcherId); errCode = ME_ERROR_DISPATCHERID_CONFLICT; } else { g_dispatchers[dispatcherId] = dispatcher; @@ -154,7 +154,7 @@ ErrorCode AddDispatcher(DispatcherConfig *config) if (dispatcher->Start != NULL) { errCode = dispatcher->Start(dispatcher); if (errCode != ME_SUCCESS) { - HDF_LOGE("%s:Start dispatcher %d failed!errCode=%d", __func__, config->dispatcherId, errCode); + HDF_LOGE("%s:Start dispatcher %u failed!errCode=%d", __func__, config->dispatcherId, errCode); break; } } @@ -242,7 +242,7 @@ static ErrorCode DoRegistService(const NodeId nodeId, const DispatcherId dispatc return ME_ERROR_WRONG_STATUS; } - HDF_LOGW("%s:Regist service Node:%d;Dispatcher:%d;Service:%d", __func__, nodeId, dispatcherId, + HDF_LOGW("%s:Register service Node:%d;Dispatcher:%u;Service:%u", __func__, nodeId, dispatcherId, remoteService->serviceId); if (g_servicesIndex[remoteService->serviceId].remoteService != NULL) { @@ -263,7 +263,7 @@ static ErrorCode RegistServiceInner(const NodeId nodeId, const DispatcherId disp } if (mapper->serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { - HDF_LOGE("%s:serviceId exceed max value! ServiceId=%d", __func__, mapper->serviceId); + HDF_LOGE("%s:serviceId exceed max value! ServiceId=%u", __func__, mapper->serviceId); return ME_ERROR_PARA_WRONG; } HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); @@ -275,6 +275,7 @@ static ErrorCode RegistServiceInner(const NodeId nodeId, const DispatcherId disp MessageNode *node = RefMessageNode(nodeId, false); if (node == NULL) { HDF_LOGE("%s:Node not found!", __func__); + OsalMutexUnlock(&g_routerMutex); return ME_ERROR_NO_SUCH_NODE; } RemoteService *remoteService = NULL; @@ -556,7 +557,7 @@ static ErrorCode DoStartMessageRouter(uint8_t nodesConfig) return ME_ERROR_MUTI_INIT_NOT_ALLOWED; } - for (i = 0; i < UINT8_MAX && i < MESSAGE_ENGINE_MAX_SERVICE; i++) { + for (i = 0; i < MESSAGE_ENGINE_MAX_SERVICE; i++) { g_servicesIndex[i].remoteService = NULL; g_servicesIndex[i].nodeIndex = NO_SUCH_NODE_INDEX; g_servicesIndex[i].dispatcherId = BAD_DISPATCHER_ID; @@ -599,10 +600,10 @@ ErrorCode EnableDefaultDispatcher(void) .queueSize = DEFAULT_DISPATCHER_QUEUE_SIZE, .priorityLevelCount = DEFAULT_DISPATCHER_PRIORITY_COUNT }; - HDF_LOGI("Regist default dispatcher..."); + HDF_LOGI("Register default dispatcher..."); ErrorCode errCode = AddDispatcher(&config); if (errCode != ME_SUCCESS) { - HDF_LOGE("Regist default dispatcher failed!ret=%d", errCode); + HDF_LOGE("Register default dispatcher failed!ret=%d", errCode); } return errCode; } diff --git a/model/network/wifi/platform/src/message/nodes/local_node.c b/model/network/wifi/platform/src/message/nodes/local_node.c index 5ac55373..b5b8c89a 100644 --- a/model/network/wifi/platform/src/message/nodes/local_node.c +++ b/model/network/wifi/platform/src/message/nodes/local_node.c @@ -67,18 +67,19 @@ static void HandleResponseMessage(const RemoteService *service, MessageContext * } ReleaseMessageContext(context); } else { - HDF_LOGE("%s:Response type not supported!type=%d", __func__, context->requestType); + HDF_LOGE("%s:Response type not supported!type=%u", __func__, context->requestType); } } ErrorCode SendMessageLocalNode(const RemoteService *service, MessageContext *context) { + uint8_t pri = HIGHEST_PRIORITY; if (service == NULL || context == NULL) { HDF_LOGE("%s:Input is NULL!", __func__); return ME_ERROR_NULL_PTR; } - if (!context->corssNode && context->requestType == MESSAGE_TYPE_SYNC_REQ) { + if (!context->crossNode && context->requestType == MESSAGE_TYPE_SYNC_REQ) { HandleRequestMessage(service, context); SetToResponse(context); return context->responseStatus; @@ -103,11 +104,9 @@ ErrorCode SendMessageLocalNode(const RemoteService *service, MessageContext *con return ME_ERROR_NO_SUCH_COMMAND; } - uint8_t pri = localService->mapper->messages[context->commandId].pri; - return localService->dispatcher->AppendMessage(localService->dispatcher, pri, context); - } else { - return localService->dispatcher->AppendMessage(localService->dispatcher, HIGHEST_PRIORITY, context); + pri = localService->mapper->messages[context->commandId].pri; } + return localService->dispatcher->AppendMessage(localService->dispatcher, pri, context); } } diff --git a/model/network/wifi/platform/src/message/sidecar.c b/model/network/wifi/platform/src/message/sidecar.c index b49e9abd..dc8692e9 100644 --- a/model/network/wifi/platform/src/message/sidecar.c +++ b/model/network/wifi/platform/src/message/sidecar.c @@ -50,7 +50,7 @@ static MessageContext *CreateMessageContext(ServiceId sender, ServiceId receiver context->senderId = sender; context->receiverId = receiver; context->reqData = sendData; - context->corssNode = false; + context->crossNode = false; return context; } @@ -260,7 +260,7 @@ Service *InitService(struct ServiceDef *def, const ServiceCfg *cfg) service->privateData = NULL; OsalMemFree(service); service = NULL; - HDF_LOGE("Regist service failed!serviceId=%d,ret=%d", def->serviceId, errCode); + HDF_LOGE("Register service failed!serviceId=%d,ret=%d", def->serviceId, errCode); return NULL; } return service; diff --git a/model/network/wifi/platform/src/qos/flow_control.c b/model/network/wifi/platform/src/qos/flow_control.c index 923598eb..b4963f5c 100644 --- a/model/network/wifi/platform/src/qos/flow_control.c +++ b/model/network/wifi/platform/src/qos/flow_control.c @@ -101,7 +101,7 @@ static FlowControlQueueID IpProcessFunc(const void *buff, uint32_t len) return QUEUE_ID_COUNT; } if (len < sizeof(struct IpHeader)) { - HDF_LOGE("%s fail: len not right!", __func__); + HDF_LOGE("%s fail: IpHeader len not right!", __func__); return QUEUE_ID_COUNT; } ipHeader = (struct IpHeader *)buff; @@ -116,6 +116,10 @@ static FlowControlQueueID IpProcessFunc(const void *buff, uint32_t len) * ---------------------------------------------------------------------- */ id = TosToFcQueueId(ipHeader->tos >> IP_PRI_SHIFT); + if ((len - sizeof(struct IpHeader)) < sizeof(struct UdpHeader)) { + HDF_LOGE("%s fail: UdpHeader len not right!", __func__); + return QUEUE_ID_COUNT; + } udpHdr = (struct UdpHeader *)(ipHeader + 1); if (((ntohs(ipHeader->fragInfo) & 0x1FFF) == 0) && IsDhcpPort(udpHdr, len - sizeof(struct IpHeader))) { id = VIP_QUEUE_ID; @@ -381,7 +385,7 @@ void DeInitFlowControl(struct FlowControlModule *fcm) return; } - /* 1:Detroy task. 2:Destroy osalwait. 3:free NetBuff. */ + /* 1:Destroy task. 2:Destroy osalwait. 3:free NetBuff. */ DestroyFlowControlTask(fcm); for (i = 0; i < FLOW_DIR_COUNT; i++) { OsalSemDestroy(&fcm->sem[i]); diff --git a/model/sensor/driver/accel/sensor_accel_driver.c b/model/sensor/driver/accel/sensor_accel_driver.c index 05bd9d4e..b2d73c95 100644 --- a/model/sensor/driver/accel/sensor_accel_driver.c +++ b/model/sensor/driver/accel/sensor_accel_driver.c @@ -38,7 +38,7 @@ static struct AccelDrvData *AccelGetDrvData(void) static struct SensorRegCfgGroupNode *g_regCfgGroup[SENSOR_GROUP_MAX] = { NULL }; -int32_t RegisterAccelChipOps(struct AccelOpsCall *ops) +int32_t RegisterAccelChipOps(const struct AccelOpsCall *ops) { struct AccelDrvData *drvData = NULL; @@ -131,7 +131,7 @@ static int32_t SetAccelEnable(void) CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor disable config failed", __func__); + HDF_LOGE("%s: accel sensor enable config failed", __func__); return HDF_FAILURE; } @@ -209,7 +209,6 @@ static int32_t InitAccelOps(struct SensorDeviceInfo *deviceInfo) { struct AccelDrvData *drvData = AccelGetDrvData(); - (void)memset_s((void *)deviceInfo, sizeof(*deviceInfo), 0, sizeof(*deviceInfo)); deviceInfo->ops.GetInfo = SetAccelInfo; deviceInfo->ops.Enable = SetAccelEnable; deviceInfo->ops.Disable = SetAccelDisable; diff --git a/model/sensor/driver/accel/sensor_accel_driver.h b/model/sensor/driver/accel/sensor_accel_driver.h index e28b39ff..c97df8e3 100644 --- a/model/sensor/driver/accel/sensor_accel_driver.h +++ b/model/sensor/driver/accel/sensor_accel_driver.h @@ -59,6 +59,6 @@ struct AccelDrvData { struct AccelOpsCall ops; }; -int32_t RegisterAccelChipOps(struct AccelOpsCall *ops); +int32_t RegisterAccelChipOps(const struct AccelOpsCall *ops); #endif /* SENSOR_ACCEL_DRIVER_H */ diff --git a/model/sensor/driver/chipset/accel/accel_bmi160.c b/model/sensor/driver/chipset/accel/accel_bmi160.c index 669dd0c7..382c60f9 100644 --- a/model/sensor/driver/chipset/accel/accel_bmi160.c +++ b/model/sensor/driver/chipset/accel/accel_bmi160.c @@ -25,9 +25,14 @@ static int32_t ReadBmi160RawData(struct SensorCfgData *data, struct AccelData *r OsalTimespec time; (void)memset_s(&time, sizeof(time), 0, sizeof(time)); - (void)OsalGetTime(&time); + (void)memset_s(reg, sizeof(reg), 0, sizeof(reg)); CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + + if (OsalGetTime(&time) != HDF_SUCCESS) { + HDF_LOGE("%s: Get time failed", __func__); + return HDF_FAILURE; + } *timestamp = time.sec * SENSOR_SECOND_CONVERT_NANOSECOND + time.usec * SENSOR_CONVERT_UNIT; /* unit nanosecond */ int32_t ret = ReadSensor(&data->busCfg, BMI160_STATUS_ADDR, &status, sizeof(uint8_t)); @@ -36,34 +41,22 @@ static int32_t ReadBmi160RawData(struct SensorCfgData *data, struct AccelData *r } ret = ReadSensor(&data->busCfg, BMI160_ACCEL_X_LSB_ADDR, ®[ACCEL_X_AXIS_LSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read X_AXIS_LSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); ret = ReadSensor(&data->busCfg, BMI160_ACCEL_X_MSB_ADDR, ®[ACCEL_X_AXIS_MSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read X_AXIS_MSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); ret = ReadSensor(&data->busCfg, BMI160_ACCEL_Y_LSB_ADDR, ®[ACCEL_Y_AXIS_LSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read Y_AXIS_LSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); ret = ReadSensor(&data->busCfg, BMI160_ACCEL_Y_MSB_ADDR, ®[ACCEL_Y_AXIS_MSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read Y_AXIS_MSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); ret = ReadSensor(&data->busCfg, BMI160_ACCEL_Z_LSB_ADDR, ®[ACCEL_Z_AXIS_LSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read Z_AXIS_LSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); ret = ReadSensor(&data->busCfg, BMI160_ACCEL_Z_MSB_ADDR, ®[ACCEL_Z_AXIS_MSB], sizeof(uint8_t)); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: i2c read Z_AXIS_MSB failed", __func__); - } + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read data"); rawData->x = (int16_t)(SENSOR_DATA_SHIFT_LEFT(reg[ACCEL_X_AXIS_MSB], SENSOR_DATA_WIDTH_8_BIT) | reg[ACCEL_X_AXIS_LSB]); @@ -78,7 +71,7 @@ static int32_t ReadBmi160RawData(struct SensorCfgData *data, struct AccelData *r int32_t ReadBmi160Data(struct SensorCfgData *data) { int32_t ret; - struct AccelData rawData = { 0, 0, 0 }; + struct AccelData rawData = { 0, 0, 0 }; int32_t tmp[ACCEL_AXIS_NUM]; struct SensorReportEvent event; @@ -114,7 +107,7 @@ static int32_t InitBmi160(struct SensorCfgData *data) CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); ret = SetSensorRegCfgArray(&data->busCfg, data->regCfgGroup[SENSOR_INIT_GROUP]); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: bmi160 sensor init config failed", __func__); + HDF_LOGE("%s: BMI160 sensor init config failed", __func__); return HDF_FAILURE; } return HDF_SUCCESS; @@ -123,11 +116,11 @@ static int32_t InitBmi160(struct SensorCfgData *data) static int32_t InitAccelPreConfig(void) { if (SetSensorPinMux(SENSOR_I2C6_DATA_REG_ADDR, SENSOR_ADDR_WIDTH_4_BYTE, SENSOR_I2C_REG_CFG) != HDF_SUCCESS) { - HDF_LOGE("%s: data write mux pin failed", __func__); + HDF_LOGE("%s: Data write mux pin failed", __func__); return HDF_FAILURE; } if (SetSensorPinMux(SENSOR_I2C6_CLK_REG_ADDR, SENSOR_ADDR_WIDTH_4_BYTE, SENSOR_I2C_REG_CFG) != HDF_SUCCESS) { - HDF_LOGE("%s: clc write mux pin failed", __func__); + HDF_LOGE("%s: Clk write mux pin failed", __func__); return HDF_FAILURE; } diff --git a/model/sensor/driver/common/include/sensor_device_manager.h b/model/sensor/driver/common/include/sensor_device_manager.h index c626ca2b..984b221b 100644 --- a/model/sensor/driver/common/include/sensor_device_manager.h +++ b/model/sensor/driver/common/include/sensor_device_manager.h @@ -13,7 +13,7 @@ #include "sensor_driver_type.h" enum SensorMethodCmd { - SENSOR_CMD_GET_INFO_LIST = 0xFFFF, + SENSOR_CMD_GET_INFO_LIST = 0, SENSOR_CMD_ENABLE = 1, SENSOR_CMD_DISABLE = 2, SENSOR_CMD_SET_BATCH = 3, diff --git a/model/sensor/driver/common/include/sensor_parser.h b/model/sensor/driver/common/include/sensor_parser.h index f3950e37..d69c3225 100644 --- a/model/sensor/driver/common/include/sensor_parser.h +++ b/model/sensor/driver/common/include/sensor_parser.h @@ -15,6 +15,8 @@ #include "sensor_driver_type.h" #include "spi_if.h" +#define SENSOR_CONFIG_MAX_ITEM 100 + enum SensorBusType { SENSOR_BUS_I2C = 0, SENSOR_BUS_SPI = 1, diff --git a/model/sensor/driver/common/src/sensor_common.c b/model/sensor/driver/common/src/sensor_common.c index 0c47fa03..c7130f67 100644 --- a/model/sensor/driver/common/src/sensor_common.c +++ b/model/sensor/driver/common/src/sensor_common.c @@ -27,7 +27,6 @@ int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen) { - uint8_t busType; int index = 0; unsigned char regBuf[I2C_REG_BUF_LEN] = {0}; struct I2cMsg msg[I2C_READ_MSG_NUM]; @@ -35,10 +34,8 @@ int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); CHECK_NULL_PTR_RETURN_VALUE(data, HDF_FAILURE); - busType = busCfg->busType; - if (busType == SENSOR_BUS_I2C) { + if (busCfg->busType == SENSOR_BUS_I2C) { CHECK_NULL_PTR_RETURN_VALUE(busCfg->i2cCfg.handle, HDF_FAILURE); - (void)memset_s(msg, sizeof(msg), 0, sizeof(msg)); msg[I2C_READ_MSG_ADDR_IDX].addr = busCfg->i2cCfg.devAddr; msg[I2C_READ_MSG_ADDR_IDX].flags = 0; @@ -50,6 +47,9 @@ int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, } else if (busCfg->i2cCfg.regWidth == SENSOR_ADDR_WIDTH_2_BYTE) { regBuf[index++] = (regAddr >> I2C_BYTE_OFFSET) & I2C_BYTE_MASK; regBuf[index++] = regAddr & I2C_BYTE_MASK; + } else { + HDF_LOGE("%s: i2c regWidth[%u] failed", __func__, busCfg->i2cCfg.regWidth); + return HDF_FAILURE; } msg[I2C_READ_MSG_VALUE_IDX].addr = busCfg->i2cCfg.devAddr; @@ -58,7 +58,7 @@ int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, msg[I2C_READ_MSG_VALUE_IDX].buf = data; if (I2cTransfer(busCfg->i2cCfg.handle, msg, I2C_READ_MSG_NUM) != I2C_READ_MSG_NUM) { - HDF_LOGE("%s: i2c[%d] read failed", __func__, busCfg->i2cCfg.busNum); + HDF_LOGE("%s: i2c[%u] read failed", __func__, busCfg->i2cCfg.busNum); return HDF_FAILURE; } } @@ -68,16 +68,13 @@ int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t dataLen) { - uint8_t busType; struct I2cMsg msg[I2C_WRITE_MSG_NUM]; CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); CHECK_NULL_PTR_RETURN_VALUE(writeData, HDF_FAILURE); - busType = busCfg->busType; - if (busType == SENSOR_BUS_I2C) { + if (busCfg->busType == SENSOR_BUS_I2C) { CHECK_NULL_PTR_RETURN_VALUE(busCfg->i2cCfg.handle, HDF_FAILURE); - (void)memset_s(msg, sizeof(msg), 0, sizeof(msg)); msg[0].addr = busCfg->i2cCfg.devAddr; msg[0].flags = 0; @@ -85,7 +82,7 @@ int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t da msg[0].buf = writeData; if (I2cTransfer(busCfg->i2cCfg.handle, msg, I2C_WRITE_MSG_NUM) != I2C_WRITE_MSG_NUM) { - HDF_LOGE("%s: i2c[%d] write failed", __func__, busCfg->i2cCfg.busNum); + HDF_LOGE("%s: i2c[%u] write failed", __func__, busCfg->i2cCfg.busNum); return HDF_FAILURE; } } @@ -163,4 +160,4 @@ void DestroySensorThread(struct OsalThread *thread, uint8_t *status) OsalThreadDestroy(thread); *status = SENSOR_THREAD_DESTROY; -} +} \ No newline at end of file diff --git a/model/sensor/driver/common/src/sensor_device_common.c b/model/sensor/driver/common/src/sensor_device_common.c index 7816aee9..08fc9f4e 100644 --- a/model/sensor/driver/common/src/sensor_device_common.c +++ b/model/sensor/driver/common/src/sensor_device_common.c @@ -82,9 +82,10 @@ static int32_t SensorOpsReadCheck(struct SensorBusCfg *busCfg, struct SensorRegC uint16_t mask; uint16_t busMask = 0xffff; int32_t ret; - uint8_t busType = busCfg->busType; - if (busType == SENSOR_BUS_I2C) { + CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); + + if (busCfg->busType == SENSOR_BUS_I2C) { ret = ReadSensor(busCfg, cfgItem->regAddr, (uint8_t *)&value, sizeof(value)); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read i2c reg"); busMask = (busCfg->i2cCfg.regWidth == SENSOR_ADDR_WIDTH_1_BYTE) ? 0x00ff : 0xffff; @@ -100,6 +101,8 @@ static int32_t SensorOpsReadCheck(struct SensorBusCfg *busCfg, struct SensorRegC static int32_t SensorOpsUpdateBitwise(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) { + (void)busCfg; + (void)cfgItem; return HDF_SUCCESS; } @@ -114,13 +117,21 @@ static struct SensorOpsCall g_doOpsCall[] = { int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group) { int32_t num = 0; + uint32_t count; struct SensorRegCfg *cfgItem = NULL; CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); CHECK_NULL_PTR_RETURN_VALUE(group, HDF_FAILURE); + CHECK_NULL_PTR_RETURN_VALUE(group->regCfgItem, HDF_FAILURE); + + count = sizeof(g_doOpsCall) / sizeof(g_doOpsCall[0]); while (num < group->itemNum) { cfgItem = (group->regCfgItem + num); + if (cfgItem->opsType >= count) { + HDF_LOGE("%s: cfg item para invalid", __func__); + break; + } if (g_doOpsCall[cfgItem->opsType].ops != NULL) { if (g_doOpsCall[cfgItem->opsType].ops(busCfg, cfgItem) != HDF_SUCCESS) { HDF_LOGE("%s: malloc sensor reg config item data failed", __func__); diff --git a/model/sensor/driver/common/src/sensor_device_manager.c b/model/sensor/driver/common/src/sensor_device_manager.c index 94c3c950..e520262e 100644 --- a/model/sensor/driver/common/src/sensor_device_manager.c +++ b/model/sensor/driver/common/src/sensor_device_manager.c @@ -48,6 +48,10 @@ int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) if (!existSensor) { devInfoNode = (struct SensorDevInfoNode*)OsalMemCalloc(sizeof(*devInfoNode)); + if (devInfoNode == NULL) { + (void)OsalMutexUnlock(&manager->mutex); + return HDF_FAILURE; + } if (memcpy_s(&devInfoNode->devInfo, sizeof(devInfoNode->devInfo), (void *)deviceInfo, sizeof(*deviceInfo)) != EOK) { HDF_LOGE("%s: copy sensor info failed", __func__); @@ -94,7 +98,10 @@ int32_t ReportSensorEvent(const struct SensorReportEvent *events) (void)OsalMutexLock(&manager->eventMutex); struct HdfSBuf *msg = HdfSBufObtain(HDF_SENSOR_EVENT_MAX_BUF); - CHECK_NULL_PTR_RETURN_VALUE(msg, HDF_ERR_INVALID_PARAM); + if (msg == NULL) { + (void)OsalMutexUnlock(&manager->eventMutex); + return HDF_ERR_INVALID_PARAM; + } if (!HdfSbufWriteBuffer(msg, events, sizeof(*events))) { HDF_LOGE("%s: sbuf write event failed", __func__); @@ -235,6 +242,7 @@ static int32_t DispatchCmdHandle(struct SensorDeviceInfo *deviceInfo, struct Hdf { int32_t methodCmd; int32_t loop; + int32_t count; CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); @@ -248,7 +256,8 @@ static int32_t DispatchCmdHandle(struct SensorDeviceInfo *deviceInfo, struct Hdf return HDF_FAILURE; } - for (loop = 0; loop < sizeof(g_sensorCmdHandle) / sizeof(g_sensorCmdHandle[0]); ++loop) { + count = sizeof(g_sensorCmdHandle) / sizeof(g_sensorCmdHandle[0]); + for (loop = 0; loop < count; ++loop) { if ((methodCmd == g_sensorCmdHandle[loop].cmd) && (g_sensorCmdHandle[loop].func != NULL)) { return g_sensorCmdHandle[loop].func(deviceInfo, data, reply); } @@ -310,15 +319,22 @@ int32_t InitSensorDevManager(struct HdfDeviceObject *device) CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); DListHeadInit(&manager->sensorDevInfoHead); - OsalMutexInit(&manager->mutex); - OsalMutexInit(&manager->eventMutex); + if (OsalMutexInit(&manager->mutex) != HDF_SUCCESS) { + HDF_LOGE("%s: init mutex failed", __func__); + return HDF_FAILURE; + } + + if (OsalMutexInit(&manager->eventMutex) != HDF_SUCCESS) { + HDF_LOGE("%s: init eventMutex failed", __func__); + return HDF_FAILURE; + } if (!HdfDeviceSetClass(device, DEVICE_CLASS_SENSOR)) { HDF_LOGE("%s: init sensor set class failed", __func__); return HDF_FAILURE; } - HDF_LOGI("%s: init sensor manager success", __func__); + HDF_LOGI("%s: init sensor manager successfully", __func__); return HDF_SUCCESS; } diff --git a/model/sensor/driver/common/src/sensor_parser.c b/model/sensor/driver/common/src/sensor_parser.c index 96392aca..57472baa 100644 --- a/model/sensor/driver/common/src/sensor_parser.c +++ b/model/sensor/driver/common/src/sensor_parser.c @@ -22,22 +22,18 @@ static char *g_sensorRegGroupName[SENSOR_GROUP_MAX] = { static uint32_t GetSensorRegGroupNameIndex(const char *name) { - uint32_t index = 0xFF; + uint32_t index; if (name == NULL) { - return index; + return SENSOR_GROUP_MAX; } for (index = 0; index < SENSOR_GROUP_MAX; ++index) { - if (strcmp(name, g_sensorRegGroupName[index]) == 0) { + if ((g_sensorRegGroupName[index] != NULL) && (strcmp(name, g_sensorRegGroupName[index]) == 0)) { break; } } - if (index == SENSOR_GROUP_MAX) { - index = 0xFF; - } - return index; } @@ -73,6 +69,11 @@ static int32_t ParseSensorRegItem(struct DeviceResourceIface *parser, const stru CHECK_NULL_PTR_RETURN_VALUE(groupName, HDF_ERR_INVALID_PARAM); int32_t num = parser->GetElemNum(regNode, groupName); + if (num <= 0 || num > SENSOR_CONFIG_MAX_ITEM) { + HDF_LOGE("%s: parser %s element num failed", __func__, groupName); + return HDF_SUCCESS; + } + uint16_t *buf = (uint16_t *)OsalMemCalloc(sizeof(uint16_t) * num); CHECK_NULL_PTR_RETURN_VALUE(buf, HDF_ERR_MALLOC_FAIL); @@ -196,7 +197,6 @@ int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) if (busCfg->busType == SENSOR_BUS_I2C) { int16_t busNum = busCfg->i2cCfg.busNum; busCfg->i2cCfg.handle = I2cOpen(busNum); - if (busCfg->i2cCfg.handle == NULL) { HDF_LOGE("%s: sensor i2c Handle invalid", __func__); return HDF_FAILURE; @@ -246,7 +246,7 @@ int32_t DetectSensorDevice(struct SensorCfgData *config) } if (value != chipIdValue) { - HDF_LOGE("%s: sensor chip[0x%x] id [0x%x] detect value[%d]", __func__, chipIdReg, chipIdValue, value); + HDF_LOGE("%s: sensor chip[0x%x] id [0x%x] detect value[%u]", __func__, chipIdReg, chipIdValue, value); (void)ReleaseSensorBusHandle(&config->busCfg); return HDF_FAILURE; } @@ -379,4 +379,4 @@ int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct Se CHECK_PARSER_RESULT_RETURN_VALUE(ret, "accelAttr"); return HDF_SUCCESS; -} +} \ No newline at end of file diff --git a/model/sensor/driver/include/sensor_driver_type.h b/model/sensor/driver/include/sensor_driver_type.h index ef2d3c70..dfbe3c39 100644 --- a/model/sensor/driver/include/sensor_driver_type.h +++ b/model/sensor/driver/include/sensor_driver_type.h @@ -37,7 +37,7 @@ enum SensorWorkMode { }; enum SensorTag { - SENSOR_TAG_NONE = 0, /**< No sensor type for sensor test*/ + SENSOR_TAG_NONE = 0, /**< No sensor type for sensor test */ SENSOR_TAG_ACCELEROMETER = 1, /**< Acceleration sensor */ SENSOR_TAG_GYROSCOPE = 2, /**< Gyroscope sensor */ SENSOR_TAG_PHOTOPLETHYSMOGRAPH = 3, /**< Photoplethysmography sensor */ diff --git a/support/platform/include/common/platform.h b/support/platform/include/common/platform.h new file mode 100644 index 00000000..dd3a5563 --- /dev/null +++ b/support/platform/include/common/platform.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ +#ifndef PLATFORM_H +#define PLATFORM_H + +#include "platform_common.h" +#include "platform_device.h" +#include "platform_manager.h" +#include "platform_queue.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_H */ diff --git a/support/platform/include/common/platform_common.h b/support/platform/include/common/platform_common.h new file mode 100644 index 00000000..a3d78b6b --- /dev/null +++ b/support/platform/include/common/platform_common.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef PLATFORM_COMMON_H +#define PLATFORM_COMMON_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +enum PlatformModuleType { + PLATFORM_MODULE_GPIO, + PLATFORM_MODULE_I2C, + PLATFORM_MODULE_SPI, + PLATFORM_MODULE_PIN, + PLATFORM_MODULE_CLOCK, + PLATFORM_MODULE_REGULATOR, + PLATFORM_MODULE_MIPI_DSI, + PLATFORM_MODULE_UART, + PLATFORM_MODULE_SDIO, + PLATFORM_MODULE_MDIO, + PLATFORM_MODULE_APB, + PLATFORM_MODULE_PCIE, + PLATFORM_MODULE_PCM, + PLATFORM_MODULE_I2S, + PLATFORM_MODULE_PWM, + PLATFORM_MODULE_DMA, + PLATFORM_MODULE_ADC, + PLATFORM_MODULE_RTC, + PLATFORM_MODULE_WDT, + PLATFORM_MODULE_I3C, + PLATFORM_MODULE_CAN, + PLATFORM_MODULE_HDMI, + PLATFORM_MODULE_MMC, + PLATFORM_MODULE_MTD, + PLATFORM_MODULE_DEFAULT, + PLATFORM_MODULE_MAX, +}; + +struct PlatformModuleInfo { + enum PlatformModuleType moduleType; + const char *moduleName; + void *priv; +}; + +struct PlatformModuleInfo *PlatformModuleInfoGet(enum PlatformModuleType moduleType); +int32_t PlatformModuleInfoCount(void); + +enum PlatformErrno { +#define HDF_PLT_ERR_START HDF_BSP_ERR_START /**< Error number start of platform. */ +#define HDF_PLT_ERR_NUM(v) (HDF_PLT_ERR_START + (v)) + HDF_PLT_ERR_OS_API = HDF_ERR_BSP_PLT_API_ERR, + HDF_PLT_ERR_OPEN_DEV = HDF_PAL_ERR_DEV_CREATE, /**< Failed to open a device. */ + HDF_PLT_ERR_INNER = HDF_PAL_ERR_INNER, /**< Internal error of platform framework. */ + + HDF_PLT_ERR_NO_DEV = HDF_PLT_ERR_NUM(-5), /**< There is no device present. */ + HDF_PLT_ERR_DEV_TYPE = HDF_PLT_ERR_NUM(-6), /**< invalid device type */ + HDF_PLT_ERR_DEV_GET = HDF_PLT_ERR_NUM(-7), /**< err on device get */ + HDF_PLT_ERR_DEV_ADD = HDF_PLT_ERR_NUM(-8), /**< err on device add */ + HDF_PLT_ERR_DEV_FULL = HDF_PLT_ERR_NUM(-9), /**< id number conflict */ + HDF_PLT_ERR_ID_REPEAT = HDF_PLT_ERR_NUM(-10), /**< id number conflict */ +#define HDF_MMC_ERR_START (HDF_PLT_ERR_START - 50) /**< Error number start for mmc. */ +#define HDF_MMC_ERR_NUM(v) (HDF_MMC_ERR_START + (v)) + HDF_MMC_ERR_SWITCH_FAIL = HDF_MMC_ERR_NUM(-1), + HDF_MMC_ERR_OTHER_CMD_IS_RUNNING = HDF_MMC_ERR_NUM(-2), + HDF_MMC_ERR_ILLEGAL_SEQ = HDF_MMC_ERR_NUM(-3), +}; + +void PlatformGlobalLock(void); +void PlatformGlobalUnlock(void); + +/* Os adapt */ +bool PlatInIrqContext(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_COMMON_H */ diff --git a/support/platform/include/common/platform_device.h b/support/platform/include/common/platform_device.h new file mode 100644 index 00000000..d5363b97 --- /dev/null +++ b/support/platform/include/common/platform_device.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef PLATFORM_DEVICE_H +#define PLATFORM_DEVICE_H + +#include "hdf_base.h" +#include "hdf_dlist.h" +#include "hdf_sref.h" +#include "osal_sem.h" +#include "osal_spinlock.h" +#include "platform_common.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct PlatformManager; + +struct PlatformDevice { + struct HdfDeviceObject *hdfDev; /* releated to an hdf device object */ + struct PlatformManager *manager; /* the platform manager it belongs to */ + uint32_t magic; /* magic number of the device instance */ + const char *name; /* name of the device instance */ + struct HdfSRef ref; /* used for reference count */ + struct DListHead node; /* linked to the list of a manager */ + struct DListHead notifiers; /* list of notifier nodes */ + bool ready; /* indicates whether initialized */ + OsalSpinlock spin; /* for member protection */ + struct OsalSem released; /* for death notification */ +}; + +enum PlatformEventType { + PLAT_EVENT_DEAD = 0, /* a platform device going to die */ +}; + +struct PlatformNotifier { + void *data; /* private data u can take */ + /** + * @brief the event handle funciton of this notifier. + * + * make sure it can be called in irq context. + * + * @param device Indicates the pointer to the platform device. + * @param event Indicates the event type of this handling process. + * + * @since 1.0 + */ + void (*handle)(struct PlatformDevice *device, enum PlatformEventType event, void *data); +}; + +struct PlatformNotifierNode { + struct DListHead node; /* link to notfifier node list */ + struct PlatformNotifier *notifier; /* pointer to the notifier instance */ +}; + +/** + * @brief Initialize a platform device. + * + * Initialize members of a platform device. + * + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformDeviceInit(struct PlatformDevice *device); + +/** + * @brief Uninitialize a platform device. + * + * Uninitialize members of a platform device. + * + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformDeviceUninit(struct PlatformDevice *device); + +/** + * @brief Increase reference count for a platform device. + * + * @param device Indicates the pointer to the platform device. + * + * @return Returns the pointer to the paltform device on success; returns NULL otherwise. + * @since 1.0 + */ +struct PlatformDevice *PlatformDeviceGet(struct PlatformDevice *device); + +/** + * @brief Decrease reference count for a platform device. + * + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformDevicePut(struct PlatformDevice *device); + +/** + * @brief Register a notifier to a platform device. + * + * Subscribe the events of a platform device by registering a notfier. + * + * @param device Indicates the pointer to the platform device. + * @param notifier Indicates the pointer to the platform notifier. + * + * @return Returns 0 if the notifier registered successfully; returns a negative value otherwise. + * @since 1.0 + */ +int32_t PlatformDeviceRegNotifier(struct PlatformDevice *device, struct PlatformNotifier *notifier); + +/** + * @brief Unregister a notifier to a platform device. + * + * Unsubscribe the events of a platform device by unregistering the notfier. + * + * @param device Indicates the pointer to the platform device. + * @param notifier Indicates the pointer to the platform notifier. + * + * @since 1.0 + */ +void PlatformDeviceUnregNotifier(struct PlatformDevice *device, struct PlatformNotifier *notifier); + +/** + * @brief Unregister all notifiers to a platform device. + * + * Unsubscribe all the events of a platform device by clearing the notfiers. + * + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformDeviceClearNotifier(struct PlatformDevice *device); + +/** + * @brief Add a platform device by module type. + * + * do not call in irq context cause can sleep + * + * @param device Indicates the pointer to the platform device. + * + * @return Returns 0 if add successfully; returns a negative value otherwise. + * @since 1.0 + */ +int32_t PlatformDeviceAdd(struct PlatformDevice *device); + +/** + * @brief Remove a platform device by module type. + * + * do not call in irq context cause can sleep + * + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformDeviceDel(struct PlatformDevice *device); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_DEVICE_H */ diff --git a/support/platform/include/common/platform_errno.h b/support/platform/include/common/platform_errno.h new file mode 100644 index 00000000..edfdbbe5 --- /dev/null +++ b/support/platform/include/common/platform_errno.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef PLATFORM_ERRNO_H +#define PLATFORM_ERRNO_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +enum PlatformErrno { +#define HDF_PLT_ERR_START HDF_BSP_ERR_START /**< Error number start of platform. */ +#define HDF_PLT_ERR_NUM(v) (HDF_PLT_ERR_START + (v)) + HDF_PLT_ERR_OS_API = HDF_ERR_BSP_PLT_API_ERR, + HDF_PLT_ERR_OPEN_DEV = HDF_PAL_ERR_DEV_CREATE, /**< Failed to open a device. */ + HDF_PLT_ERR_INNER = HDF_PAL_ERR_INNER, /**< Internal error of platform framework. */ + + HDF_PLT_ERR_NO_DEV = HDF_PLT_ERR_NUM(-5), /**< There is no device present. */ + HDF_PLT_ERR_DEV_TYPE = HDF_PLT_ERR_NUM(-6), /**< invalid device type */ + HDF_PLT_ERR_DEV_GET = HDF_PLT_ERR_NUM(-7), /**< err on device get */ + HDF_PLT_ERR_DEV_ADD = HDF_PLT_ERR_NUM(-8), /**< err on device add */ + HDF_PLT_ERR_DEV_FULL = HDF_PLT_ERR_NUM(-9), /**< id number conflict */ + HDF_PLT_ERR_ID_REPEAT = HDF_PLT_ERR_NUM(-10), /**< id number conflict */ +#define HDF_MMC_ERR_START (HDF_PLT_ERR_START - 50) /**< Error number start for mmc. */ +#define HDF_MMC_ERR_NUM(v) (HDF_MMC_ERR_START + (v)) + HDF_MMC_ERR_SWITCH_FAIL = HDF_MMC_ERR_NUM(-1), + HDF_MMC_ERR_OTHER_CMD_IS_RUNNING = HDF_MMC_ERR_NUM(-2), + HDF_MMC_ERR_ILLEGAL_SEQ = HDF_MMC_ERR_NUM(-3), +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_ERRNO_H */ diff --git a/support/platform/include/common/platform_manager.h b/support/platform/include/common/platform_manager.h new file mode 100644 index 00000000..8bb1c25d --- /dev/null +++ b/support/platform/include/common/platform_manager.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef PLATFORM_MANAGER_H +#define PLATFORM_MANAGER_H + +#include "hdf_base.h" +#include "hdf_dlist.h" +#include "osal_spinlock.h" +#include "platform_device.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct PlatformManager { + const char *name; /* name of the manager */ + struct DListHead devices; /* list to keep all it's device instances */ + OsalSpinlock spin; /* for member protection */ +}; + +/** + * @brief Create a platform manager. + * + * Create a platform manager with member initialized. + * + * @param name Indicates the name of the manager. + * + * @return Returns the pointer to the paltform manager on success; returns NULL otherwise. + * @since 1.0 + */ +struct PlatformManager *PlatformManagerCreate(const char *name); + +/** + * @brief Get a platform manager by module type. + * + * @param module Indicates the module type of the manager. + * + * @return Returns the pointer to the paltform manager on success; returns NULL otherwise. + * @since 1.0 + */ +struct PlatformManager *PlatformManagerGet(enum PlatformModuleType module); + +/** + * @brief Add a platform device to a platform manager. + * + * Add a platform device to make it managed by platform core. + * + * @param manager Indicates the pointer to the platform manager. + * @param device Indicates the pointer to the platform device. + * + * @return Returns 0 if the devcie added successfully; returns a negative value otherwise. + * @since 1.0 + */ +int32_t PlatformManagerAddDevice(struct PlatformManager *manager, struct PlatformDevice *device); + +/** + * @brief Remove a platform device from a platform manager. + * + * Remove a platform device to make it away from management of platform core. + * + * @param manager Indicates the pointer to the platform manager. + * @param device Indicates the pointer to the platform device. + * + * @since 1.0 + */ +void PlatformManagerDelDevice(struct PlatformManager *manager, struct PlatformDevice *device); + +/** + * @brief Find a particular device from the manager. + * + * Locate a particular device from the manager by a matching function, witch will be called for + * each device, untill it returns true indicatting a device is "found". + * The device found will be returned with reference count increased. + * + * @param manager Indicates the pointer to the platform manager. + * @param data Indicates the pointer to the data passed to match function. + * @param match Indicates the pointer to the match function. + * + * @return Returns the pointer to the paltform device on success; returns NULL otherwise. + * @since 1.0 + */ +struct PlatformDevice *PlatformManagerFindDevice(struct PlatformManager *manager, void *data, + bool (*match)(struct PlatformDevice *pdevice, void *data)); + +/** + * @brief Get a platform device from the manager by magic. + * + * The device got will be returned with reference count increased. + * + * @param manager Indicates the pointer to the platform manager. + * @param magic Indicates the magic number of the target platform device. + * + * @return Returns the pointer to the paltform device on success; returns NULL otherwise. + * @since 1.0 + */ +struct PlatformDevice *PlatformManagerGetDeviceByMagic(struct PlatformManager *manager, uint32_t magic); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_MANAGER_H */ diff --git a/support/platform/include/common/platform_queue.h b/support/platform/include/common/platform_queue.h new file mode 100644 index 00000000..00b6839e --- /dev/null +++ b/support/platform/include/common/platform_queue.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef PLATFORM_QUEUE_H +#define PLATFORM_QUEUE_H + +#include "hdf_dlist.h" +#include "osal_thread.h" +#include "osal_sem.h" +#include "osal_spinlock.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct PlatformMsg; +struct PlatformQueue; + +struct PlatformMsg { + struct DListHead node; + struct OsalSem sem; + int32_t code; + int32_t error; + bool block; /* whether need to block thread */ + void *data; +}; + +int32_t PlatformMsgWait(struct PlatformMsg *msg); +typedef int32_t (*PlatformMsgHandle)(struct PlatformQueue *queue, struct PlatformMsg *msg); + +struct PlatformQueue { + const char *name; + OsalSpinlock spin; + struct OsalSem sem; + struct DListHead msgs; + struct OsalThread thread; /* the worker thread of this queue */ + PlatformMsgHandle handle; + void *data; +}; + +void PlatformQueueAddMsg(struct PlatformQueue *queue, struct PlatformMsg *msg); +struct PlatformQueue *PlatformQueueCreate(PlatformMsgHandle handle, const char *name, void *data); +void PlatformQueueDestroy(struct PlatformQueue *queue); +int32_t PlatformQueueStart(struct PlatformQueue *queue); +int32_t PlatformQueueSuspend(struct PlatformQueue *queue); +int32_t PlatformQueueResume(struct PlatformQueue *queue); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PLATFORM_QUEUE_H */ diff --git a/support/platform/include/emmc_core.h b/support/platform/include/emmc_core.h index 55f835f2..d6730afb 100644 --- a/support/platform/include/emmc_core.h +++ b/support/platform/include/emmc_core.h @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#ifndef emmc_CORE_H -#define emmc_CORE_H +#ifndef EMMC_CORE_H +#define EMMC_CORE_H #include "emmc_if.h" #include "hdf_base.h" @@ -39,7 +39,7 @@ struct EmmcCntlr { /** * @brief emmc host device operations. - * These methods need to be filled up by specific paltform. + * These methods need to be filled up by specific platform. */ struct EmmcMethod { int32_t (*getCid)(struct EmmcCntlr *, uint8_t *, uint32_t); diff --git a/support/platform/include/i2c_core.h b/support/platform/include/i2c_core.h index 81208c18..0e5d513a 100644 --- a/support/platform/include/i2c_core.h +++ b/support/platform/include/i2c_core.h @@ -11,7 +11,6 @@ #include "hdf_base.h" #include "i2c_if.h" -#include "osal_atomic.h" #include "osal_mutex.h" #ifdef __cplusplus @@ -28,7 +27,6 @@ struct I2cLockMethod; struct I2cCntlr { struct OsalMutex lock; - OsalAtomic atom; void *owner; int16_t busId; void *priv; diff --git a/support/platform/include/mmc/mmc_block.h b/support/platform/include/mmc/mmc_block.h new file mode 100644 index 00000000..bec2bb78 --- /dev/null +++ b/support/platform/include/mmc/mmc_block.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_BLOCK_H +#define MMC_BLOCK_H + +#include "mmc_corex.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int32_t MmcBlockAdd(struct MmcDevice *mmc); +void MmcBlockDel(struct MmcDevice *mmc); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_BLOCK_H */ diff --git a/support/platform/include/mmc/mmc_caps.h b/support/platform/include/mmc/mmc_caps.h new file mode 100644 index 00000000..7f90d063 --- /dev/null +++ b/support/platform/include/mmc/mmc_caps.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_CAPS_H +#define MMC_CAPS_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +enum MmcVolt { VOLT_3V3 = 0, VOLT_1V8, VOLT_1V2 }; + +enum MmcPowerMode { MMC_POWER_MODE_POWER_OFF = 0, MMC_POWER_MODE_POWER_UP, MMC_POWER_MODE_POWER_ON }; + +enum MmcBusWidth { BUS_WIDTH1 = 0, BUS_WIDTH4 = 2, BUS_WIDTH8 = 3 }; + +enum MmcBusTiming { + BUS_TIMING_MMC_DS = 0, + BUS_TIMING_MMC_HS, + BUS_TIMING_SD_HS, + BUS_TIMING_UHS_SDR12, + BUS_TIMING_UHS_SDR25, + BUS_TIMING_UHS_SDR50, + BUS_TIMING_UHS_SDR104, + BUS_TIMING_UHS_DDR50, + BUS_TIMING_UHS_DDR52, + BUS_TIMING_MMC_HS200, /* for emmc */ + BUS_TIMING_MMC_HS400, /* for emmc */ +}; + +union MmcCaps { + uint32_t capsData; + struct CapsBitsData { + uint32_t cap4Bit : 1; /* bit:0 support 4 bit transfer */ + uint32_t cap8Bit : 1; /* bit:1 support 8 bit transfer */ + uint32_t highSpeed : 1; /* bit:2 support high-speed timing */ + uint32_t sdioIrq : 1; /* bit:3 signal pending SDIO irqs */ + uint32_t onlySpi : 1; /* bit:4 only support spi protocols */ + uint32_t needPoll : 1; /* bit:5 need polling for card-detection */ + uint32_t nonremovable : 1; /* bit:6 Nonremoveable eg. eMMC */ + uint32_t waitWhileBusy : 1; /* bit:7 waits while card is busy */ + uint32_t erase : 1; /* bit:8 allow erase */ + uint32_t ddr1v8 : 1; /* bit:9 support ddr mode at 1.8V */ + uint32_t ddr1v2 : 1; /* bit:10 support ddr mode at 1.2V */ + uint32_t powerOffCard : 1; /* bit:11 support power off after boot */ + uint32_t busWidthTest : 1; /* bit:12 CMD14/CMD19 bus width ok */ + uint32_t uhsSdr12 : 1; /* bit:13 support UHS SDR12 mode */ + uint32_t uhsSdr25 : 1; /* bit:14 support UHS SDR25 mode */ + uint32_t uhsSdr50 : 1; /* bit:15 support UHS SDR50 mode */ + uint32_t uhsSdr104 : 1; /* bit:16 support UHS SDR104 mode */ + uint32_t uhsDdr50 : 1; /* bit:17 support UHS DDR50 mode */ + uint32_t xpc330 : 1; /* bit:18 support >150mA current at 3.3V */ + uint32_t xpc300 : 1; /* bit:19 support >150mA current at 3.0V */ + uint32_t xpc180 : 1; /* bit:20 support >150mA current at 1.8V */ + uint32_t driverTypeA : 1; /* bit:21 support driver type A */ + uint32_t driverTypeC : 1; /* bit:22 support driver type C */ + uint32_t driverTypeD : 1; /* bit:23 support driver type D */ + uint32_t maxCurrentLimit200 : 1; /* bit:24 max current limit 200mA */ + uint32_t maxCurrentLimit400 : 1; /* bit:25 max current limit 400mA */ + uint32_t maxCurrentLimit600 : 1; /* bit:26 max current limit 600mA */ + uint32_t maxCurrentLimit800 : 1; /* bit:27 max current limit 800mA */ + uint32_t cmd23 : 1; /* bit:28 support CMD23 */ + uint32_t hardwareReset : 1; /* bit:29 support hardware reset */ + uint32_t sdSupportProtocol3 : 1; /* bit:30 SD support Protocol 3.0 */ + uint32_t cmdStop : 1; /* bit:31 support cmd stop */ + } bits; +}; + +union MmcCaps2 { + uint32_t caps2Data; + struct Caps2BitsData { + uint32_t bootPartNoAcc : 1; /* bit:0 boot partition no access */ + uint32_t cacheCtrl : 1; /* bit:1 allow cache control */ + uint32_t poweroffNotify : 1; /* bit:2 support notify power off */ + uint32_t noMultiRead : 1; /* bit:3 not support multiblock read */ + uint32_t noSleepCmd : 1; /* bit:4 not support sleep command */ + uint32_t hs200Sdr1v8 : 1; /* bit:5 support hs200 sdr 1.8V */ + uint32_t hs200Sdr1v2 : 1; /* bit:6 support sdr hs200 1.2V */ + uint32_t brokenVoltage : 1; /* bit:7 use broken voltage */ + uint32_t detectNoErr : 1; /* bit:8 I/O err check card removal */ + uint32_t hcEraseSize : 1; /* bit:9 High-capacity erase size */ + uint32_t hs400Support1v8 : 1; /* bit:10 support hs400 1.8V */ + uint32_t hs400Support1v2 : 1; /* bit:11 support hs400 1.2V */ + uint32_t hs400EnhancedStrobe : 1; /* bit:12 support hs400 enhanced strobe */ + uint32_t reserved : 18; /* bits:13~31, reserved */ + } bits; +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* _MMC_CAPS_H */ diff --git a/support/platform/include/mmc/mmc_corex.h b/support/platform/include/mmc/mmc_corex.h new file mode 100644 index 00000000..6cdd2d0a --- /dev/null +++ b/support/platform/include/mmc/mmc_corex.h @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_CORE_H +#define MMC_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "mmc_caps.h" +#include "mmc_protocol.h" +#include "osal_mem.h" +#include "osal_mutex.h" +#include "osal_time.h" +#include "platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define MMC_CNTLR_NR_MAX 3 +#define MMC_DEV_NR_MAX 3 +#define MMC_SEC_SIZE 512 + +#define MMC_MIN(x, y) (((x) < (y)) ? (x) : (y)) +#define MMC_MAX(x, y) (((x) < (y)) ? (y) : (x)) + +struct MmcCntlr; +struct MmcCntlrOps; +struct MmcDevice; +struct MmcMsg; +struct MmcData; +struct MmcCmd; +enum MmcMsgCode; +enum MmcCmdCode; +union MmcDevState; + +enum MmcDevType { + MMC_DEV_EMMC = 0, + MMC_DEV_SD, + MMC_DEV_SDIO, + MMC_DEV_COMBO, + MMC_DEV_INVALID +}; + +struct MmcCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *hdfDevObj; + struct PlatformDevice device; + struct OsalMutex mutex; + struct OsalSem released; + uint32_t devType; + struct MmcDevice *curDev; + struct MmcCntlrOps *ops; + struct PlatformQueue *msgQueue; + uint16_t index; + uint16_t voltDef; + uint32_t vddBit; + uint32_t freqMin; + uint32_t freqMax; + uint32_t freqDef; + union MmcOcr ocrDef; + union MmcCaps caps; + union MmcCaps2 caps2; + uint32_t maxBlkNum; + uint32_t maxBlkSize; + uint32_t maxReqSize; + bool devPluged; + bool detecting; + void *priv; +}; + +struct MmcCntlrOps { + int32_t (*request)(struct MmcCntlr *cntlr, struct MmcCmd *cmd); + int32_t (*setClock)(struct MmcCntlr *cntlr, uint32_t clock); + int32_t (*setPowerMode)(struct MmcCntlr *cntlr, enum MmcPowerMode mode); + int32_t (*setBusWidth)(struct MmcCntlr *cntlr, enum MmcBusWidth width); + int32_t (*setBusTiming)(struct MmcCntlr *cntlr, enum MmcBusTiming timing); + int32_t (*setSdioIrq)(struct MmcCntlr *cntlr, bool enable); + int32_t (*hardwareReset)(struct MmcCntlr *cntlr); + int32_t (*systemInit)(struct MmcCntlr *cntlr); + int32_t (*setEnhanceSrobe)(struct MmcCntlr *cntlr, bool enable); + int32_t (*switchVoltage)(struct MmcCntlr *cntlr, enum MmcVolt volt); + bool (*devReadOnly)(struct MmcCntlr *cntlr); + bool (*devPluged)(struct MmcCntlr *cntlr); + bool (*devBusy)(struct MmcCntlr *cntlr); + int32_t (*tune)(struct MmcCntlr *cntlr, uint32_t cmdCode); + int32_t (*rescanSdioDev)(struct MmcCntlr *cntlr); +}; + +/* controller management */ +int32_t MmcCntlrAdd(struct MmcCntlr *cntlr); +void MmcCntlrRemove(struct MmcCntlr *cntlr); +struct MmcDevice *MmcCntlrGetDevice(struct MmcCntlr *cntlr); + +static inline struct MmcCntlr *MmcCntlrGet(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL && PlatformDeviceGet(&cntlr->device) != NULL) { + return cntlr; + } + return NULL; +} + +static inline struct MmcCntlr *MmcCntlrGetByNr(uint16_t number) +{ + struct PlatformDevice *device = PlatformManagerGetDeviceByMagic(PlatformManagerGet(PLATFORM_MODULE_MMC), number); + + if (device == NULL) { + return NULL; + } + return CONTAINER_OF(device, struct MmcCntlr, device); +} + +static inline void MmcCntlrPut(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL) { + PlatformDevicePut(&cntlr->device); + } +} + +static inline bool MmcCntlrDevPresent(struct MmcCntlr *cntlr) +{ + return (cntlr != NULL && cntlr->curDev != NULL); +} + +static inline void MmcCntlrLock(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL) { + (void)OsalMutexLock(&cntlr->mutex); + } +} + +static inline void MmcCntlrUnlock(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL) { + (void)OsalMutexUnlock(&cntlr->mutex); + } +} + +/* controller common bussiness */ +int32_t MmcCntlrDoRequest(struct MmcCntlr *cntlr, struct MmcCmd *cmd); +int32_t MmcCntlrAddMsgToQueue(struct MmcCntlr *cntlr, struct MmcCmd *cmd, int32_t code, bool block); +int32_t MmcCntlrAddRequestMsgToQueue(struct MmcCntlr *cntlr, struct MmcCmd *cmd); +int32_t MmcCntlrAddDetectMsgToQueue(struct MmcCntlr *cntlr); +int32_t MmcCntlrAddPlugMsgToQueue(struct MmcCntlr *cntlr); +int32_t MmcCntlrAddSdioRescanMsgToQueue(struct MmcCntlr *cntlr); +int32_t MmcCntlrParse(struct MmcCntlr *cntlr, struct HdfDeviceObject *obj); +int32_t MmcCntlrCreatSdioIrqThread(struct MmcCntlr *cntlr); +void MmcCntlrDestroySdioIrqThread(struct MmcCntlr *cntlr); +void MmcCntlrNotifySdioIrqThread(struct MmcCntlr *cntlr); + +/* controller private bussiness */ +void MmcCntlrSetClock(struct MmcCntlr *cntlr, uint32_t clock); +void MmcCntlrSetBusWidth(struct MmcCntlr *cntlr, enum MmcBusWidth width); +void MmcCntlrSetBusTiming(struct MmcCntlr *cntlr, enum MmcBusTiming timing); +void MmcCntlrSetEnhanceSrobe(struct MmcCntlr *cntlr, bool enable); +int32_t MmcCntlrSwitchVoltage(struct MmcCntlr *cntlr, enum MmcVolt voltage); +bool MmcCntlrDevReadOnly(struct MmcCntlr *cntlr); +bool MmcCntlrDevBusy(struct MmcCntlr *cntlr); +bool MmcCntlrDevPluged(struct MmcCntlr *cntlr); +int32_t MmcCntlrTune(struct MmcCntlr *cntlr, uint32_t cmdCode); +void MmcCntlrSelectWorkVoltage(struct MmcCntlr *cntlr, union MmcOcr *ocr); +void MmcCntlrPowerUp(struct MmcCntlr *cntlr); +void MmcCntlrPowerOff(struct MmcCntlr *cntlr); +int32_t MmcCntlrAllocDev(struct MmcCntlr *cntlr, enum MmcDevType devType); +void MmcCntlrFreeDev(struct MmcCntlr *cntlr); +bool MmcCntlrSupportUhs(struct MmcCntlr *cntlr); +bool MmcCntlrSupportHighSpeed400EnhancedStrobe(struct MmcCntlr *cntlr); +bool MmcCntlrSupportHighSpeed400(struct MmcCntlr *cntlr); +bool MmcCntlrSupportHighSpeed200(struct MmcCntlr *cntlr); +bool MmcCntlrSdSupportCmd23(struct MmcCntlr *cntlr); +bool MmcCntlrEmmcSupportCmd23(struct MmcCntlr *cntlr); + +struct MmcDeviceWorkParam { + uint32_t clock; + enum MmcBusWidth width; + enum MmcBusTiming timing; +}; + +struct MmcRegister { + union MmcOcr ocr; + uint32_t rca; + uint32_t rawCid[CID_LEN]; + uint32_t rawCsd[CSD_LEN]; + struct MmcCid cid; + struct MmcCsd csd; +}; + +union MmcDevState { + uint32_t stateData; + struct StateBitsData { + uint32_t present : 1; + uint32_t readonly : 1; + uint32_t highSpeed : 1; + uint32_t blockAddr : 1; + uint32_t ddrMode : 1; + uint32_t highSpeedDdr : 1; + uint32_t uhs : 1; + uint32_t sdxc : 1; + uint32_t hs200 : 1; + uint32_t sleep : 1; + uint32_t removeable : 1; + uint32_t blkszForByteMode : 1; + uint32_t hs400 : 1; + uint32_t hs400es : 1; + uint32_t reserverd : 17; + } bits; +}; + +struct MmcDevice { + struct PlatformDevice device; + struct MmcCntlr *cntlr; + struct MmcRegister reg; + struct MmcDeviceWorkParam workPara; + union MmcDevState state; + enum MmcDevType type; + size_t secSize; // by bytes + size_t capacity; // by sectors + size_t eraseSize; // by sectors + struct StorageBlock *sb; + void *priv; +}; + +/* device management */ +int32_t MmcDeviceAdd(struct MmcDevice *mmc); +void MmcDeviceAddOps(struct MmcDevice *mmc, void *ops); +void MmcDeviceRemove(struct MmcDevice *mmc); +struct MmcDevice *MmcDeviceGet(struct MmcDevice *mmc); +void MmcDevicePut(struct MmcDevice *mmc); + +/* device business */ +ssize_t MmcDeviceRead(struct MmcDevice *mmc, uint8_t *buf, size_t startSec, size_t nSec); +ssize_t MmcDeviceWrite(struct MmcDevice *mmc, uint8_t *buf, size_t startSec, size_t nSec); +ssize_t MmcDeviceErase(struct MmcDevice *mmc, size_t startSec, size_t nSec); + +static inline bool MmcDeviceIsPresent(struct MmcDevice *mmc) +{ + return (mmc != NULL && mmc->state.bits.present); +} + +struct MmcCmd { + uint32_t cmdCode; + uint32_t argument; + uint32_t resp[MMC_CMD_RESP_SIZE]; + uint32_t respType; + int32_t returnError; + struct MmcData *data; +}; + +#define DATA_WRITE (0x1 << 0) +#define DATA_READ (0x1 << 1) +#define DATA_STREAM (0x1 << 2) +struct MmcData { + uint32_t blockSize; /* data block size, byte */ + uint32_t blockNum; + int32_t returnError; + uint8_t *dataBuffer; + void *scatter; + uint32_t scatterLen; + uint32_t dataFlags; + struct MmcCmd stopCmd; /* stop command */ + bool sendStopCmd; +}; + +enum MmcMsgCode { + MMC_MSG_REQUEST, + MMC_MSG_PLUG, + MMC_MSG_UNPLUG, + MMC_MSG_SDIO_RESCAN, +}; + +struct MmcMsg { + struct PlatformMsg msg; + struct MmcCmd *mmcCmd; +}; + +struct MmcRwData { + uint8_t *buf; + bool writeFlag; + size_t startSector; + size_t sectors; +}; + +int32_t MmcDoDetect(struct MmcCntlr *cntlr); +void MmcDeleteDev(struct MmcCntlr *cntlr); +int32_t MmcSendStatus(struct MmcCntlr *cntlr, uint32_t *status); +int32_t MmcStopTransmission(struct MmcCntlr *cntlr, bool writeFlag, uint32_t *stopStatus); +int32_t MmcSendTuning(struct MmcCntlr *cntlr, uint32_t cmdCode, bool sendStop); +int32_t MmcSendErase(struct MmcCntlr *cntlr, uint32_t startSec, uint32_t nSec); +void MmcSetupReadWriteBlocksCmd(struct MmcDevice *mmc, struct MmcCmd *cmd, struct MmcRwData *info); +int32_t MmcSendReadWriteBlocks(struct MmcCntlr *cntlr, struct MmcRwData *info); +int32_t SdioReinit(struct MmcCntlr *cntlr); +int32_t SdioReadCccrIoEnable(struct MmcCntlr *cntlr, uint8_t *val); +int32_t SdioCccrIntEnable(struct MmcCntlr *cntlr); +int32_t SdioCccrIntDisable(struct MmcCntlr *cntlr); +int32_t SdioCccrIoEnable(struct MmcCntlr *cntlr); +int32_t SdioCccrIoDisable(struct MmcCntlr *cntlr); +int32_t SdioReadCccrIntPending(struct MmcCntlr *cntlr, uint8_t *val); +int32_t SdioReadCccrIoReady(struct MmcCntlr *cntlr, uint8_t *val); +int32_t SdioSetFbrIoBlockSize(struct MmcCntlr *cntlr, uint32_t blkSize); +int32_t SdioReadWriteByte(struct MmcCntlr *cntlr, bool writeFlag, + uint32_t funcNum, uint32_t addr, uint8_t *data); +int32_t SdioReadWriteBlock(struct MmcCntlr *cntlr, struct SdioRwBlockInfo *info); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_CORE_H */ diff --git a/support/platform/include/mmc/mmc_dispatch.h b/support/platform/include/mmc/mmc_dispatch.h new file mode 100644 index 00000000..51db247a --- /dev/null +++ b/support/platform/include/mmc/mmc_dispatch.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_DISPATCH_H +#define MMC_DISPATCH_H + +#ifndef __USER__ +#include "devsvc_manager_clnt.h" +#endif + +#ifdef __USER__ +#include "hdf_io_service_if.h" +#endif + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#ifndef __USER__ +int32_t MmcIoDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply); +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_DISPATCH_H */ diff --git a/support/platform/include/mmc/mmc_emmc.h b/support/platform/include/mmc/mmc_emmc.h new file mode 100644 index 00000000..dadfec8a --- /dev/null +++ b/support/platform/include/mmc/mmc_emmc.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_EMMC_H +#define MMC_EMMC_H + +#include "emmc_if.h" +#include "mmc_corex.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct EmmcRegister { + struct EmmcExtCsd extCsd; +}; + +struct EmmcDevice { + struct MmcDevice mmc; + struct EmmcDeviceOps *emmcOps; + struct EmmcRegister emmcReg; +}; + +struct EmmcDeviceOps { + int32_t (*getCid)(struct EmmcDevice *, uint8_t *, uint32_t); +}; + +int32_t EmmcDeviceGetCid(struct EmmcDevice *dev, uint8_t *cid, uint32_t len); +void EmmcDeviceAddOps(struct EmmcDevice *dev, void *ops); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_EMMC_H */ diff --git a/support/platform/include/mmc/mmc_protocol.h b/support/platform/include/mmc/mmc_protocol.h new file mode 100644 index 00000000..7bab66d5 --- /dev/null +++ b/support/platform/include/mmc/mmc_protocol.h @@ -0,0 +1,1191 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_PROTOCOL_H +#define MMC_PROTOCOL_H + +#include "hdf_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define CID_LEN 4 +#define CID_BITS 128 +#define CID_BYTES_LEN 16 +#define CID_PNM_LEN 8 +#define CSD_LEN 4 +#define CSD_BITS 128 +#define EXT_CSD_BYTES_LEN 512 +#define BITS_PER_BYTE 8 +#define SCR_LEN 2 +#define SCR_BYTES_LEN 8 +#define SCR_BITS 64 +#define DSR_BITS 16 +#define SSR_LEN 16 +#define SSR_BYTES_LEN 64 +#define SSR_BITS 512 + +/* The basic unit data transfer is a block whose maximum size is always 512 bytes. */ +#define BYTES_PER_BLOCK 512 +#define MMC_MAX_BLOCKSIZE_SHIFT 9 + +#define SDIO_BLOCK_TRANSFER_MAX_BLKNUM 511 + +/* mmc commands */ +enum MmcCmdCode { + GO_IDLE_STATE = 0, /* resets all cards to idle state */ + SEND_OP_COND = 1, /* + * asks all cards in idle state to send their operation conditions register contents + * in the response on the CMD line. + */ + ALL_SEND_CID = 2, /* asks all cards to send their CID numbers on the CMD line. */ + SET_RELATIVE_ADDR = 3, /* assigns relative address to the card. */ + SET_DSR = 4, /* programs the DSR of all cards. */ + SWITCH = 6, /* Switches the mode of operation of the selected card or modifies the EXT_CSD registers. */ + SELECT_CARD = 7, /* + * command toggles a card between the stand-by and transfer states or between the programming and + * disconnect states. In both cases the card is selected by its own relative address and gets + * deselected by any other address; address 0 deselects all. + */ + SEND_EXT_CSD = 8, /* The card sends its EXT_CSD register as a block of data. */ + SEND_CSD = 9, /* addressed card sends its card-specific data (CSD) on the CMD line. */ + SEND_CID = 10, /* addressed card sends its card identification (CID) on CMD the line. */ + READ_DAT_UNTIL_STOP = 11, /* + * reads data stream from the card, starting at the given address, + * until a STOP_TRANSMISSION follows. + */ + STOP_TRANSMISSION = 12, /* + * Terminates a read/write stream/multiple block operation. + * When CMD12 is used to terminate a read transaction the card will respond with R1. + * When it is used to stop a write transaction the card will respondwith R1b. + */ + SEND_STATUS = 13, /* addressed card sends its status register. */ + GO_INACTIVE_STATE = 15, /* + * sets the card to inactive state in order to protect the card stack against + * communication breakdowns. + */ + SET_BLOCKLEN = 16, /* + * sets the block length (in bytes) for all following block commands (read and write). + * Default block length is specified in the CSD. + */ + READ_SINGLE_BLOCK = 17, /* reads a block of the size selected by the SET_BLOCKLEN command. */ + READ_MULTIPLE_BLOCK = 18, /* + * continuously transfers data blocks from card to host until interrupted + * by a stop command or the requested number of data block transmitted. + */ + WRITE_DAT_UNTIL_STOP = 20, /* + * writes data stream from the host, starting at the given address, + * until a STOP_TRANSMISSION follows. + */ + SEND_TUNING_BLOCK_HS200 = 21, /* + * Dedicated for HS200 mode, used to optimize host sampling points. + * The host sends the CMD21 command, and the device sends the data block in tuning + * mode. The host collects data at different sampling points to find the best + * sampling point. + */ + SET_BLOCK_COUNT = 23, /* + * Defines the number of blocks which are going to be transferred in the immediately + * succeeding multiple block read or write command. + */ + WRITE_BLOCK = 24, /* writes a block of the size selected by the SET_BLOCKLEN command. */ + WRITE_MULTIPLE_BLOCK = 25, /* + * continuously writes blocks of data until a STOP_TRANSMISSION follows + * or the requested number of block received. + */ + PROGRAM_CID = 26, /* + * programming of the card identification register. This command shall be issued only once + * per card. The card contains hardware to prevent this operation after the first programming. + * Normally this command is reserved for the manufacturer. + */ + PROGRAM_CSD = 27, /* programming of the programmable bits of the CSD. */ + SET_WRITE_PROT = 28, /* + * if the card has write protection features, + * this command sets the write protection bit of the addressed group. + * The properties of write protection are coded in the card specific data (WP_GRP_SIZE). + */ + CLR_WRITE_PROT = 29, /* + * if the card provides write protection features, + * this command clears the write protection bit of the addressed group. + */ + SEND_WRITE_PROT = 30, /* + * if the card provides write protection features, + * this command asks the card to send the status of the write protection bits. + */ + ERASE_GROUP_START = 35, /* sets the address of the first erase group within a range to be selected for erase. */ + ERASE_GROUP_END = 36, /* + * sets the address of the last erase group within a continuous + * range to be selected for erase. + */ + MMC_ERASE = 38, /* erases all previously selected write blocks. */ + MMC_FAST_IO = 39, /* + * used to write and read 8 bit (register) data fields. The command addresses a card and + * a register and provides the data for writing if the write flag is set. The R4 response + * contains data read from the addressed register. This command accesses application + * dependent registers which are not defined in the MultiMediaCard standard. + */ + GO_IRQ_STATE = 40, /* Sets the system into interrupt mode. */ + LOCK_UNLOCK = 42, /* + * Used to set/reset the password or lock/ unlock the card. + * The size of the data block is set by the SET_BLOCK_LEN command. + */ + APP_CMD = 55, /* + * Indicates to the card that the next command is an application specific command + * rather than a standard command. + */ + GEN_CMD = 56, /* + * Used either to transfer a data block to the card or to get a data block from the card + * for general purpose / application specific commands. + * The size of the data block shall be set by the SET_BLOCK_LEN command. + */ +}; + +#define MMC_CARD_BUSY_STATUS 0x80000000 /* Card Power up status bit */ + +/* OCR bit definitions */ +enum MmcOcrBitsMark { + MMC_OCR_1V65_1V95 = 0x00000080, /* VDD 1.65V ~ 1.95V */ + MMC_OCR_2V0_2V1 = 0x00000100, /* VDD 2.0V ~ 2.1V */ + MMC_OCR_2V1_2V2 = 0x00000200, /* VDD 2.1V ~ 2.2V */ + MMC_OCR_2V2_2V3 = 0x00000400, /* VDD 2.2V ~ 2.3V */ + MMC_OCR_2V3_2V4 = 0x00000800, /* VDD 2.3V ~ 2.4V */ + MMC_OCR_2V4_2V5 = 0x00001000, /* VDD 2.4V ~ 2.5V */ + MMC_OCR_2V5_2V6 = 0x00002000, /* VDD 2.5V ~ 2.6V */ + MMC_OCR_2V6_2V7 = 0x00004000, /* VDD 2.6V ~ 2.7V */ + MMC_OCR_2V7_2V8 = 0x00008000, /* VDD 2.7V ~ 2.8V */ + MMC_OCR_2V8_2V9 = 0x00010000, /* VDD 2.8V ~ 2.9V */ + MMC_OCR_2V9_3V0 = 0x00020000, /* VDD 2.9V ~ 3.0V */ + MMC_OCR_3V0_3V1 = 0x00040000, /* VDD 3.0V ~ 3.1V */ + MMC_OCR_3V1_3V2 = 0x00080000, /* VDD 3.1V ~ 3.2V */ + MMC_OCR_3V2_3V3 = 0x00100000, /* VDD 3.2V ~ 3.3V */ + MMC_OCR_3V3_3V4 = 0x00200000, /* VDD 3.3V ~ 3.4V */ + MMC_OCR_3V4_3V5 = 0x00400000, /* VDD 3.4V ~ 3.5V */ + MMC_OCR_3V5_3V6 = 0x00800000, /* VDD 3.5V ~ 3.6V */ +}; + +/* ocr register describe */ +union MmcOcr { + uint32_t ocrData; + struct OcrBits { + uint32_t reserved : 7; + uint32_t vdd1v65To1v95 : 1; /* bit:7 voltage 1.65 ~ 1.95 */ + uint32_t vdd2v0To2v1 : 1; /* bit:8 voltage 2.0 ~ 2.1 */ + uint32_t vdd2v1To2v2 : 1; /* bit:9 voltage 2.1 ~ 2.2 */ + uint32_t vdd2v2To2v3 : 1; /* bit:10 voltage 2.2 ~ 2.3 */ + uint32_t vdd2v3To2v4 : 1; /* bit:11 voltage 2.3 ~ 2.4 */ + uint32_t vdd2v4To2v5 : 1; /* bit:12 voltage 2.4 ~ 2.5 */ + uint32_t vdd2v5To2v6 : 1; /* bit:13 voltage 2.5 ~ 2.6 */ + uint32_t vdd2v6To2v7 : 1; /* bit:14 voltage 2.6 ~ 2.7 */ + uint32_t vdd2v7To2v8 : 1; /* bit:15 voltage 2.7 ~ 2.8 */ + uint32_t vdd2v8To2v9 : 1; /* bit:16 voltage 2.8 ~ 2.9 */ + uint32_t vdd2v9To3v0 : 1; /* bit:17 voltage 2.9 ~ 3.0 */ + uint32_t vdd3v0To3v1 : 1; /* bit:18 voltage 3.0 ~ 3.1 */ + uint32_t vdd3v1To3v2 : 1; /* bit:19 voltage 3.1 ~ 3.2 */ + uint32_t vdd3v2To3v3 : 1; /* bit:20 voltage 3.2 ~ 3.3 */ + uint32_t vdd3v3To3v4 : 1; /* bit:21 voltage 3.3 ~ 3.4 */ + uint32_t vdd3v4To3v5 : 1; /* bit:22 voltage 3.4 ~ 3.5 */ + uint32_t vdd3v5To3v6 : 1; /* bit:23 voltage 3.5 ~ 3.6 */ + uint32_t s18r : 1; /* bit:24 switch to 1.8v accepted */ + uint32_t reserved2 : 2; + uint32_t sdioMemoryPreset : 1; /* bit:27 sdio memory present */ + uint32_t sdXpc : 1; /* bit:28 XPC for ACMD41 */ + uint32_t sdUhsII : 1; /* bit:29 UHSII for resp of ACMD41 */ + uint32_t hcs : 1; /* bit:30 support high capacity */ + uint32_t busy : 1; /* bit:31 This bit is set to LOW if the card has not finished the power up routine */ + } bits; +}; + +/* SEND_STATUS rsp, card status bits */ +enum MmcRspCardStatus { + OUT_OF_RANGE = (1 << 31), /* The command's argument was out of the allowed range for this card. */ + ADDRESS_ERROR = (1 << 30), /* A misaligned address which did not match the block length was used in the command. */ + BLOCK_LEN_ERROR = (1 << 29), /* The transferred block length is not allowed for this card, + * or the number of transferred bytes does not match the block length. + */ + ERASE_SEQ_ERROR = (1 << 28), /* An error in the sequence of erase commands occurred. */ + ERASE_PARAM = (1 << 27), /* An invalid selection of erase groups for erase occurred. */ + WP_VIOLATION = (1 << 26), /* Attempt to program a write protected block. */ + CARD_IS_LOCKED = (1 << 25), /* When set, signals that the card is locked by the host. */ + LOCK_UNLOCK_FAILED = (1 << 24), /* Set when a sequence or password error has been detected in lock/unlock card + * command or if there was an attempt to access a locked card. + */ + COM_CRC_ERROR = (1 << 23), /* The CRC check of the previous command failed. */ + ILLEGAL_COMMAND = (1 << 22), /* Command not legal for the card state. */ + CARD_ECC_FAILED = (1 << 21), /* Card internal ECC was applied but failed to correct the data. */ + CC_ERROR = (1 << 20), /* Internal card controller error. */ + GENERAL_ERROR = (1 << 19), /* A general or an unknown error occurred during the operation. */ + UNDERRUN = (1 << 18), /* The card could not sustain data transfer in stream read mode. */ + OVERRUN = (1 << 17), /* The card could not sustain data programming in stream write mode. */ + CID_CSD_OVERWRITE = (1 << 16), /* can be either one of the following errors: + * - The CID register has been already written and can not be overwritten + * - The read only section of the CSD does not match the card content. + * - An attempt to reverse the copy (set as original) or permanent WP (unprotected) + * bits was made. + */ + WP_ERASE_SKIP = (1 << 15), /* Only partial address space was erased due to existing write protected blocks. */ + CARD_ECC_DISABLED = (1 << 14), /* The command has been executed without using the internal ECC. */ + ERASE_RESET = (1 << 13), /* An erase sequence was cleared before executing because an out of erase sequence + * command was received. + */ + READY_FOR_DATA = (1 << 8), /* corresponds to buffer empty signalling on the bus. */ + SWITCH_ERROR = (1 << 7), /* If set, the card did not switch to the expected mode as requested by + * the SWITCH command. + */ + URGENT_BKOPS = (1 << 6), /* If set, device needs to perform background operations urgently. + * Host can check EXT_CSD field BKOPS_STATUS for the detailed level. + */ + IS_APP_CMD = (1 << 5), /* The card will expect ACMD, or indication that the command has been + * interpreted as ACMD. + */ +}; + +/* + * The state of the card when receiving the command. If the command execution causes a + * state change, it will be visible to the host in the response to the next command. + * The four bits([12:9]) are interpreted as a binary coded number between 0 and 15. + */ +#define MMC_CARD_CURRENT_STATE(x) ((x & 0x00001E00) >> 9) /* sx, b (4 bits) */ +enum MmcCardCurrentState { + STATE_IDLE = 0, + STATE_READY = 1, + STATE_IDENT = 2, + STATE_STBY = 3, + STATE_TRAN = 4, + STATE_DATA = 5, + STATE_RCV = 6, + STATE_PRG = 7, + STATE_DIS = 8, +}; + +/* addressed (point-to-point) commands (ac) sent on CMD line, response on CMD line. */ +#define MMC_CMD_TYPE_AC (0x0 << 5) + +/* + * addressed (point-to-point) data transfer commands (adtc) sent on CMD line, response on CMD line, + * data transfer on DAT line. + */ +#define MMC_CMD_TYPE_ADTC (0x1 << 5) + +/* broadcast commands (bc) sent on CMD line, no response. */ +#define MMC_CMD_TYPE_BC (0x2 << 5) + +/* broadcast commands with response (bcr) sent on CMD line, response (all cards simultaneously) on CMD line. */ +#define MMC_CMD_TYPE_BCR (0x3 << 5) + +#define MMC_CMD_RESP_SIZE 4 +/* cmd resp type */ +#define RESP_PRESENT (1 << 0) +#define RESP_136 (1 << 1) /* 136 bit response */ +#define RESP_CRC (1 << 2) /* expect valid crc */ +#define RESP_BUSY (1 << 3) /* card may send busy */ +#define RESP_CMDCODE (1 << 4) /* response contains opcode */ + +#define MMC_RESP_NONE 0 +#define MMC_RESP_R1 (RESP_PRESENT | RESP_CMDCODE | RESP_CRC) +#define MMC_RESP_R1B (RESP_PRESENT | RESP_CMDCODE | RESP_BUSY | RESP_CRC) +#define MMC_RESP_R2 (RESP_PRESENT | RESP_136 | RESP_CRC) +#define MMC_RESP_R3 (RESP_PRESENT) +#define MMC_RESP_R4 (RESP_PRESENT) +#define MMC_RESP_R5 (RESP_PRESENT | RESP_CMDCODE | RESP_CRC) +#define MMC_RESP_R6 (RESP_PRESENT | RESP_CMDCODE | RESP_CRC) +#define MMC_RESP_R7 (RESP_PRESENT | RESP_CMDCODE | RESP_CRC) + +#define MMC_RESP_TYPE(cmd) ((cmd)->respType & (RESP_PRESENT | RESP_136 | RESP_CRC | RESP_BUSY | RESP_CMDCODE)) + +#define MMC_RESP_SPI_S1 (1 << 7) +#define MMC_RESP_SPI_S2 (1 << 8) +#define MMC_RESP_SPI_B4 (1 << 9) +#define MMC_RESP_SPI_BUSY (1 << 10) + +#define MMC_RESP_SPI_R1 (MMC_RESP_SPI_S1) +#define MMC_RESP_SPI_R1B (MMC_RESP_SPI_S1 | MMC_RESP_SPI_BUSY) +#define MMC_RESP_SPI_R2 (MMC_RESP_SPI_S1 | MMC_RESP_SPI_S2) +#define MMC_RESP_SPI_R3 (MMC_RESP_SPI_S1 | MMC_RESP_SPI_B4) +#define MMC_RESP_SPI_R4 (MMC_RESP_SPI_S1 | MMC_RESP_SPI_B4) +#define MMC_RESP_SPI_R5 (MMC_RESP_SPI_S1 | MMC_RESP_SPI_S2) +#define MMC_RESP_SPI_R7 (MMC_RESP_SPI_S1 | MMC_RESP_SPI_B4) + +enum MmcCsdStructure { + MMC_CSD_STRUCTURE_VER_1_0 = 0, + MMC_CSD_STRUCTURE_VER_1_1 = 1, + MMC_CSD_STRUCTURE_VER_1_2 = 2, /* Specification Version 4.1-4.2-4.3 */ + MMC_CSD_STRUCTURE_VER_OTHER = 3, /* Version is coded int the CSD_STRUCTURE byte in the EXT_CSD register. */ +}; + +enum MmcCsdSpecVersion { + MMC_CSD_SPEC_VER_0 = 0, + MMC_CSD_SPEC_VER_1 = 1, + MMC_CSD_SPEC_VER_2 = 2, + MMC_CSD_SPEC_VER_3 = 3, + MMC_CSD_SPEC_VER_4 = 4, +}; + +enum MmcCsdCardCmdClass { + MMC_CSD_CCC_BASIC = (1 << 0), + MMC_CSD_CCC_BLOCK_READ = (1 << 2), + MMC_CSD_CCC_BLOCK_WRITE = (1 << 4), + MMC_CSD_CCC_ERASE = (1 << 5), + MMC_CSD_CCC_WRITE_PROT = (1 << 6), + MMC_CSD_CCC_LOCK_CARD = (1 << 7), + MMC_CSD_CCC_APP_SPEC = (1 << 8), + MMC_CSD_CCC_IO_MODE = (1 << 9), + MMC_CSD_CCC_SWITCH = (1 << 10), +}; + +enum MmcBusMode { + MMC_BUS_MODE_NULL = 0, + MMC_1_2V_DDR_MODE = 1, + MMC_1_8V_DDR_MODE = 2, + MMC_1_2V_SDR_MODE = 3, + MMC_1_8V_SDR_MODE = 4, +}; + +/* CID register define */ +struct MmcCid { + uint32_t mid; /* Manufacturer ID */ + char pnm[CID_PNM_LEN]; /* Product name */ + uint32_t psn; /* Product serial number */ + uint16_t oid; /* OEM/Application ID */ + uint16_t year; /* Manufacturing date: The y field */ + uint8_t month; /* Manufacturing date: The m field */ + /* + * The product revision is composed of two Binary Coded Decimal (BCD) digits, four bits each, + * representing an "n.m" revision number. + */ + uint8_t hwPrv; /* Product revision: n */ + uint8_t fwPrv; /* Product revision: m */ +}; + +/* CSD register define */ +struct MmcCsd { + uint8_t structure; /* CSD_STRUCTURE: [127:126] */ + uint8_t specVers; /* emmc-->SPEC_VERS: [125:122] */ + uint16_t ccc; /* card command classes: [95:84] */ + uint16_t taccClks; /* data read access-time-2 in CLK(NSAC)[111:104]: The unit for NSAC is 100 clock cycles. */ + uint32_t taccNs; /* data read access-time-1(TAAC)[119:112]: time unit[2:0] * time value[6:3] */ + uint32_t cSize; /* device size(C_SIZE): [73:62] */ + uint32_t r2wFactor; /* write speed factor(R2W_FACTOR): [28:26] */ + uint32_t maxDtr; /* max data transfer rate[103:96]: transfer rate unit[2:0] * time value[6:3] */ + uint32_t eraseSize; /* erase sector size: [45:39], emmc and sd are different. */ + uint32_t readBlkLen; /* max read data block length(READ_BL_LEN): [83:80] */ + uint32_t writeBlkLen; /* max write data block length(WRITE_BL_LEN): [25:22] */ + uint32_t capacity; /* see CSD Field C_SIZE. */ + uint32_t rdPartial : 1, /* partial blocks for read allowed: [79] */ + rdMisalign : 1, /* read block misalignment: [77] */ + wrPartial : 1, /* partial blocks for write allowed: [21] */ + wrMisalign : 1; /* write block misalignment: [78] */ +}; + +/* Emmc Extended CSD fields */ +enum EmmcExtendedCsdField { + EMMC_EXT_CSD_ENH_START_ADDR = 136, /* R/W, 4 bytes */ + EMMC_EXT_CSD_ENH_SIZE_MULT = 140, /* R/W, 3 bytes */ + EMMC_EXT_CSD_GP_SIZE_MULT = 143, /* R/W, 12 bytes */ + EMMC_EXT_CSD_PARTITIONS_ATTRIBUTE = 156, /* R/W */ + EMMC_EXT_CSD_PARTITIONING_SUPPORT = 160, /* RO */ + EMMC_EXT_CSD_HPI_MGMT = 161, /* R/W */ + EMMC_EXT_CSD_RST_N_FUNCTION = 162, /* R/W */ + EMMC_EXT_CSD_WR_REL_PARAM = 166, /* RO */ + EMMC_EXT_CSD_BOOT_WP = 173, /* R/W */ + EMMC_EXT_CSD_ERASE_GROUP_DEF = 175, /* R/W */ + EMMC_EXT_CSD_PARTITION_CONFIG = 179, /* R/W */ + EMMC_EXT_CSD_ERASED_MEM_CONT = 181, /* RO */ + EMMC_EXT_CSD_BUS_WIDTH = 183, /* R/W */ + EMMC_EXT_CSD_STROBE_SUPPORT = 184, /* RO */ + EMMC_EXT_CSD_HS_TIMING = 185, /* R/W */ + EMMC_EXT_CSD_POWER_CLASS = 187, /* R/W */ + EMMC_EXT_CSD_REV = 192, /* RO */ + EMMC_EXT_CSD_STRUCTURE = 194, /* RO */ + EMMC_EXT_CSD_CARD_TYPE = 196, /* RO */ + EMMC_EXT_CSD_OUT_OF_INTERRUPT_TIME = 198, /* RO */ + EMMC_EXT_CSD_PARTITION_SWITCH_TIME = 199, /* RO */ + EMMC_EXT_CSD_PWR_CL_52_195 = 200, /* RO */ + EMMC_EXT_CSD_PWR_CL_26_195 = 201, /* RO */ + EMMC_EXT_CSD_PWR_CL_52_360 = 202, /* RO */ + EMMC_EXT_CSD_PWR_CL_26_360 = 203, /* RO */ + EMMC_EXT_CSD_SEC_CNT = 212, /* RO, 4 bytes */ + EMMC_EXT_CSD_S_A_TIMEOUT = 217, /* RO */ + EMMC_EXT_CSD_HC_WP_GRP_SIZE = 221, /* RO */ + EMMC_EXT_CSD_REL_WR_SEC_C = 222, /* RO */ + EMMC_EXT_CSD_ERASE_TIMEOUT_MULT = 223, /* RO */ + EMMC_EXT_CSD_HC_ERASE_GRP_SIZE = 224, /* RO */ + EMMC_EXT_CSD_BOOT_MULTI = 226, /* RO */ + EMMC_EXT_CSD_SEC_TRIM_MULT = 229, /* RO */ + EMMC_EXT_CSD_SEC_ERASE_MULT = 230, /* RO */ + EMMC_EXT_CSD_SEC_FEATURE_SUPPORT = 231, /* RO */ + EMMC_EXT_CSD_TRIM_MULT = 232, /* RO */ + EMMC_EXT_CSD_PWR_CL_200_195 = 236, /* RO */ + EMMC_EXT_CSD_PWR_CL_200_360 = 237, /* RO */ + EMMC_EXT_CSD_PWR_CL_DDR_52_195 = 238, /* RO */ + EMMC_EXT_CSD_PWR_CL_DDR_52_360 = 239, /* RO */ + EMMC_EXT_CSD_HPI_FEATURES = 503, /* RO */ +}; + +#define EMMC_EXT_CSD_SEC_CNT_BYTES 4 +#define EMMC_EXT_CSD_ENH_START_ADDR_BYTES 4 +#define EMMC_EXT_CSD_GP_SIZE_MULT_BYTES 12 +#define EMMC_EXT_CSD_ENH_SIZE_MULT_BYTES 3 + +/* PARTITION_CONFIG[179], bit2-bit0: PARTITION_ACCESS. */ +#define EMMC_EXT_CSD_PART_CONFIG_ACCESS_MASK (0x7) + +enum EmmcExtCsdStructure { + EMMC_EXT_CSD_STRUCTURE_VER_1_0 = 0, + EMMC_EXT_CSD_STRUCTURE_VER_1_1 = 1, + EMMC_EXT_CSD_STRUCTURE_VER_1_2 = 2, /* Specification Version 4.1-4.2-4.3-4.4 */ + EMMC_EXT_CSD_STRUCTURE_VER_OTHER = 3, /* Reserved for future use. */ +}; + +enum EmmcExtCsdRev { + EMMC_EXT_CSD_REV_1_0 = 0, /* Revision 1.0(for MMC v4.0) */ + EMMC_EXT_CSD_REV_1_1 = 1, /* Revision 1.1(for MMC v4.1) */ + EMMC_EXT_CSD_REV_1_2 = 2, /* Revision 1.2(for MMC v4.2) */ + EMMC_EXT_CSD_REV_1_3 = 3, /* Revision 1.3(for MMC v4.3) */ + EMMC_EXT_CSD_REV_1_4 = 4, /* Revision 1.4(Obsolete) */ + EMMC_EXT_CSD_REV_1_5 = 5, /* Revision 1.5(for MMC v4.4.1) */ + EMMC_EXT_CSD_REV_OTHER = 6, /* Reserved */ +}; + +#define EMMC_EXT_CSD_CARD_TYPE_MASK 0x3F /* Mask out reserved bits */ + +enum EmmcExtCsdCardType { + EMMC_EXT_CSD_CARD_TYPE_26 = 0x01, /* Card can run at 26MHz */ + EMMC_EXT_CSD_CARD_TYPE_52 = 0x02, /* Card can run at 52MHz */ + EMMC_EXT_CSD_CARD_TYPE_DDR_1_8V = 0x04, /* DDR mode @1.8V or 3V I/O, Card can run at 52MHz */ + EMMC_EXT_CSD_CARD_TYPE_DDR_1_2V = 0x08, /* DDR mode @1.2V I/O, Card can run at 52MHz */ + EMMC_EXT_CSD_CARD_TYPE_DDR_52 = 0x0C, /* EMMC_EXT_CSD_CARD_TYPE_DDR_1_8V | EMMC_EXT_CSD_CARD_TYPE_DDR_1_2V */ + EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V = 0x10, /* Card can run at 200MHz */ + EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL = 0x13, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_1_8V = 0x17, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_1_2V = 0x1B, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_52 = 0x1F, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V = 0x20, /* SDR mode @1.2V I/O, Card can run at 200MHz */ + EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL = 0x23, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_1_8V = 0x27, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_1_2V = 0x2B, + EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_52 = 0x2F, + EMMC_EXT_CSD_CARD_TYPE_SDR_200 = 0x30, + EMMC_EXT_CSD_CARD_TYPE_SDR_ALL = 0x33, + EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_1_8V = 0x37, + EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_1_2V = 0x3B, + EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_52 = 0x3F, + EMMC_EXT_CSD_CARD_TYPE_HS400_1_8V = 0x40, /* Card can run at 200MHz DDR, 1.8V */ + EMMC_EXT_CSD_CARD_TYPE_HS400_1_2V = 0x80, /* Card can run at 200MHz DDR, 1.2V */ + EMMC_EXT_CSD_CARD_TYPE_HS400 = 0xC0, + EMMC_EXT_CSD_CARD_TYPE_HS400ES = 0x100, /* Card can run at HS400ES */ +}; + +enum EmmcExtCsdHighSpeedMaxDtr { + EMMC_EXT_CSD_HIGH_SPEED_26 = 26000000, /* 26M */ + EMMC_EXT_CSD_HIGH_SPEED_52 = 52000000, /* 52M */ + EMMC_EXT_CSD_HIGH_SPEED_200 = 200000000, /* 200M */ +}; + +/* High Priority Interrupt */ +enum EmmcExtCsdHpiFeatures { + EMMC_EXT_CSD_HPI_SUPPORT = (1 << 0), /* HPI mechanism supported flag. */ + EMMC_EXT_CSD_HPI_IMPLEMENTATION = (1 << 1), /* 0x0 : HPI mechanism implementation based on CMD13. + * 0x1 : HPI mechanism implementation based on CMD12. + */ +}; + +/* EXT_CSD access modes */ +enum EmmcExtCsdAccessMode { + EMMC_EXT_CSD_CMD_SET = 0x00, /* The command set is changed according to the Cmd Set field of the argument. */ + EMMC_EXT_CSD_SET_BITS = 0x01, /* + * The bits in the pointed byte are set, + * according to the '1' bits in the Value field. + */ + EMMC_EXT_CSD_CLEAR_BITS = 0x02, /* + * The bits in the pointed byte are cleared, + * according to the '1' bits in the Value field. + */ + EMMC_EXT_CSD_WRITE_BYTE = 0x03, /* The Value field is written into the pointed byte. */ +}; + +enum EmmcExtCsdBusWidth { + EMMC_EXT_CSD_BUS_WIDTH_1 = 0, /* 1 bit mode */ + EMMC_EXT_CSD_BUS_WIDTH_4 = 1, /* 4 bit mode */ + EMMC_EXT_CSD_BUS_WIDTH_8 = 2, /* 8 bit mode */ + EMMC_EXT_CSD_DDR_BUS_WIDTH_4 = 5, /* 4 bit DDR mode */ + EMMC_EXT_CSD_DDR_BUS_WIDTH_8 = 6, /* 8 bit DDR mode */ + EMMC_EXT_CSD_BUS_WIDTH_STROBE = (1 << 7), /* Enhanced strobe mode */ +}; + +enum EmmcExtCsdBusTiming { + EMMC_EXT_CSD_BUS_TIMING_HS = 1, /* High speed */ + EMMC_EXT_CSD_BUS_TIMING_HS200 = 2, /* HS200 */ + EMMC_EXT_CSD_BUS_TIMING_HS400 = 3, /* HS400 */ + EMMC_EXT_CSD_BUS_DRV_STR_SHIFT = 4, /* Driver Strength shift */ +}; + +enum EmmcExtCsdCmdSet { + EMMC_EXT_CSD_CMD_SET_NORMAL = (1 << 0), + EMMC_EXT_CSD_CMD_SET_SECURE = (1 << 1), + EMMC_EXT_CSD_CMD_SET_CPSECURE = (1 << 2), +}; + +/* + * PWR_CL_ff_vvv, PWR_CL_DDR_ff_vvv. + * Bits [7:4] code the current consumption for the 8 bit bus configuration. + * Bits [3:0] code the current consumption for the 4 bit bus configuration. + */ +#define EMMC_EXT_CSD_PWR_CL_8BIT_MASK 0xF0 /* 8 bit PWR CLS */ +#define EMMC_EXT_CSD_PWR_CL_4BIT_MASK 0x0F /* 8 bit PWR CLS */ +#define EMMC_EXT_CSD_PWR_CL_8BIT_SHIFT 4 +#define EMMC_EXT_CSD_PWR_CL_4BIT_SHIFT 0 + +/* + * S_A_TIMEOUT [217]. + * Max register value defined is 0x17 which equals 838.86ms timeout. Values between 0x18 and 0xFF are reserved. + */ +#define MAX_S_A_TIMEOUT_VALUE 0x17 + +/* + * PARTITIONING_SUPPORT [160]. + * Bit[7:2]: Reserved. + * Bit[1]: ENH_ATTRIBUTE_EN. + * 0x0: Device can not have enhanced technological features in partitions and user data area. + * 0x1: Device can have enhanced technological features in partitions and user data area. + * Bit[0]: PARTITIONING_EN. + * 0x0: Device does not support partitioning features. + * 0x1: Device supports partitioning features. + * Partitioning feature is optional for device. + */ +#define PARTITIONING_SUPPORT_ENH_ATTRIBUTE_EN (1 << 1) +#define PARTITIONING_SUPPORT_PARTITIONING_EN (1 << 0) + +/* + * PARTITIONS_ATTRIBUTE [156]. + * Bit[7:5]: Reserved. + * Bit[4]: ENH_4. 0x0: Default; 0x1: Set Enhanced attribute in General Purpose partition 4. + * Bit[3]: ENH_3. 0x0: Default; 0x1: Set Enhanced attribute in General Purpose partition 3. + * Bit[2]: ENH_2. 0x0: Default; 0x1: Set Enhanced attribute in General Purpose partition 2. + * Bit[1]: ENH_1. 0x0: Default; 0x1: Set Enhanced attribute in General Purpose partition 1. + * Bit[0]: ENH_USR. 0x0: Default; 0x1: Set Enhanced attribute in User Data Area. + */ +#define PARTITIONS_ATTRIBUTE_ENH_4 (1 << 4) +#define PARTITIONS_ATTRIBUTE_ENH_3 (1 << 3) +#define PARTITIONS_ATTRIBUTE_ENH_2 (1 << 2) +#define PARTITIONS_ATTRIBUTE_ENH_1 (1 << 1) +#define PARTITIONS_ATTRIBUTE_ENH_USR (1 << 0) + +/* + * The Extended CSD register defines the card properties and selected modes. It is 512 bytes long. The most + * significant 320 bytes are the Properties segment, which defines the card capabilities and cannot be modified + * by the host. The lower 192 bytes are the Modes segment, which defines the configuration the card is + * working in. These modes can be changed by the host by means of the SWITCH command. + */ +struct EmmcExtCsd { + uint8_t rev; /* EXT_CSD_REV: [192] */ + uint8_t eraseGroupDef; /* ERASE_GROUP_DEF: [175] */ + uint8_t secFeatureSupport; /* SEC_FEATURE_SUPPORT: [231] */ + uint8_t relWrSecorCount; /* Reliable write sector count(REL_WR_SEC_C): [222] */ + uint8_t wrRelParam; /* Write reliability parameter register(WR_REL_PARAM): [166] */ + uint8_t partConfig; /* PARTITION_CONFIG: [179] */ + uint32_t partSwitchTime; /* PARTITION_SWITCH_TIME:[199], ms */ + uint32_t saTimeout; /* Sleep/Awake Timeout = 100ns * 2^S_A_timeout, S_A_TIMEOUT: [217], Units: 100ns */ + uint32_t hsMaxDtr; /* high-speed max data transfer rate, according to cardType */ + uint32_t sectors; /* SEC_COUNT: [215:212], 512B/secter */ + uint32_t cardType; /* see rawCardType */ + uint32_t hcEraseSize; /* High-capacity erase unit size: [224] */ + uint32_t hcEraseTimeout; /* High-capacity erase timeout: [223], ms */ + uint32_t secTrimMult; /* Secure TRIM Multiplier: [229] */ + uint32_t secEraseMult; /* Secure Erase Multiplier: [230] */ + uint32_t trimTimeout; /* TRIM Multiplier: [232], TRIM Timeout = 300ms * TRIM_MULT */ + bool enhAreaEnable; /* enable bit */ + uint64_t enhAreaOffset; /* Enhanced User Data Start Address(ENH_START_ADDR): [139:136] */ + uint32_t enhAreaSize; /* Enhanced User Data Area Size(ENH_SIZE_MULT): [142:140] */ + uint32_t cache_size; /* Units: KB */ + bool hpiEnable; /* HPI enable bit */ + bool hpi; /* HPI_FEATURES: [503], Bit[0]: HPI_SUPPORT */ + uint32_t hpiCmd; /* HPI_FEATURES: [503], Bit[1]: HPI_IMPLEMENTATION, cmd used as HPI */ + uint32_t dataSectorSize; /* 512 bytes or 4KB */ + uint32_t data_tag_unit_size; /* DATA TAG UNIT size */ + uint32_t boot_ro_lock; /* ro lock support */ + uint32_t bootSize; /* Boot Partition size = 128Kbytes * BOOT_SIZE_MULT, BOOT_SIZE_MULT: [226] */ + uint8_t pwrClF52V195; /* Power class for 52MHz at 1.95V: [200] */ + uint8_t pwrClF26V195; /* Power class for 26MHz at 1.95V: [201] */ + uint8_t pwrClF52V360; /* Power class for 52MHz at 3.6V: [202] */ + uint8_t pwrClF26V360; /* Power class for 26MHz at 3.6V: [203] */ + uint8_t pwrClF200V195; /* Power class for 200MHz at 1.95V: [236] */ + uint8_t pwrClF200V360; /* Power class for 200MHz at 1.95V: [237] */ + uint8_t pwrClDdrF52V195; /* Power class for 52MHz, DDR at 3.6V: [238] */ + uint8_t pwrClDdrF52V360; /* Power class for 52MHz, DDR at 3.6V: [239] */ + uint8_t rawPartitionSupport; /* PARTITIONING_SUPPORT: [160] */ + uint8_t rawErasedMemCount; /* ERASED_MEM_CONT: [181] */ + uint8_t strobeSupport; /* strobe Support:[184] */ + uint8_t rawCsdStructure; /* CSD_STRUCTURE: [194] */ + uint8_t rawCardType; /* CARD_TYPE: [196] */ + uint8_t outOfInterruptTime; /* OUT_OF_INTERRUPT_TIME: [198], Units: 10ms */ + uint8_t rawSaTimeout; /* S_A_TIMEOUT: [217], 100ns */ + uint8_t rawHcWpGrpSize; /* High-capacity write protect group size(HC_WP_GRP_SIZE): [221] */ + uint8_t rawEraseTimeoutMult; /* ERASE_TIMEOUT_MULT: [223] */ + uint8_t rawHcEraseGrpSize; /* HC_ERASE_GRP_SIZE: [224] */ + uint8_t rawSecTrimMult; /* SEC_TRIM_MULT: [229] */ + uint8_t rawSecEraseMult; /* SEC_ERASE_MULT: [230] */ + uint8_t rawSecFeatureSupport; /* SEC_FEATURE_SUPPORT: [231] */ + uint8_t rawTrimMult; /* TRIM_MULT: [232] */ + uint8_t rawSectors[EMMC_EXT_CSD_SEC_CNT_BYTES]; /* SEC_COUNT: [215:212] */ +}; + +/* SD_SWITCH_FUNC mode */ +#define SD_SWITCH_FUNC_CHECK 0 +#define SD_SWITCH_FUNC_SET 1 + +/* SD_SWITCH_FUNC function groups */ +#define SD_SWITCH_FUNC_GRP_ACCESS 0 + +/* SD_SWITCH_FUNC access modes */ +#define SD_SWITCH_FUNC_ACCESS_DEF 0 +#define SD_SWITCH_FUNC_ACCESS_HS 1 + +/* + * As a response to the switch function command, the SD Memory Card will send R1 response on the CMD line, + * and 512 bits of status on the DAT lines. + */ +#define SD_SWITCH_FUNCTION_STATUS_BYTES_LEN 64 + +enum SdCmdCode { + SD_CMD_SEND_RELATIVE_ADDR = 3, /* ask the card to publish a new relative address (RCA). */ + SD_CMD_SWITCH_FUNC = 6, /* Checks switchable function (mode 0) and switchs card function (mode 1). */ + SD_CMD_SEND_IF_COND = 8, /* + * Sends SD Memory Card interface condition, which includes host supply voltage + * information and asks the card whether card supports voltage. + */ + SD_CMD_SWITCH_VOLTAGE = 11, /* Switch to 1.8V bus signaling level. */ + SD_CMD_SEND_TUNING_BLOCK = 19, /* 64 bytes tuning pattern is sent for SDR50 and SDR104. */ + SD_CMD_ERASE_WR_BLK_START = 32, /* sets the address of the first writeblock to be erased. */ + SD_CMD_ERASE_WR_BLK_END = 33, /* sets the address of the last write block of the continuous range to be erased. */ + SD_ACMD_SET_BUS_WIDTH = 6, /* + * Defines the data bus width ('00' =1bit or '10' =4 bits bus) to be used for data + * transfer. The allowed data bus widths are given in SCR register. + */ + SD_ACMD_SD_STATUS = 13, /* Send the SD Memory Card status. */ + SD_ACMD_SEND_NUM_WR_BLKS = 22, /* Send the number of the written (without errors) write blocks. */ + SD_ACMD_OP_COND = 41, /* + * Asks the accessed card to send its operating condition register(OCR) content + * in the response on the CMD line. + */ + SD_ACMD_SEND_SCR = 51, /* Reads the SD Configuration Register(SCR). */ +}; + +enum SdSwitchFuncMode { + SD_SWITCH_FUNC_MODE_CHECK = 0, /* + * Check function is used to query if the card supports + * a specific function or functions. + */ + SD_SWITCH_FUNC_MODE_SET = 1, /* Set function is uesd to switch the functionality of the card. */ +}; + +enum SdSwitchFuncGroup { + SD_SWITCH_FUNC_GROUP_1 = 0, /* Function Group 1 is defined as Bus Speed Mode switch. */ + SD_SWITCH_FUNC_GROUP_2 = 1, /* Function Group 2 is defined for Command System extension. */ + SD_SWITCH_FUNC_GROUP_3 = 2, /* Function Group 3 is defined as driver strength selection for UHS-I modes. */ + SD_SWITCH_FUNC_GROUP_4 = 3, /* Function Group 4 is defined as current limit switch for each UHS-I mode. */ + SD_SWITCH_FUNC_GROUP_5 = 4, /* reserved. */ + SD_SWITCH_FUNC_GROUP_6 = 5, /* reserved. */ +}; + +struct SdSwitchFuncParam { + uint32_t mode; + uint32_t group; + uint32_t value; +}; + +enum SdBusSpeedMode { + SD_BUS_SPEED_MODE_DS = 0, /* Default Speed up to 25MHz 3.3V signaling */ + SD_BUS_SPEED_MODE_UHS_SDR12 = 0, /* SDR up to 25MHz 1.8V signaling */ + SD_BUS_SPEED_MODE_HS = 1, /* High Speed 50MHz 3.3V signaling */ + SD_BUS_SPEED_MODE_UHS_SDR25 = 1, /* SDR up to 50MHz 1.8V signaling */ + SD_BUS_SPEED_MODE_UHS_SDR50 = 2, /* SDR up to 100MHz 1.8V signaling */ + SD_BUS_SPEED_MODE_UHS_SDR104 = 3, /* SDR up to 208MHz 1.8V signaling */ + SD_BUS_SPEED_MODE_UHS_DDR50 = 4, /* DDR up to 50MHz 1.8V signaling */ +}; + +/* sd max data transfer rate */ +enum SdMaxDtr { + SD_HIGH_SPEED_MAX_DTR = 50000000, + SD_UHS_SDR104_MAX_DTR = 208000000, + SD_UHS_SDR50_MAX_DTR = 100000000, + SD_UHS_DDR50_MAX_DTR = 50000000, + SD_UHS_SDR25_MAX_DTR = 50000000, + SD_UHS_SDR12_MAX_DTR = 25000000, +}; + +enum SdDrvType { + SD_DRV_TYPE_B = 0x01, + SD_DRV_TYPE_A = 0x02, + SD_DRV_TYPE_C = 0x04, + SD_DRV_TYPE_D = 0x08, +}; + +enum SdMaxCurrentLimitBit { + SD_MAX_CURRENT_LIMIT_200 = (1 << 0), /* 200mA bit */ + SD_MAX_CURRENT_LIMIT_400 = (1 << 1), /* 400mA bit */ + SD_MAX_CURRENT_LIMIT_600 = (1 << 2), /* 600mA bit */ + SD_MAX_CURRENT_LIMIT_800 = (1 << 3), /* 800mA bit */ +}; + +enum SdMaxCurrentLimitValue { + SD_MAX_CURRENT_LIMIT_200_VALUE = 0, /* 200mA */ + SD_MAX_CURRENT_LIMIT_400_VALUE = 1, /* 400mA */ + SD_MAX_CURRENT_LIMIT_600_VALUE = 2, /* 600mA */ + SD_MAX_CURRENT_LIMIT_800_VALUE = 3, /* 800mA */ +}; + +enum SdScrSpec { + SD_SCR_SPEC_0 = 0, + SD_SCR_SPEC_1 = 1, + SD_SCR_SPEC_2 = 2, +}; + +enum SdScrBusWidths { + SD_SCR_BUS_WIDTHS_1 = (1 << 0), + SD_SCR_BUS_WIDTHS_4 = (1 << 2), +}; + +#define SD_SCR_SPEED_CLASS_CONTROL_SUPPORT (0x1 << 0) /* cmd20 */ +#define SD_SCR_SET_BLOCK_COUNT_SUPPORT (0x1 << 1) /* cmd23 */ + +/* SD Configuration register */ +struct SdScr { + uint8_t sdSpec; + uint8_t sdSpec3; + uint8_t sdBusWidths; + uint8_t cmdSupport; +}; + +/* + * SPEED_CLASS Code Field, SEPPD_CLASS : VAL. + * 0 : 0, 1 : 2, 2 : 4, 3 : 6, 4 : 10, 5-FF : reversed. + */ +enum SdSsrSpeedClass { + SD_SSR_SPEED_CLASS_0 = 0, + SD_SSR_SPEED_CLASS_1 = 1, + SD_SSR_SPEED_CLASS_2 = 2, + SD_SSR_SPEED_CLASS_3 = 3, + SD_SSR_SPEED_CLASS_4 = 4, + SD_SSR_SPEED_CLASS_REV = 5, +}; + +enum SdSsrSpeedClassVal { + SD_SSR_SPEED_CLASS_0_VAL = 0, + SD_SSR_SPEED_CLASS_1_VAL = 2, + SD_SSR_SPEED_CLASS_2_VAL = 4, + SD_SSR_SPEED_CLASS_3_VAL = 6, + SD_SSR_SPEED_CLASS_4_VAL = 10, + SD_SSR_SPEED_CLASS_REV_VAL = 20, +}; + +enum SdSsrUhsSpeedGrade { + SD_SSR_UHS_SPEED_GRADE_0 = 0, /* Less than 10MB/sec */ + SD_SSR_UHS_SPEED_GRADE_1 = 1, /* 10MB/sec and above */ + SD_SSR_UHS_SPEED_GRADE_2 = 2, /* Reversed */ + SD_SSR_UHS_SPEED_GRADE_3 = 3, /* 30MB/sec and above */ + SD_SSR_UHS_SPEED_GRADE_4 = 4, /* 4h-Fh, Reversed */ +}; + +/* SD Status register */ +struct SdSsr { + uint8_t speedClass; + uint8_t auSize; + uint16_t eraseSize; + uint8_t eraseTimeout; + uint8_t eraseOffset; + uint8_t uhsSpeedGrade; + uint32_t auValue; +}; + +union SdSpec3BusMode { + uint32_t data; + struct dataBits { + uint32_t uhsSdr12 : 1; + uint32_t uhsSdr25 : 1; + uint32_t uhsSdr50 : 1; + uint32_t uhsSdr104 : 1; + uint32_t uhsDdr50 : 1; + + uint32_t reserved : 27; + } bits; +}; + +struct SdSwitchCaps { + enum SdMaxDtr hsMaxDtr; + enum SdMaxDtr uhsMaxDtr; + union SdSpec3BusMode sdSpec3BusMode; + enum SdDrvType sdSpec3DrvType; + enum SdMaxCurrentLimitBit sdSpec3CurrLimit; +}; + +enum SdioCmdCode { + /* + * It is similar to the operation of ACMD41 for SD memory cards. + * It is used to inquire about the valtage range needed by the I/O card. + */ + SDIO_SEND_OP_COND = 5, + /* + * It is the simplest means to access a single register within the total 128K of register space in any I/O function, + * including the common I/O area (CIA). This command reads or writes 1 byte using only 1 command/response pair. + * A common use is to initialize registers or monitor status values for I/O functions. This command is the fastest + * means to read or write single I/O registers, as it requires only a single command/response pair. + */ + SDIO_RW_DIRECT = 52, + /* + * This command allows the reading or writing of a large number of I/O registers with a single command. + * Since this is a data transfer command, it provides the highest possible transfer rate. + */ + SDIO_RW_EXTENDED = 53, +}; + +/* Card Common Control Registers (CCCR), Register Name--Address. */ +enum SdioCccrAddr { + CCCR_SDIO_REVISION = 0x00, /* bit3-bit0: CCCR_REVISION, bit7-bit4: SDIO_REVISION. */ + SD_SPECIFICATION_REVISION = 0x01, /* bit3-bit0: SD_REVISION, bit7-bit4: RFU. */ + IO_ENABLE = 0x02, /* bit7-bit1: IOEx, bit0: RFU. */ + IO_READY = 0x03, /* bit7-bit1: IORx, bit0: RFU. */ + INT_ENABLE = 0x04, /* bit7-bit1: IENx, bit0: IENM. */ + INT_PENDING = 0x05, /* bit7-bit1: INTx, bit0: RFU. */ + IO_ABORT = 0x06, /* bit2-bit0: ASx, bit3: RES, bit7-bit4: RFU. */ + BUS_INTERFACE_CONTROL = 0x07, /* + * bit1-bit0: Bus Width, bit2: S8B, bit3: RFU, bit4:RFU, bit5: ECSI, + * bit6: SCSI, bit7: CD Disable. + */ + CARD_CAPBILITY = 0x08, /* + * bit0: SDC, bit1: SMB, bit2: SRW, bit3: SBS, bit4: S4MI, bit5: E4MI, + * bit6: LSC, bit7: 4BLS. + */ + COMMON_CIS_POINTER = 0x09, /* 09h-0Bh, Pointer to card's common CIS. */ + BUS_SUSPEND = 0x0C, /* bit0: BS, bit1: BR, bit7-bit2: RFU. */ + FUNCTION_SELECT = 0x0D, /* bit3-bit0: FSx, bit6-bit4: RFU, bit7: DF. */ + EXEC_FLAG = 0x0E, /* bit7-bit0: EXx. */ + FN0_BLOCK_SIZE = 0x10, /* 11h-10h, I/O block size for Function 0. */ + POWER_CONTROL = 0x12, /* bit0: SMPC, bit1: EMPC, bit7-bit2: RFU. */ + BUS_SPEED_SELECT = 0x13, /* bit0: SHS, bit3-bit1: BSSx, bit7-bit4: RFU. */ + UHS_I_SUPPORT = 0x14, /* bit0: SSDR50, bit1: SSDR104, bit2: SDDR50, bit7-bit3: RFU. */ + DRIVER_STRENGTH = 0x15, /* bit0: SDTA, bit1: SDTC, bit2: SDTD, bit3: RFU, bit4: DTS0, bit5: DTS1, bit7-6: RFU. */ + INTERRUPT_EXTENSION = 0x16, /* bit0: SAI, bit1: EAI, bit7-bit2: RFU. */ +}; + +/* CCCR_SDIO_REVISION-->bit3-bit0: CCCR_REVISION. */ +enum SdioCccrRev { + SDIO_CCCR_VERSION_1_00 = 0x00, /* CCCR/FBR Version 1.00 */ + SDIO_CCCR_VERSION_1_10 = 0x01, /* CCCR/FBR Version 1.10 */ + SDIO_CCCR_VERSION_1_20 = 0x02, /* CCCR/FBR Version 1.20 */ + SDIO_CCCR_VERSION_3_00 = 0x03, /* CCCR/FBR Version 3.00 */ +}; + +/* CCCR_SDIO_REVISION-->bit7-bit4: SDIO_REVISION. */ +enum SdioCccrSdioRev { + SDIO_CCCR_SDIO_REV_1_00 = 0x00, /* SDIO Spec Version 1.00 */ + SDIO_CCCR_SDIO_REV_1_10 = 0x01, /* SDIO Spec Version 1.10 */ + SDIO_CCCR_SDIO_REV_1_20 = 0x02, /* SDIO Spec Version 1.20 */ + SDIO_CCCR_SDIO_REV_2_00 = 0x03, /* SDIO Spec Version 2.00 */ + SDIO_CCCR_SDIO_REV_3_00 = 0x04, /* SDIO Spec Version 3.00 */ +}; + +/* SD_SPECIFICATION_REVISION-->bit3-bit0: SD_REVISION. */ +enum SdioCccrSdRev { + SDIO_CCCR_SD_REV_1_01 = 0x00, /* SD Physical Spec Version 1.01 */ + SDIO_CCCR_SD_REV_1_10 = 0x01, /* SD Physical Spec Version 1.10 */ + SDIO_CCCR_SD_REV_2_00 = 0x02, /* SD Physical Spec Version 2.00 */ + SDIO_CCCR_SD_REV_3_0x = 0x03, /* SD Physical Spev Version 3.0x */ +}; + +/* IO_ABORT-->bit3: RES(I/O Card Reset). + * Setting the RES to 1 shall cause I/O functions perform a soft reset. This does not affect the current card + * protocol selection and CD Disable. It is auto cleared, so there is no need to rewrite a value of 0. + */ +#define SDIO_CCCR_RES 0x08 + +/* BUS_INTERFACE_CONTROL-->bit1-bit0: Bus Width. */ +enum SdioCccrWidth { + SDIO_CCCR_WIDTH_1BIT = 0x00, /* 1-bit */ + SDIO_CCCR_WIDTH_4BIT = 0x02, /* 4-bit bus */ + SDIO_CCCR_WIDTH_8BIT = 0x03 /* 8-bit bus(only for embedded SDIO) */ +}; + +/* BUS_INTERFACE_CONTROL-->bit5: ECSI. Enable Continuous SPI Interrupt. */ +#define SDIO_CCCR_ECSI 0x20 +/* BUS_INTERFACE_CONTROL-->bit6: SCSI. Support Continuous SPI Interrupt. */ +#define SDIO_CCCR_SCSI 0x40 +/* + * BUS_INTERFACE_CONTROL-->bit7: CD Disable. Card Detect Disable. + * Connect[0]/DisConnect[1] the 10K-90K ohm pull-up resistor on CD/DAT[3](pin1) of the card. + * The pull-up may be used for card detection. This bit shall be set to 1 before issuing CMD53. + */ +#define SDIO_CCCR_CD_DISABLE 0x80 + +/* CARD_CAPBILITY */ +enum SdioCccrCapbility { + SDIO_CCCR_CAP_SDC = 0x01, /* Support Direct Command(CMD52). If set, all functions shall accept and execute + * the CMD52 while data transfer is underway on the DAT[x] lines. + */ + SDIO_CCCR_CAP_SMB = 0x02, /* Support Multiple Block Transfer. If set, all functions shall accept and execute + * CMD53 with the optional block mode bit set. + */ + SDIO_CCCR_CAP_SRW = 0x04, /* Support Read Wait. If set, all functions on the card are able to accept + * the wait signal on DAT[2]. + */ + SDIO_CCCR_CAP_SBS = 0x08, /* Support Bus Control. If set, all functions except 0 shall accept a request to + * suspend operations and resume under host control. + */ + SDIO_CCCR_CAP_S4MI = 0x10, /* Support Block Gap Interrupt. Support bit of interrupt between blocks of data + * in 4-bit SD mode. If set, the SDIO card is able to signal an interrupt between + * blocks while data transfer is in progress. + */ + SDIO_CCCR_CAP_E4MI = 0x20, /* Enable Block Gap Interrupt. If set, the card shall generate interrupts + * during 4 bit multi-block data transfer. + */ + SDIO_CCCR_CAP_LSC = 0x40, /* Low-Speed Card. If set, it indicates that the SDIO card is a Low-Speed Card. + * if this bit is clear, The SDIO card is Full-Speed card. + */ + SDIO_CCCR_CAP_4BLS = 0x80, /* 4-bit Mode Support for Low-Speed Card. if the SDIO card is a Low-Speed Card and + * it supports 4-bit data transfer, then this bit shall be set. + */ +}; + +/* POWER_CONTROL-->bit0: SMPC, bit1: EMPC */ +enum SdioCccrPower { + SDIO_CCCR_POWER_SMPC = 0x01, /* Support Master Power Control. */ + SDIO_CCCR_POWER_EMPC = 0x02, /* Enable Master Power Control. */ +}; + +/* BUS_SPEED_SELECT-->bit0: SHS. Support High-Speed. */ +#define SDIO_CCCR_BUS_SPEED_SHS 0x01 +/* + * BUS_SPEED_SELECT-->BSS0. BSS0 = 0, Default Speed(25MHz); BSS0 = 1, High Speed(50MHz). + * If the card is initialized 3.3V signaling, then BSS0 is effective. When SHS is set to 0, + * writing to this bit is ignored and always indicates 0. The card operates in High-Speed timing mode + * with a clock rate up to 50MHz. + */ +#define SDIO_CCCR_BUS_SPEED_EHS 0x02 + +/* + * BUS_SPEED_SELECT-->bit3-bit1: BSSx. + * If the card is initialized 1.8V signaling, then BSS[2:0] is effective. A card that supports UHS-I shall + * support High Speed mode and SHS shall be set to 1. + */ +enum SdioCccrBusSpeed { + SDIO_CCCR_BUS_SPEED_SDR12 = 0, /* Max Clock Freq: 25MHz. */ + SDIO_CCCR_BUS_SPEED_SDR25 = 1, /* Max Clock Freq: 50MHz. */ + SDIO_CCCR_BUS_SPEED_SDR50 = 2, /* Max Clock Freq: 100MHz. */ + SDIO_CCCR_BUS_SPEED_SDR104 = 3, /* Max Clock Freq: 208MHz. */ + SDIO_CCCR_BUS_SPEED_DDR50 = 4, /* Max Clock Freq: 50MHz. */ +}; + +/* UHS_I_SUPPORT-->bit0: SSDR50, bit1: SSDR104, bit2: SDDR50. */ +enum SdioCccrUhsISupport { + SDIO_CCCR_UHS_I_SSDR50 = (1 << 0), /* Support SDR50. If this bit set to 1, SDR12 and SDR25 shall be supported. */ + SDIO_CCCR_UHS_I_SSDR104 = (1 << 1), /* + * Support SDR104. If this bit set to 1, + * SDR12, SDR25 and SDR50 shall be supported. + */ + SDIO_CCCR_UHS_I_SDDR50 = (1 << 2), /* + * Support DDR50. If this bit set to 1, + * SDR12, SDR25 and SDR50 shall be supported. + */ +}; + +/* DRIVER_STRENGTH-->bit0: SDTA, bit1: SDTC, bit2: SDTD, bit3: RFU, bit4: DTS0, bit5: DTS1, bit7-bit6: RFU. */ +enum SdioCccrDriveTypeSupport { + SDIO_CCCR_DRIVE_SDTA = (1 << 0), + SDIO_CCCR_DRIVE_SDTC = (1 << 1), + SDIO_CCCR_DRIVE_SDTD = (1 << 2), +}; + +/* DRIVER_STRENGTH-->bit4: DTS0, bit5: DTS1. */ +enum SdioCccrDriveTypeSelect { + SDIO_CCCR_DTS_TYPE_B = (0 << 4), + SDIO_CCCR_DTS_TYPE_A = (1 << 4), + SDIO_CCCR_DTS_YPE_C = (2 << 4), + SDIO_CCCR_DTS_TYPE_D = (3 << 4), +}; + +/* INTERRUPT_EXTENSION-->bit0: SAI, bit1: EAI. */ +#define SDIO_CCCR_SAI 0x01 /* Support Asynchronous Interrupt. */ +#define SDIO_CCCR_EAI 0x02 /* Enable Asynchronous Interrupt. */ + +/* Function Basic Registers (FBR), Register Name--Address. */ +enum SdioFbrAddr { + SDIO_FBR_STD_FUNCTION_INTERFACE_CODE = 0x00, /* + * bit7: CSA enable, bit6: support CSA, bit5-bit4L: RFU, + * bit3-bit0: Standard SDIO Function Interface Code. + */ + SDIO_FBR_EXT_STD_FUNCTION_INTERFACE_CODE = 0x01, /* Extended Standard SDIO Function Interface Code. */ + SDIO_FBR_POWER_SELECTION = 0x02, /* bit0: SPS, bit1: EPS, bit3-bit2: RFU, bit7-bit4: PSx. */ + SDIO_FBR_POINTER_CIS = 0x09, /* n09h-n0Bh: (Card Information Structure)CIS pointer */ + SDIO_FBR_POINTER_CSA = 0x0C, /* n0Ch-n0Eh: (Code Storage Area)CSA pointer */ + SDIO_FBR_CSA_DATA_ACCESS = 0x0F, /* Data access window to CSA. */ + SDIO_FBR_IO_BLOCK_SIZE = 0x10, /* I/O block size. */ +}; + +/* The address of FBR is from 00n00h to 00nFFh where n is the function number(1 to 7). */ +#define SDIO_FBR_BASE_ADDR(f) ((f) * 0x100) + +/* SDIO_FBR_STD_FUNCTION_INTERFACE_CODE-->bit3-bit0: Standard SDIO Function Interface Code. */ +enum SdioFbrStdFuncIfCode { + SDIO_FBR_NO_STD_IF = 0x00, /* No SDIO standard interface supported by this function. */ + SDIO_FBR_STD_UART = 0x01, /* This function support SDIO standard UART. */ + SDIO_FBR_STD_BLUETOOTH_TYPE_A = 0x02, /* This function support SDIO Bluetooth Type-A standard interface. */ + SDIO_FBR_STD_BLUETOOTH_TYPE_B = 0x03, /* This function support SDIO Bluetooth Type-B standard interface. */ + SDIO_FBR_STD_GPS = 0x04, /* This function support SDIO GPS standard interface. */ + SDIO_FBR_STD_CAMERA = 0x05, /* This function support SDIO Camera standard interface. */ + SDIO_FBR_STD_PHS = 0x06, /* This function support SDIO PHS standard interface. */ + SDIO_FBR_STD_WLAN = 0x07, /* This function support SDIO WLAN interface. */ + SDIO_FBR_STD_EMBEDDED_SDIO_ATA = 0x08, /* This function support Embedded SDIO-ATA standard interface. */ + SDIO_FBR_STD_BLUETOOTH_TYPE_A_AMP = 0x09, /* This function support SDIO Bluetooth Type-A AMP standard interface. */ + SDIO_FBR_STD_SDIO_IF = 0x0F, /* + * This function support an SDIO standard interface number greater than Eh. + * In this case, the value in SDIO_FBR_EXT_STD_FUNCTION_INTERFACE_CODE identifies + * the standard SDIO interfaces type. + */ +}; + +/* SDIO_FBR_STD_FUNCTION_INTERFACE_CODE-->bit6: support CSA. */ +#define SDIO_FBR_SUPPORTS_CSA 0x40 +/* + * SDIO_FBR_STD_FUNCTION_INTERFACE_CODE-->bit7: CSA enable. + * If this function does not support CSA, then this bit shall be R/O and always read as 0. + */ +#define SDIO_FBR_CSA_ENABLE 0x80 + +/* + * SDIO_FBR_POWER_SELECTION-->bit0: SPS(Support Power Selection). + * SPS = 0: This function has no Power Selection. EPS shall be zero. + * SPS = 1: This function has 2 Power modes which are selected by EPS. + * This bit is effective when EMPC = 1 in CCCR and PS[3:0] = 0. + */ +#define SDIO_FBR_POWER_SPS 0x01 +/* + * SDIO_FBR_POWER_SELECTION-->bit1: EPS(Enable Power Selection). + * Enable (low) Power Selection. + */ +#define SDIO_FBR_POWER_EPS 0x02 +/* Sdio function 1-7. */ +#define SDIO_MAX_FUNCTION_NUMBER 7 + +/* SDIO CMD5 response R4, [24]S18A(Switching to 1.8V Accepted). */ +#define SDIO_R4_S18A (1 << 24) +/* R4, [27]Memory Present. Set to 1 if the card also contains SD memory. Set to 0 if the card is I/O only. */ +#define SDIO_R4_MEMORY_PRESENT (1 << 27) + +/* R5: [15:8]Response flags, indicating the status of the SDIO card. */ +enum SdioR5CardStatusBits { + SDIO_R5_COM_CRC_ERROR = (1 << 15), /* The CRC chack of the previous command failed. */ + SDIO_R5_ILLEGAL_COMMAND = (1 << 14), /* Command not legal for the card State. */ + SDIO_R5_ERROR = (1 << 11), /* A general or an unknuwn error occurred during the operation. */ + SDIO_R5_FUNCTION_NUMBER = (1 << 9), /* An invalid function number was requested. */ + SDIO_R5_OUT_OF_RANGE = (1 << 8), /* The command's argument was out of the allowed range for this card. */ +}; + +/* R5: [13:12]IO_CURRENT_STATE. */ +enum SdioCurrentState { + SDIO_CURRENT_STATE_DIS = 0, /* Disable. Initialize, Standby and Inactive States(card not selected). */ + SDIO_CURRENT_STATE_CMD = 1, /* DAT lines free. Command waiting, Executing CMD52 in CMD State. */ + SDIO_CURRENT_STATE_TRN = 2, /* Transfer. Command executing with data transfer using DAT[0] or DAT[3:0] lines. */ +}; + +/* Card Common Control Registers(CCCR). */ +struct SdioCccr { + uint32_t sdioRev; + uint32_t sdRev; + uint32_t multiBlock : 1; + uint32_t lowSpeed : 1; + uint32_t lowSpeed4Bit : 1; + uint32_t highPower : 1; + uint32_t highSpeed : 1; + uint32_t disableCd : 1; +}; + +/* + * n09-n0B, these three bytes make up a 24-bit pointer(only the lower 17 bits are used) to the start of the + * Card Information Structure(CIS) that is associated with each function. + */ +#define SDIO_CCCR_CIS_START_ADDR_BYTES 3 + +/* + * There are 2 tuples with only a tuple code, the CISTPL_NULL and the CISTPL_END. These tuples do not have any + * additional bytes. For all other tuples, bytes 1 of each tuple contains a link to the next tuple in the chain. + * If the link field is 0, the the tuple body is empty. + * If the link contains FFh, the this tuple is the last tuple in its chain. + */ +enum SdioCisTupleCode { + SDIO_CIS_TPL_NULL = 0x00, /* Null tuple. */ + SDIO_CIS_TPL_CHECKSUM = 0x10, /* Checksum Control. */ + SDIO_CIS_TPL_VERS_1 = 0x15, /* Level 1 version/product-information. */ + SDIO_CIS_TPL_ALTSTR = 0x16, /* The Alternate Language String Tuple. */ + SDIO_CIS_TPL_MANFID = 0x20, /* Manufacturer Identification String Tuple. */ + SDIO_CIS_TPL_FUNCID = 0x21, /* Function Identification Tuple. */ + SDIO_CIS_TPL_FUNCE = 0x22, /* Function Extensions. */ + SDIO_CIS_TPL_SDIO_STD = 0x91, /* Additional information for functions built to support application + * specifications for standard SDIO functions. + */ + SDIO_CIS_TPL_SDIO_EXT = 0x92, /* Reserved for future use with SDIO devices. */ + SDIO_CIS_TPL_END = 0xFF, /* The End-0f-chain Tuple. */ +}; + +#define SDIO_CIS_TPL_MANFID_MIN_SIZE 0x04 +#define SDIO_CIS_TPL_FUNCE_COMMON_MIN_SIZE 0x04 +#define SDIO_CIS_TPL_FUNCE_FUNCTION_PC_MIN_SIZE 0x1C +#define SDIO_CIS_TPL_FUNCE_FUNCTION_PC_MAX_SIZE 0x2A +#define SDIO_CIS_TPLFE_ENABLE_TIMEOUT_VAL_DEF 100 + +enum SdioCisTupleFunceType { + SDIO_CIS_TPL_FUNCE_COMMON = 0, /* This tuple gives the host common information about the card. */ + SDIO_CIS_TPL_FUNCE_FUNCTION_PC = 1, /* Extended Data 01h is defined for Power Control. */ + SDIO_CIS_TPL_FUNCE_FUNCTION_PS = 2, /* Extended of this tuple indicates that the card supports the Power State. */ +}; + +/* Card Information Structure(CIS). */ +struct SdioCis { + uint16_t vendorId; + uint16_t deviceId; + uint16_t blkSize; + uint32_t maxDtr; +}; + +/* + * The Card Information Structure is one or more chains(or linked lists) of data blocks or tuples. + * Basic Tuple Format: TPL_CODE, TPL_LINK, The tuple body. + */ +struct SdioCisTuple { + uint8_t tplCode; /* Tuple code: CISTPL_XXX */ + uint8_t tplLink; /* TPL_LINK Offset to next tuple in chains. This is the number of bytes in the tuple body. */ + uint8_t tplBody[0]; /* The tuple body(n bytes). */ +}; + +struct SdioCmdParam { + uint32_t funcNum; + uint32_t regAddr; + uint8_t writeData; + bool incrAddrFlag; + bool writeflag; + bool scatterFlag; + uint32_t scatterLen; +}; + +struct SdioRwBlockInfo { + uint32_t addr; + uint8_t *buf; + uint32_t size; + uint32_t scatterLen; + bool writeFlag; + bool incrAddrFlag; + bool scatterFlag; +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* _MMC_PROTOCOL_H */ diff --git a/support/platform/include/mmc/mmc_sd.h b/support/platform/include/mmc/mmc_sd.h new file mode 100644 index 00000000..451566cc --- /dev/null +++ b/support/platform/include/mmc/mmc_sd.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_SD_H +#define MMC_SD_H + +#include "mmc_corex.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct SdRegister { + uint32_t rawScr[SCR_LEN]; + uint16_t rawDsr; + struct SdScr scr; + struct SdSsr ssr; + struct SdSwitchCaps swCaps; +}; + +struct SdDevice { + struct MmcDevice mmc; + enum SdBusSpeedMode busSpeedMode; + struct SdRegister reg; +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_SD_H */ diff --git a/support/platform/include/mmc/mmc_sdio.h b/support/platform/include/mmc/mmc_sdio.h new file mode 100644 index 00000000..9ee57952 --- /dev/null +++ b/support/platform/include/mmc/mmc_sdio.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef MMC_SDIO_H +#define MMC_SDIO_H + +#include "mmc_sd.h" +#include "osal_thread.h" +#include "sdio_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct SdioFunction { + struct SdioDevice *dev; + uint32_t maxBlkSize; + uint32_t curBlkSize; + uint32_t funcNum; + uint8_t funcClass; + uint16_t vendorId; + uint16_t deviceId; + uint32_t timeOut; + SdioIrqHandler *irqHandler; +}; + +struct SdioRegister { + struct SdioCccr cccr; + struct SdioCis cis; +}; + +struct SdioDevice { + struct SdDevice sd; + struct SdioDeviceOps *sdioOps; + struct SdioRegister sdioReg; + uint32_t functions; + struct SdioFunction *sdioFunc[SDIO_MAX_FUNCTION_NUMBER]; + struct SdioFunction *curFunction; + struct OsalThread thread; /* irq thread */ + struct OsalSem sem; + bool irqPending; + bool threadRunning; +}; + +struct SdioDeviceOps { + int32_t (*incrAddrReadBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t); + int32_t (*incrAddrWriteBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t); + int32_t (*fixedAddrReadBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*fixedAddrWriteBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t, uint32_t); + int32_t (*func0ReadBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t); + int32_t (*func0WriteBytes)(struct SdioDevice *, uint8_t *, uint32_t, uint32_t); + int32_t (*setBlockSize)(struct SdioDevice *, uint32_t); + int32_t (*getCommonInfo)(struct SdioDevice *, SdioCommonInfo *, uint32_t); + int32_t (*setCommonInfo)(struct SdioDevice *, SdioCommonInfo *, uint32_t); + int32_t (*flushData)(struct SdioDevice *); + int32_t (*enableFunc)(struct SdioDevice *); + int32_t (*disableFunc)(struct SdioDevice *); + int32_t (*claimIrq)(struct SdioDevice *, SdioIrqHandler *); + int32_t (*releaseIrq)(struct SdioDevice *); + int32_t (*findFunc)(struct SdioDevice *, struct SdioFunctionConfig *); + int32_t (*claimHost)(struct SdioDevice *); + int32_t (*releaseHost)(struct SdioDevice *); +}; + +int32_t SdioDeviceFindFunction(struct SdioDevice *sdio, struct SdioFunctionConfig *config); +int32_t SdioDeviceIncrAddrReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size); +int32_t SdioDeviceIncrAddrWriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size); +int32_t SdioDeviceFixedAddrReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); +int32_t SdioDeviceFixedAddrWriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); +int32_t SdioDeviceFunc0ReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size); +int32_t SdioDeviceFunc0WriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size); +int32_t SdioDeviceSetBlockSize(struct SdioDevice *sdio, uint32_t blockSize); +int32_t SdioDeviceGetCommonInfo(struct SdioDevice *sdio, + SdioCommonInfo *info, SdioCommonInfoType infoType); +int32_t SdioDeviceSetCommonInfo(struct SdioDevice *sdio, + SdioCommonInfo *info, SdioCommonInfoType infoType); +int32_t SdioDeviceFlushData(struct SdioDevice *sdio); +int32_t SdioDeviceClaimHost(struct SdioDevice *sdio); +int32_t SdioDeviceReleaseHost(struct SdioDevice *sdio); +int32_t SdioDeviceEnableFunc(struct SdioDevice *sdio); +int32_t SdioDeviceDisableFunc(struct SdioDevice *sdio); +int32_t SdioDeviceClaimIrq(struct SdioDevice *sdio, SdioIrqHandler *irqHandler); +int32_t SdioDeviceReleaseIrq(struct SdioDevice *sdio); + +void SdioDeviceAddOps(struct SdioDevice *sdio, void *ops); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MMC_SDIO_H */ diff --git a/support/platform/include/plat_common.h b/support/platform/include/plat_common.h index e10234ec..6610dd57 100644 --- a/support/platform/include/plat_common.h +++ b/support/platform/include/plat_common.h @@ -13,4 +13,4 @@ bool PlatInIrqContext(void); -#endif +#endif /* PLATFORM_COMMON_H */ diff --git a/support/platform/include/plat_log.h b/support/platform/include/plat_log.h index 4de73d19..bc2d0671 100644 --- a/support/platform/include/plat_log.h +++ b/support/platform/include/plat_log.h @@ -17,4 +17,4 @@ #define PLAT_LOGV(fmt, arg...) HDF_LOGV(fmt, ##arg) #endif -#endif +#endif /* PLATFORM_LOG_H */ diff --git a/support/platform/include/sdio_core.h b/support/platform/include/sdio_core.h index 92a8d7cb..ef18b6c5 100644 --- a/support/platform/include/sdio_core.h +++ b/support/platform/include/sdio_core.h @@ -38,7 +38,7 @@ struct SdioCntlr { /** * @brief sdio host device operations. - * These methods need to be filled up by specific paltform. + * These methods need to be filled up by specific platform. */ struct SdioMethod { int32_t (*incrAddrReadBytes)(struct SdioCntlr *, uint8_t *, uint32_t, uint32_t, uint32_t); diff --git a/support/platform/include/watchdog_core.h b/support/platform/include/watchdog_core.h index 43bb1de6..84620473 100644 --- a/support/platform/include/watchdog_core.h +++ b/support/platform/include/watchdog_core.h @@ -45,7 +45,7 @@ struct WatchdogMethod { /** * @brief Add a new WatchdogCntlr to HDF. * - * @param cntlr The watchdog conroller to be added. + * @param cntlr The watchdog controller to be added. * * @return Returns 0 on success; returns a negative value otherwise. * @since 1.0 diff --git a/support/platform/src/common/platform_common.c b/support/platform/src/common/platform_common.c new file mode 100644 index 00000000..694bda31 --- /dev/null +++ b/support/platform/src/common/platform_common.c @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_log.h" +#include "osal_spinlock.h" +#include "platform_common.h" + +static struct PlatformModuleInfo g_platformModules[] = { +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_GPIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_GPIO) + { + .moduleType = PLATFORM_MODULE_GPIO, + .moduleName = "PLATFORM_MODULE_GPIO", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_I2C) || defined(CONFIG_DRIVERS_HDF_PLATFORM_I2C) + { + .moduleType = PLATFORM_MODULE_I2C, + .moduleName = "PLATFORM_MODULE_I2C", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SPI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SPI) + { + .moduleType = PLATFORM_MODULE_SPI, + .moduleName = "PLATFORM_MODULE_SPI", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PIN) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PIN) + { + .moduleType = PLATFORM_MODULE_PIN, + .moduleName = "PLATFORM_MODULE_PIN", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_CLOCK) || defined(CONFIG_DRIVERS_HDF_PLATFORM_CLOCK) + { + .moduleType = PLATFORM_MODULE_CLOCK, + .moduleName = "PLATFORM_MODULE_CLOCK", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_REGULATOR) || defined(CONFIG_DRIVERS_HDF_PLATFORM_REGULATOR) + { + .moduleType = PLATFORM_MODULE_REGULATOR, + .moduleName = "PLATFORM_MODULE_REGULATOR", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MIPI_DSI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MIPI_DSI) + { + .moduleType = PLATFORM_MODULE_MIPI_DSI, + .moduleName = "PLATFORM_MODULE_MIPI_DSI", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_UART) || defined(CONFIG_DRIVERS_HDF_PLATFORM_UART) + { + .moduleType = PLATFORM_MODULE_UART, + .moduleName = "PLATFORM_MODULE_UART", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SDIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SDIO) + { + .moduleType = PLATFORM_MODULE_SDIO, + .moduleName = "PLATFORM_MODULE_SDIO", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MDIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MDIO) + { + .moduleType = PLATFORM_MODULE_MDIO, + .moduleName = "PLATFORM_MODULE_MDIO", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_APB) || defined(CONFIG_DRIVERS_HDF_PLATFORM_APB) + { + .moduleType = PLATFORM_MODULE_APB, + .moduleName = "PLATFORM_MODULE_APB", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PCIE) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PCIE) + { + .moduleType = PLATFORM_MODULE_PCIE, + .moduleName = "PLATFORM_MODULE_PCIE", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PCM) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PCM) + { + .moduleType = PLATFORM_MODULE_PCM, + .moduleName = "PLATFORM_MODULE_PCM", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_I2S) || defined(CONFIG_DRIVERS_HDF_PLATFORM_I2S) + { + .moduleType = PLATFORM_MODULE_I2S, + .moduleName = "PLATFORM_MODULE_I2S", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PWM) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PWM) + { + .moduleType = PLATFORM_MODULE_PWM, + .moduleName = "PLATFORM_MODULE_PWM", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_DMA) || defined(CONFIG_DRIVERS_HDF_PLATFORM_DMA) + { + .moduleType = PLATFORM_MODULE_DMA, + .moduleName = "PLATFORM_MODULE_DMA", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_ADC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_ADC) + { + .moduleType = PLATFORM_MODULE_ADC, + .moduleName = "PLATFORM_MODULE_ADC", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_RTC) + { + .moduleType = PLATFORM_MODULE_RTC, + .moduleName = "PLATFORM_MODULE_RTC", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_WDT) || defined(CONFIG_DRIVERS_HDF_PLATFORM_WDT) + { + .moduleType = PLATFORM_MODULE_WDT, + .moduleName = "PLATFORM_MODULE_WDT", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_I3C) || defined(CONFIG_DRIVERS_HDF_PLATFORM_I3C) + { + .moduleType = PLATFORM_MODULE_I3C, + .moduleName = "PLATFORM_MODULE_I3C", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_CAN) || defined(CONFIG_DRIVERS_HDF_PLATFORM_CAN) + { + .moduleType = PLATFORM_MODULE_CAN, + .moduleName = "PLATFORM_MODULE_CAN", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_HDMI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_HDMI) + { + .moduleType = PLATFORM_MODULE_HDMI, + .moduleName = "PLATFORM_MODULE_HDMI", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MMC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MMC) + { + .moduleType = PLATFORM_MODULE_MMC, + .moduleName = "PLATFORM_MODULE_MMC", + }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MTD) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MTD) + { + .moduleType = PLATFORM_MODULE_MTD, + .moduleName = "PLATFORM_MODULE_MTD", + }, +#endif + { + .moduleType = PLATFORM_MODULE_DEFAULT, + .moduleName = "PLATFORM_MODULE_DEFAULT", + }, +}; + +static OsalSpinlock g_platformSpin; +static bool g_platformReady; + +void PlatformGlobalLock(void) +{ + if (g_platformReady == false) { + (void)OsalSpinInit(&g_platformSpin); + g_platformReady = true; + } + (void)OsalSpinLock(&g_platformSpin); +} + +void PlatformGlobalUnlock(void) +{ + (void)OsalSpinUnlock(&g_platformSpin); +} + +struct PlatformModuleInfo *PlatformModuleInfoGet(enum PlatformModuleType moduleType) +{ + int32_t i; + + for (i = 0; i < PlatformModuleInfoCount(); i++) { + if (g_platformModules[i].moduleType == moduleType) { + return &g_platformModules[i]; + } + } + return NULL; +} + +int32_t PlatformModuleInfoCount(void) +{ + return sizeof(g_platformModules) / sizeof(g_platformModules[0]); +} diff --git a/support/platform/src/common/platform_device.c b/support/platform/src/common/platform_device.c new file mode 100644 index 00000000..0e70cddf --- /dev/null +++ b/support/platform/src/common/platform_device.c @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_log.h" +#include "osal_mem.h" +#include "platform_common.h" +#include "platform_device.h" +#include "platform_manager.h" + +#define PLATFORM_DEV_NAME_DEFAULT "platform_device" + +static void PlatformDeviceOnFirstGet(struct HdfSRef *sref) +{ + (void)sref; +} + +static void PlatformDeviceOnLastPut(struct HdfSRef *sref) +{ + struct PlatformDevice *device = NULL; + struct PlatformNotifierNode *pos = NULL; + struct PlatformNotifierNode *tmp = NULL; + + if (sref == NULL) { + return; + } + + device = CONTAINER_OF(sref, struct PlatformDevice, ref); + if (device == NULL) { + HDF_LOGE("PlatformDeviceOnLastPut: get device is NULL!"); + return; + } + (void)OsalSpinLock(&device->spin); + device->ready = false; + + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &device->notifiers, struct PlatformNotifierNode, node) { + if (pos != NULL && pos->notifier != NULL && pos->notifier->handle != NULL) { + pos->notifier->handle(device, PLAT_EVENT_DEAD, pos->notifier->data); + } + } + + (void)OsalSpinUnlock(&device->spin); +} + +struct IHdfSRefListener g_platObjListener = { + .OnFirstAcquire = PlatformDeviceOnFirstGet, + .OnLastRelease = PlatformDeviceOnLastPut, +}; + +static void PlatformEventHandle(struct PlatformDevice *device, enum PlatformEventType event, void *data) +{ + if (device == NULL) { + return; + } + if (event == PLAT_EVENT_DEAD) { + (void)OsalSemPost(&device->released); + } +} + +static struct PlatformNotifier g_platformEventNotifier = { + .data = NULL, + .handle = PlatformEventHandle, +}; + +void PlatformDeviceInit(struct PlatformDevice *device) +{ + if (device == NULL) { + HDF_LOGW("PlatformDeviceInit: device is NULL"); + return; + } + + if (device->name == NULL) { + device->name = PLATFORM_DEV_NAME_DEFAULT; + } + + (void)OsalSpinInit(&device->spin); + (void)OsalSemInit(&device->released, 0); + DListHeadInit(&device->node); + DListHeadInit(&device->notifiers); + HdfSRefConstruct(&device->ref, &g_platObjListener); + + if (PlatformDeviceRegNotifier(device, &g_platformEventNotifier) != HDF_SUCCESS) { + HDF_LOGE("PlatformDeviceInit: reg notifier fail"); + } + device->ready = true; +} + +void PlatformDeviceUninit(struct PlatformDevice *device) +{ + if (device == NULL) { + HDF_LOGW("PlatformDevice: device is NULL"); + return; + } + device->ready = false; + + /* make sure no reference anymore before exit. */ + (void)OsalSemWait(&device->released, HDF_WAIT_FOREVER); + PlatformDeviceClearNotifier(device); + (void)OsalSemDestroy(&device->released); + (void)OsalSpinDestroy(&device->spin); +} + +struct PlatformDevice *PlatformDeviceGet(struct PlatformDevice *device) +{ + if (device == NULL) { + HDF_LOGE("PlatformDeviceGet: device is NULL"); + return NULL; + } + + HdfSRefAcquire(&device->ref); + return device; +} + +void PlatformDevicePut(struct PlatformDevice *device) +{ + if (device != NULL) { + HdfSRefRelease(&device->ref); + } +} + +int32_t PlatformDeviceRegNotifier(struct PlatformDevice *device, struct PlatformNotifier *notifier) +{ + struct PlatformNotifierNode *pNode = NULL; + + if (device == NULL || notifier == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + pNode = (struct PlatformNotifierNode *)OsalMemCalloc(sizeof(*pNode)); + if (pNode == NULL) { + HDF_LOGE("PlatformDeviceRegNotifier: alloc pNode fail"); + return HDF_ERR_MALLOC_FAIL; + } + pNode->notifier = notifier; + (void)OsalSpinLock(&device->spin); + DListInsertTail(&pNode->node, &device->notifiers); + (void)OsalSpinUnlock(&device->spin); + return HDF_SUCCESS; +} + +static void PlatformDeviceRemoveNotifier(struct PlatformDevice *device, struct PlatformNotifier *notifier) +{ + struct PlatformNotifierNode *pos = NULL; + struct PlatformNotifierNode *tmp = NULL; + + if (device->notifiers.next == NULL || device->notifiers.prev == NULL) { + HDF_LOGD("PlatformDeviceRemoveNotifier: notifiers not init."); + return; + } + + (void)OsalSpinLock(&device->spin); + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &device->notifiers, struct PlatformNotifierNode, node) { + if (pos != NULL && pos->notifier != NULL) { + /* if notifier not set, we remove all the notifier nodes. */ + if (notifier == NULL || notifier == pos->notifier) { + DListRemove(&pos->node); + OsalMemFree(pos); + } + if (notifier == pos->notifier) { + break; + } + } + } + (void)OsalSpinUnlock(&device->spin); +} + +void PlatformDeviceUnregNotifier(struct PlatformDevice *device, struct PlatformNotifier *notifier) +{ + if (device == NULL || notifier == NULL) { + return; + } + PlatformDeviceRemoveNotifier(device, notifier); +} + +void PlatformDeviceClearNotifier(struct PlatformDevice *device) +{ + if (device == NULL) { + return; + } + PlatformDeviceRemoveNotifier(device, NULL); +} + +int32_t PlatformDeviceAdd(struct PlatformDevice *device) +{ + struct PlatformManager *manager = NULL; + + if (device == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + PlatformDeviceInit(device); + manager = device->manager; + if (manager == NULL) { + manager = PlatformManagerGet(PLATFORM_MODULE_DEFAULT); + } + return PlatformManagerAddDevice(manager, device); +} + +void PlatformDeviceDel(struct PlatformDevice *device) +{ + struct PlatformManager *manager = NULL; + + if (device == NULL) { + return; + } + + manager = device->manager; + if (manager == NULL) { + manager = PlatformManagerGet(PLATFORM_MODULE_DEFAULT); + } + PlatformManagerDelDevice(manager, device); + PlatformDeviceUninit(device); +} diff --git a/support/platform/src/common/platform_manager.c b/support/platform/src/common/platform_manager.c new file mode 100644 index 00000000..0f3ccf66 --- /dev/null +++ b/support/platform/src/common/platform_manager.c @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_sem.h" +#include "platform_common.h" +#include "platform_device.h" +#include "platform_manager.h" + +#define PLATFORM_MANAGER_NAME_DEFAULT "PlatformManagerDefault" + +static void PlatformManagerInit(struct PlatformManager *manager) +{ + if (manager->name == NULL) { + manager->name = PLATFORM_MANAGER_NAME_DEFAULT; + } + + OsalSpinInit(&manager->spin); + DListHeadInit(&manager->devices); +} + +struct PlatformManager *PlatformManagerCreate(const char *name) +{ + struct PlatformManager *manager = NULL; + + manager = (struct PlatformManager *)OsalMemCalloc(sizeof(*manager)); + if (manager == NULL) { + HDF_LOGE("PlatformManagerCreate: malloc fail!"); + return NULL; + } + manager->name = name; + PlatformManagerInit(manager); + return manager; +} + +struct PlatformManager *PlatformManagerGet(enum PlatformModuleType module) +{ + struct PlatformManager *manager = NULL; + struct PlatformModuleInfo *info = NULL; + + info = PlatformModuleInfoGet(module); + if (info == NULL) { + HDF_LOGE("PlatformManagerGet: get module(%d) info failed", module); + return NULL; + } + + PlatformGlobalLock(); + if (info->priv == NULL) { + manager = PlatformManagerCreate(info->moduleName); + info->priv = manager; + } else { + manager = (struct PlatformManager *)info->priv; + } + PlatformGlobalUnlock(); + + return manager; +} + +int32_t PlatformManagerAddDevice(struct PlatformManager *manager, struct PlatformDevice *device) +{ + struct PlatformDevice *tmp = NULL; + bool repeatId = false; + + if (manager == NULL || device == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + device->manager = manager; + + if (PlatformDeviceGet(device) == NULL) { // keep a reference by manager + return HDF_PLT_ERR_DEV_GET; + } + + (void)OsalSpinLock(&manager->spin); + DLIST_FOR_EACH_ENTRY(tmp, &manager->devices, struct PlatformDevice, node) { + if (tmp != NULL && tmp->magic == device->magic) { + repeatId = true; + HDF_LOGE("PlatformManagerAddDevice: repeated magic:%u!", device->magic); + break; + } + } + if (!repeatId) { + DListInsertTail(&device->node, &manager->devices); + } + (void)OsalSpinUnlock(&manager->spin); + + if (repeatId) { + PlatformDevicePut(device); + } + return repeatId ? HDF_PLT_ERR_ID_REPEAT : HDF_SUCCESS; +} + +void PlatformManagerDelDevice(struct PlatformManager *manager, struct PlatformDevice *device) +{ + if (manager == NULL || device == NULL) { + return; + } + + if (device->manager != manager) { + HDF_LOGE("PlatformManagerDelDevice: manager mismatch!"); + return; + } + + (void)OsalSpinLock(&manager->spin); + if (!DListIsEmpty(&device->node)) { + DListRemove(&device->node); + } + (void)OsalSpinUnlock(&manager->spin); + PlatformDevicePut(device); // put the reference hold by manager +} + +struct PlatformDevice *PlatformManagerFindDevice(struct PlatformManager *manager, void *data, + bool (*match)(struct PlatformDevice *pdevice, void *data)) +{ + struct PlatformDevice *tmp = NULL; + struct PlatformDevice *pdevice = NULL; + + if (manager == NULL || match == NULL) { + return NULL; + } + if (manager->devices.prev == NULL || manager->devices.next == NULL) { + HDF_LOGD("PlatformManagerFindDevice: devices not init."); + return NULL; + } + + (void)OsalSpinLock(&manager->spin); + DLIST_FOR_EACH_ENTRY(tmp, &manager->devices, struct PlatformDevice, node) { + if (tmp != NULL && match(tmp, data)) { + pdevice = PlatformDeviceGet(tmp); + } + } + (void)OsalSpinUnlock(&manager->spin); + + return pdevice; +} + +static bool PlatformDeviceMatchByMagic(struct PlatformDevice *device, void *data) +{ + uint32_t magic = (uint32_t)(uintptr_t)data; + + return (device != NULL && device->magic == magic); +} + +struct PlatformDevice *PlatformManagerGetDeviceByMagic(struct PlatformManager *manager, uint32_t magic) +{ + if (manager == NULL) { + return NULL; + } + return PlatformManagerFindDevice(manager, (void *)(uintptr_t)magic, PlatformDeviceMatchByMagic); +} diff --git a/support/platform/src/common/platform_queue.c b/support/platform/src/common/platform_queue.c new file mode 100644 index 00000000..3a83ee01 --- /dev/null +++ b/support/platform/src/common/platform_queue.c @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "platform_queue.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_mutex.h" +#include "osal_thread.h" + +#define MMC_QUEUE_THREAD_STAK 20000 + +static int32_t PlatformQueueThreadWorker(void *data) +{ + int32_t ret; + struct PlatformQueue *queue = (struct PlatformQueue *)data; + struct PlatformMsg *msg = NULL; + + while (true) { + /* wait envent */ + ret = OsalSemWait(&queue->sem, HDF_WAIT_FOREVER); + if (ret != HDF_SUCCESS) { + continue; + } + + (void)OsalSpinLock(&queue->spin); + if (DListIsEmpty(&queue->msgs)) { + msg = NULL; + } else { + msg = DLIST_FIRST_ENTRY(&queue->msgs, struct PlatformMsg, node); + DListRemove(&msg->node); + } + (void)OsalSpinUnlock(&queue->spin); + /* message process */ + if (msg != NULL) { + (void)(queue->handle(queue, msg)); + if (msg->block == true) { + (void)OsalSemPost(&msg->sem); + } + } + } + return HDF_SUCCESS; +} + +struct PlatformQueue *PlatformQueueCreate(PlatformMsgHandle handle, const char *name, void *data) +{ + int32_t ret; + struct PlatformQueue *queue = NULL; + + if (handle == NULL) { + return NULL; + } + + queue = (struct PlatformQueue *)OsalMemCalloc(sizeof(*queue)); + if (queue == NULL) { + HDF_LOGE("PlatformQueueCreate: alloc queue fail!"); + return NULL; + } + (void)OsalSpinInit(&queue->spin); + (void)OsalSemInit(&queue->sem, 0); + DListHeadInit(&queue->msgs); + + ret = OsalThreadCreate(&queue->thread, (OsalThreadEntry)PlatformQueueThreadWorker, (void *)queue); + if (ret != HDF_SUCCESS) { + HDF_LOGE("PlatformQueueCreate: create thread fail!"); + OsalMemFree(queue); + return NULL; + } + + queue->name = (name == NULL) ? "PlatformWorkerThread" : name; + queue->handle = handle; + queue->data = data; + return queue; +} + +void PlatformQueueDestroy(struct PlatformQueue *queue) +{ + if (queue == NULL) { + return; + } + + (void)OsalThreadDestroy(&queue->thread); + (void)OsalSemDestroy(&queue->sem); + (void)OsalSpinDestroy(&queue->spin); + OsalMemFree(queue); +} + +int32_t PlatformQueueStart(struct PlatformQueue *queue) +{ + int32_t ret; + struct OsalThreadParam cfg; + + if (queue == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cfg.name = (char *)queue->name; + cfg.priority = OSAL_THREAD_PRI_HIGHEST; + cfg.stackSize = MMC_QUEUE_THREAD_STAK; + ret = OsalThreadStart(&queue->thread, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("PlatformQueueStart: start thread fail:%d", ret); + return ret; + } + + return HDF_SUCCESS; +} + +int32_t PlatformQueueSuspend(struct PlatformQueue *queue) +{ + if (queue == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return OsalThreadSuspend(&queue->thread); +} + +int32_t PlatformQueueResume(struct PlatformQueue *queue) +{ + if (queue == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return OsalThreadResume(&queue->thread); +} + +void PlatformQueueAddMsg(struct PlatformQueue *queue, struct PlatformMsg *msg) +{ + if (queue == NULL || msg == NULL) { + return; + } + + if (msg->block == true) { + (void)OsalSemInit(&msg->sem, 0); + } + DListHeadInit(&msg->node); + msg->error = HDF_SUCCESS; + (void)OsalSpinLock(&queue->spin); + DListInsertTail(&msg->node, &queue->msgs); + (void)OsalSpinUnlock(&queue->spin); + /* notify the worker thread */ + (void)OsalSemPost(&queue->sem); +} + +int32_t PlatformMsgWait(struct PlatformMsg *msg) +{ + if (msg == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (msg->block == false) { + return HDF_SUCCESS; + } + return OsalSemWait(&msg->sem, HDF_WAIT_FOREVER); +} diff --git a/support/platform/src/dmac_core.c b/support/platform/src/dmac_core.c index 320fcf5c..b2b207b4 100644 --- a/support/platform/src/dmac_core.c +++ b/support/platform/src/dmac_core.c @@ -6,16 +6,17 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "dmac_core.h" #include #include "hdf_log.h" #include "osal_io.h" #include "osal_irq.h" #include "osal_mem.h" -#include "dmac_core.h" #define HDF_LOG_TAG dmac_core #define DMA_ALIGN_SIZE 256 +#define DMA_MAX_TRANS_SIZE_DEFAULT 256 static int DmacCheck(struct DmaCntlr *cntlr) { @@ -66,7 +67,7 @@ static void DmacFreeLli(struct DmacChanInfo *chanInfo) */ void DmaCntlrDestroy(struct DmaCntlr *cntlr) { - int i; + unsigned int i; if (cntlr == NULL || cntlr->channelNum > DMAC_CHAN_NUM_MAX) { HDF_LOGE("%s: cntlr null or channel invalid!", __func__); @@ -107,7 +108,7 @@ static void DmacCallbackHandle(struct DmacChanInfo *chanInfo) static int DmacWaitM2mSendComplete(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo) { - unsigned int ret; + uint32_t ret; if (DmacCheck(cntlr) != HDF_SUCCESS) { HDF_LOGE("check fail"); @@ -130,7 +131,7 @@ static int DmacWaitM2mSendComplete(struct DmaCntlr *cntlr, struct DmacChanInfo * static int DmacAllocateChannel(struct DmaCntlr *cntlr) { - unsigned int flags; + uint32_t flags; int i; if (DmacCheck(cntlr) != HDF_SUCCESS) { @@ -190,7 +191,7 @@ static struct DmacChanInfo *DmacRequestChannel(struct DmaCntlr *cntlr, HDF_LOGE("%s: get channel fail ret = %d", __func__, ret); return NULL; } - HDF_LOGD("channel = %d, transfer type = %d width = %u, config = 0x%x, lliflag = 0x%x", + HDF_LOGD("channel = %d, transfer type = %u width = %u, config = 0x%x, lliflag = 0x%x", ret, chanInfo->transferType, chanInfo->width, chanInfo->config, chanInfo->lliEnFlag); return chanInfo; } @@ -220,19 +221,13 @@ static int DmacFillLli(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo, plli->count = cntlr->maxTransSize; } else { plli->nextLli = 0; - plli->count = (length % cntlr->maxTransSize); + plli->count = cntlr->maxTransSize == 0 ? length : (length % cntlr->maxTransSize); } plli->srcAddr = (long long)srcaddr; plli->destAddr = (long long)dstaddr; plli->config = chanInfo->config; - HDF_LOGD("plli->srcAddr = 0x%llx\n", plli->srcAddr); - HDF_LOGD("plli->destAddr = 0x%llx\n", plli->destAddr); - HDF_LOGD("plli->nextLli = 0x%llx\n", plli->nextLli); - HDF_LOGD("plli->config = 0x%x\n", plli->config); - HDF_LOGD("plli->count = 0x%x\n", plli->count); - if (chanInfo->transferType == TRASFER_TYPE_P2M) { dstaddr += plli->count; } else if (chanInfo->transferType == TRASFER_TYPE_M2P) { @@ -240,6 +235,7 @@ static int DmacFillLli(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo, } plli++; } + plli = chanInfo->lli; cntlr->dmacCacheFlush((UINTPTR)plli, (UINTPTR)plli + (UINTPTR)(sizeof(struct DmacLli) * lliNum)); HDF_LOGD("alloc_addr = 0x%x, alloc_addr + (sizeof(DmacLli) * lli_num)= 0x%x\n", (UINTPTR)plli, (UINTPTR)plli + (UINTPTR)(sizeof(struct DmacLli) * lliNum)); @@ -369,6 +365,7 @@ static int DmacM2mTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg) return HDF_FAILURE; } if (dmaSize == 0) { + DmacFreeChannel(cntlr, chanInfo->channel); return HDF_FAILURE; } leftSize -= dmaSize; @@ -403,7 +400,7 @@ int32_t DmaCntlrTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg) } else if (msg->direct == TRASFER_TYPE_M2M) { return DmacM2mTransfer(cntlr, msg); } else { - HDF_LOGE("%s: invalid direct %d", __func__, msg->direct); + HDF_LOGE("%s: invalid direct %u", __func__, msg->direct); return HDF_FAILURE; } return DmacPeriphTransfer(cntlr, msg, periphAddr); @@ -419,7 +416,7 @@ unsigned int DmaGetCurrChanDestAddr(struct DmaCntlr *cntlr, unsigned int chan) return cntlr->dmacGetCurrDestAddr(cntlr, chan); } -static uint32_t DmacIsr(int irq, void *dev) +static uint32_t DmacIsr(uint32_t irq, void *dev) { struct DmaCntlr *cntlr = (struct DmaCntlr *)dev; unsigned int channelStatus; @@ -431,9 +428,9 @@ static uint32_t DmacIsr(int irq, void *dev) } if (irq != cntlr->irq || cntlr->channelNum > DMAC_CHAN_NUM_MAX) { - HDF_LOGE("%s: cntlr parm err! irq:%d, channel:%u", + HDF_LOGE("%s: cntlr param err! irq:%u, channel:%u", __func__, cntlr->irq, cntlr->channelNum); - return HDF_SUCCESS; + return HDF_ERR_INVALID_PARAM; } for (i = 0; i < cntlr->channelNum; i++) { channelStatus = cntlr->dmacGetChanStatus(cntlr, i); @@ -455,15 +452,19 @@ int DmacInit(struct DmaCntlr *cntlr) HDF_LOGE("check fail"); return HDF_FAILURE; } - if (cntlr->channelNum > DMAC_CHAN_NUM_MAX) { - HDF_LOGE("%s: invalid channel:%d", __func__, cntlr->channelNum); + if (cntlr->channelNum == 0 || cntlr->channelNum > DMAC_CHAN_NUM_MAX) { + HDF_LOGE("%s: invalid channel:%u", __func__, cntlr->channelNum); return HDF_FAILURE; } + if (cntlr->maxTransSize == 0) { + cntlr->maxTransSize = DMA_MAX_TRANS_SIZE_DEFAULT; + } cntlr->remapBase = (char *)OsalIoRemap((unsigned long)cntlr->phyBase, (unsigned long)cntlr->regSize); - OsalSpinInit(&cntlr->lock); + (void)OsalSpinInit(&cntlr->lock); cntlr->channelList = (struct DmacChanInfo *)OsalMemCalloc(sizeof(struct DmacChanInfo) * cntlr->channelNum); if (cntlr->channelList == NULL) { HDF_LOGE("channel list malloc fail"); + (void)OsalSpinDestroy(&cntlr->lock); OsalIoUnmap((void *)cntlr->remapBase); return HDF_FAILURE; } @@ -474,9 +475,10 @@ int DmacInit(struct DmaCntlr *cntlr) } ret = OsalRegisterIrq(cntlr->irq, 0, (OsalIRQHandle)DmacIsr, "PlatDmac", cntlr); if (ret != HDF_SUCCESS) { - HDF_LOGE("DMA Irq %d request failed, ret = %d\n", cntlr->irq, ret); + HDF_LOGE("DMA Irq %u request failed, ret = %d\n", cntlr->irq, ret); OsalMemFree(cntlr->channelList); cntlr->channelList = NULL; + (void)OsalSpinDestroy(&cntlr->lock); OsalIoUnmap((void *)cntlr->remapBase); } return ret; diff --git a/support/platform/src/emmc_core.c b/support/platform/src/emmc_core.c index b30cc433..91c0061c 100644 --- a/support/platform/src/emmc_core.c +++ b/support/platform/src/emmc_core.c @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include "device_resource_if.h" #include "emmc_core.h" +#include "device_resource_if.h" #include "hdf_log.h" #include "osal_mem.h" @@ -16,11 +16,11 @@ int32_t EmmcCntlrFindHost(struct EmmcCntlr *cntlr) { if (cntlr == NULL || cntlr->method == NULL || cntlr->method->findHost == NULL) { - HDF_LOGE("EmmcCntlrFindHost: cntlr or method or findHost is NULL!"); + HDF_LOGE("EmmcCntlrFindHost: cntlr or method or findHost is null!"); return HDF_ERR_INVALID_PARAM; } if (cntlr->method->findHost(cntlr, &(cntlr->configData)) != HDF_SUCCESS) { - HDF_LOGE("EmmcCntlrFindHost: findHost fail!"); + HDF_LOGE("EmmcCntlrFindHost: findHost failed"); return HDF_ERR_INVALID_OBJECT; } return HDF_SUCCESS; @@ -42,8 +42,8 @@ int32_t EmmcCntlrGetCid(struct EmmcCntlr *cntlr, uint8_t *cid, uint32_t size) static int32_t EmmcGetCidWriteBackReply(struct HdfSBuf *reply, uint8_t *cid, uint32_t size) { - if (HdfSbufWriteBuffer(reply, cid, size) == false) { - HDF_LOGE("EmmcGetCidWriteBackReply: write to reply fail!"); + if (!HdfSbufWriteBuffer(reply, cid, size)) { + HDF_LOGE("EmmcGetCidWriteBackReply: write to reply failed"); return HDF_ERR_IO; } return HDF_SUCCESS; @@ -56,7 +56,7 @@ static int32_t EmmcGetCidDispatch(struct EmmcCntlr *cntlr, struct HdfSBuf *reply ret = EmmcCntlrGetCid(cntlr, cid, EMMC_CID_LEN); if (ret != HDF_SUCCESS) { - HDF_LOGE("EmmcGetCidDispatch: EmmcCntlrGetCid fail!"); + HDF_LOGE("EmmcGetCidDispatch: EmmcCntlrGetCid failed"); return ret; } return EmmcGetCidWriteBackReply(reply, cid, EMMC_CID_LEN); @@ -69,23 +69,23 @@ static int32_t EmmcIoDispatch(struct HdfDeviceIoClient *client, int cmd, struct (void)data; if (client == NULL || client->device == NULL) { - HDF_LOGE("EmmcIoDispatch: client or client->device is NULL"); + HDF_LOGE("EmmcIoDispatch: client or client->device is null"); return HDF_ERR_INVALID_OBJECT; } if (reply == NULL) { - HDF_LOGE("EmmcIoDispatch: reply is NULL"); + HDF_LOGE("EmmcIoDispatch: reply is null"); return HDF_ERR_INVALID_PARAM; } cntlr = (struct EmmcCntlr *)client->device->service; if (cntlr == NULL) { - HDF_LOGE("EmmcIoDispatch: service is NULL"); + HDF_LOGE("EmmcIoDispatch: service is null"); return HDF_ERR_INVALID_OBJECT; } if (cntlr->priv == NULL) { if (EmmcCntlrFindHost(cntlr) != HDF_SUCCESS) { - HDF_LOGE("EmmcIoDispatch: find host fail!"); + HDF_LOGE("EmmcIoDispatch: find host failed"); return HDF_ERR_INVALID_OBJECT; } } @@ -107,13 +107,13 @@ struct EmmcCntlr *EmmcCntlrCreateAndBind(struct HdfDeviceObject *device) struct EmmcCntlr *cntlr = NULL; if (device == NULL) { - HDF_LOGE("EmmcCntlrCreateAndBind: device is NULL!"); + HDF_LOGE("EmmcCntlrCreateAndBind: device is null!"); return NULL; } cntlr = (struct EmmcCntlr *)OsalMemCalloc(sizeof(*cntlr)); if (cntlr == NULL) { - HDF_LOGE("EmmcCntlrCreateAndBind: malloc host fail!"); + HDF_LOGE("EmmcCntlrCreateAndBind: malloc host failed"); return NULL; } cntlr->device = device; @@ -139,27 +139,27 @@ int32_t EmmcFillConfigData(struct HdfDeviceObject *device, struct EmmcConfigData int32_t ret; if (device == NULL || configData == NULL) { - HDF_LOGE("EmmcFillConfigData: input para is NULL."); + HDF_LOGE("EmmcFillConfigData: input para is null."); return HDF_FAILURE; } node = device->property; if (node == NULL) { - HDF_LOGE("EmmcFillConfigData: drs node is NULL."); + HDF_LOGE("EmmcFillConfigData: drs node is null."); return HDF_FAILURE; } drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); if (drsOps == NULL || drsOps->GetUint32 == NULL) { - HDF_LOGE("EmmcFillConfigData: invalid drs ops fail!"); + HDF_LOGE("EmmcFillConfigData: invalid drs ops failed"); return HDF_FAILURE; } ret = drsOps->GetUint32(node, "hostId", &(configData->hostId), 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("EmmcFillConfigData: read funcNum fail!"); + HDF_LOGE("EmmcFillConfigData: read funcNum failed"); return ret; } - HDF_LOGD("EmmcFillConfigData: Success! hostId = %d.", configData->hostId); + HDF_LOGD("EmmcFillConfigData: Success! hostId = %u.", configData->hostId); return HDF_SUCCESS; } diff --git a/support/platform/src/emmc_if.c b/support/platform/src/emmc_if.c index 1010af75..ed70d88c 100644 --- a/support/platform/src/emmc_if.c +++ b/support/platform/src/emmc_if.c @@ -6,12 +6,12 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "emmc_if.h" #include #ifndef __USER__ #include "devsvc_manager_clnt.h" #include "emmc_core.h" #endif -#include "emmc_if.h" #include "hdf_base.h" #ifdef __USER__ #include "hdf_io_service_if.h" @@ -96,16 +96,10 @@ static int32_t EmmcGetCidReadReplyData(struct HdfSBuf *reply, uint8_t *cid, uint uint32_t rLen; const void *rBuf = NULL; - if (HdfSbufReadBuffer(reply, &rBuf, &rLen) == false) { + if (!HdfSbufReadBuffer(reply, &rBuf, &rLen)) { HDF_LOGE("EmmcGetCidReadReplyData: read rBuf fail!"); return HDF_ERR_IO; } - if (size != rLen) { - HDF_LOGE("EmmcGetCidReadReplyData: err len:%u, rLen:%u", size, rLen); - if (rLen > size) { - rLen = size; - } - } if (memcpy_s(cid, size, rBuf, rLen) != EOK) { HDF_LOGE("EmmcGetCidReadReplyData: memcpy rBuf fail!"); @@ -115,7 +109,7 @@ static int32_t EmmcGetCidReadReplyData(struct HdfSBuf *reply, uint8_t *cid, uint return HDF_SUCCESS; } -int32_t EmmcServiceGetCid(struct HdfIoService *service, uint8_t *cid, uint32_t size) +static int32_t EmmcServiceGetCid(struct HdfIoService *service, uint8_t *cid, uint32_t size) { int32_t ret; struct HdfSBuf *reply = NULL; @@ -161,7 +155,7 @@ int32_t EmmcGetCid(DevHandle handle, uint8_t *cid, uint32_t size) } if (cid == NULL || size < EMMC_CID_LEN) { - HDF_LOGE("EmmcGetCid: error parms!"); + HDF_LOGE("EmmcGetCid: error params!"); return HDF_ERR_INVALID_PARAM; } #ifdef __USER__ @@ -176,7 +170,7 @@ void EmmcGetHuid(uint8_t *cid, uint32_t size) DevHandle handle = NULL; if (cid == NULL || size == 0) { - HDF_LOGE("EmmcGetUdid: error parms!"); + HDF_LOGE("EmmcGetUdid: error params!"); return; } if (memset_s(cid, sizeof(uint8_t) * size, 0, sizeof(uint8_t) * size) != EOK) { @@ -186,11 +180,11 @@ void EmmcGetHuid(uint8_t *cid, uint32_t size) handle = EmmcOpen(0); if (handle == NULL) { - HDF_LOGD("EmmcGetUdid: open fail, use default value!"); + HDF_LOGW("EmmcGetUdid: open fail, use default value!"); return; } if (EmmcGetCid(handle, cid, size) != HDF_SUCCESS) { - HDF_LOGD("EmmcGetUdid: get fail, use default value!"); + HDF_LOGW("EmmcGetUdid: get fail, use default value!"); } EmmcClose(handle); } diff --git a/support/platform/src/gpio_core.c b/support/platform/src/gpio_core.c index eaca5907..7224aeb2 100644 --- a/support/platform/src/gpio_core.c +++ b/support/platform/src/gpio_core.c @@ -212,7 +212,7 @@ static int32_t GpioIrqBridgeFunc(uint16_t local, void *data) (void)local; (void)OsalSpinLockIrqSave(&bridge->spin, &flags); - if (bridge->stop == false) { + if (!bridge->stop) { (void)OsalSemPost(&bridge->sem); } (void)OsalSpinUnlockIrqRestore(&bridge->spin, &flags); @@ -230,7 +230,7 @@ static int GpioIrqThreadWorker(void *data) if (ret != HDF_SUCCESS) { continue; } - if (bridge->stop == true) { + if (bridge->stop) { break; } PLAT_LOGV("GpioIrqThreadWorker: enter! gpio:%u-%u", bridge->cntlr->start, bridge->local); @@ -320,7 +320,7 @@ static void GpioIrqBridgeDestroy(struct GpioIrqBridge *bridge) #ifndef __KERNEL__ uint32_t flags; (void)OsalSpinLockIrqSave(&bridge->spin, &flags); - if (bridge->stop == false) { + if (!bridge->stop) { bridge->stop = true; (void)OsalSemPost(&bridge->sem); } diff --git a/support/platform/src/i2c_core.c b/support/platform/src/i2c_core.c index 0ee4f3bd..93b6e40f 100644 --- a/support/platform/src/i2c_core.c +++ b/support/platform/src/i2c_core.c @@ -32,20 +32,7 @@ static int32_t I2cCntlrLockDefault(struct I2cCntlr *cntlr) if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; } - -__TRY_LOCK: - if (OsalAtomicRead(&cntlr->atom) >= 1) { - OsalAtomicDec(&cntlr->atom); - return HDF_SUCCESS; - } - - if (PlatInIrqContext()) { - OsalMDelay(LOCK_WAIT_SECONDS_M); - } else { - OsalMSleep(LOCK_WAIT_SECONDS_M); - } - - goto __TRY_LOCK; + return OsalMutexLock(&cntlr->lock); } static void I2cCntlrUnlockDefault(struct I2cCntlr *cntlr) @@ -53,8 +40,7 @@ static void I2cCntlrUnlockDefault(struct I2cCntlr *cntlr) if (cntlr == NULL) { return; } - - OsalAtomicInc(&cntlr->atom); + (void)OsalMutexUnlock(&cntlr->lock); } static const struct I2cLockMethod g_i2cLockOpsDefault = { @@ -121,7 +107,7 @@ static void I2cManagerRemoveCntlr(struct I2cCntlr *cntlr) } /* - * Find an i2c cntroller by bus number, without ref count + * Find an i2c controller by bus number, without ref count */ static struct I2cCntlr *I2cManagerFindCntlr(int16_t number) { @@ -165,6 +151,8 @@ void I2cCntlrPut(struct I2cCntlr *cntlr) int32_t I2cCntlrAdd(struct I2cCntlr *cntlr) { + int32_t ret; + if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; } @@ -183,9 +171,13 @@ int32_t I2cCntlrAdd(struct I2cCntlr *cntlr) HDF_LOGE("I2cCntlrAdd: init lock fail!"); return HDF_FAILURE; } - OsalAtomicSet(&cntlr->atom, 1); - return I2cManagerAddCntlr(cntlr); + ret = I2cManagerAddCntlr(cntlr); + if (ret != HDF_SUCCESS) { + (void)OsalMutexDestroy(&cntlr->lock); + return ret; + } + return HDF_SUCCESS; } void I2cCntlrRemove(struct I2cCntlr *cntlr) @@ -244,7 +236,7 @@ static int32_t I2cTransferRebuildMsgs(struct HdfSBuf *data, struct I2cMsg **ppms uint8_t *bufReply = NULL; struct I2cMsg *msgs = NULL; - if (!HdfSbufReadBuffer(data, (const void **)&msgs, &len)) { + if (!HdfSbufReadBuffer(data, (const void **)&msgs, &len) || msgs == NULL) { HDF_LOGE("I2cTransferRebuildMsgs: read msgs fail!"); return HDF_ERR_IO; } diff --git a/support/platform/src/i2c_if.c b/support/platform/src/i2c_if.c index 2da22446..59665074 100644 --- a/support/platform/src/i2c_if.c +++ b/support/platform/src/i2c_if.c @@ -267,7 +267,7 @@ int32_t I2cTransfer(DevHandle handle, struct I2cMsg *msgs, int16_t count) } if (msgs == NULL || count <= 0) { - HDF_LOGE("I2cTransfer: err parms! msgs:%s, count:%d", + HDF_LOGE("I2cTransfer: err params! msgs:%s, count:%d", (msgs == NULL) ? "0" : "x", count); return HDF_ERR_INVALID_PARAM; } diff --git a/support/platform/src/mipi_dsi_core.c b/support/platform/src/mipi_dsi_core.c index 0e2c74cb..6a616935 100644 --- a/support/platform/src/mipi_dsi_core.c +++ b/support/platform/src/mipi_dsi_core.c @@ -6,10 +6,10 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include "osal_time.h" -#include "osal_mem.h" -#include "hdf_log.h" #include "mipi_dsi_core.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" #define HDF_LOG_TAG mipi_dsi_core @@ -36,21 +36,21 @@ int32_t MipiDsiRegisterCntlr(struct MipiDsiCntlr *cntlr) return HDF_FAILURE; } -DevHandle MipiDsiOpen(uint8_t id) +DevHandle MipiDsiOpen(uint8_t number) { - if (id >= MAX_CNTLR_CNT) { - HDF_LOGE("id invalid"); + if (number >= MAX_CNTLR_CNT) { + HDF_LOGE("invalid number"); return NULL; } - if (g_mipiDsihandle[id].cntlr == NULL) { - HDF_LOGE("no mipi_dsi %d cntlr", id); + if (g_mipiDsihandle[number].cntlr == NULL) { + HDF_LOGE("no mipi_dsi %d cntlr", number); return NULL; } - if (OsalMutexLock(&(g_mipiDsihandle[id].lock)) != HDF_SUCCESS) { + if (OsalMutexLock(&(g_mipiDsihandle[number].lock)) != HDF_SUCCESS) { HDF_LOGE("mutex lock fail"); return NULL; } - return (DevHandle)(&(g_mipiDsihandle[id])); + return (DevHandle)(&(g_mipiDsihandle[number])); } void MipiDsiClose(DevHandle handle) @@ -64,7 +64,7 @@ void MipiDsiClose(DevHandle handle) static int32_t MipiDsiSetDevCfg(struct MipiDsiCntlr *cntlr) { - /* set controler config */ + /* set controller config */ if (cntlr->setCntlrCfg == NULL) { HDF_LOGE("setCntlrCfg is NULL"); return HDF_FAILURE; @@ -137,6 +137,7 @@ void MipiDsiSetLpMode(DevHandle handle) HDF_LOGI("toLp not support!"); } } + void MipiDsiSetHsMode(DevHandle handle) { struct MipiDsiCntlr *cntlr = NULL; @@ -151,6 +152,7 @@ void MipiDsiSetHsMode(DevHandle handle) HDF_LOGI("toHs not support!"); } } + void MipiDsiEnterUlps(DevHandle handle) { struct MipiDsiCntlr *cntlr = NULL; @@ -165,6 +167,7 @@ void MipiDsiEnterUlps(DevHandle handle) HDF_LOGI("enterUlps not support!"); } } + void MipiDsiExitUlps(DevHandle handle) { struct MipiDsiCntlr *cntlr = NULL; diff --git a/support/platform/src/mmc/emmc_if.c b/support/platform/src/mmc/emmc_if.c new file mode 100644 index 00000000..b3c9f206 --- /dev/null +++ b/support/platform/src/mmc/emmc_if.c @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef __USER__ +#include "devsvc_manager_clnt.h" +#include "mmc_emmc.h" +#endif +#include "emmc_if.h" +#include "hdf_base.h" +#ifdef __USER__ +#include "hdf_io_service_if.h" +#endif +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_LOG_TAG emmc_if_c + +#ifdef __USER__ +static int32_t EmmcGetCidReadReplyData(struct HdfSBuf *reply, uint8_t *cid, uint32_t size) +{ + uint32_t rLen; + const void *rBuf = NULL; + + if (HdfSbufReadBuffer(reply, &rBuf, &rLen) == false) { + HDF_LOGE("EmmcGetCidReadReplyData: read rBuf fail!"); + return HDF_ERR_IO; + } + if (size != rLen) { + HDF_LOGE("EmmcGetCidReadReplyData: err len:%u, rLen:%u", size, rLen); + if (rLen > size) { + rLen = size; + } + } + + if (memcpy_s(cid, size, rBuf, rLen) != EOK) { + HDF_LOGE("EmmcGetCidReadReplyData: memcpy rBuf fail!"); + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +int32_t EmmcServiceGetCid(struct HdfIoService *service, uint8_t *cid, uint32_t size) +{ + int32_t ret; + struct HdfSBuf *reply = NULL; + + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + HDF_LOGE("EmmcServiceGetCid: failed to obtain reply!"); + ret = HDF_ERR_MALLOC_FAIL; + goto __EXIT; + } + + if (service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("EmmcServiceGetCid: dispatcher or Dispatch is NULL!"); + ret = HDF_ERR_NOT_SUPPORT; + goto __EXIT; + } + + ret = service->dispatcher->Dispatch(&service->object, EMMC_CMD_GET_CID, NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("EmmcServiceGetCid: failed to send service call:%d", ret); + goto __EXIT; + } + + ret = EmmcGetCidReadReplyData(reply, cid, size); + if (ret != HDF_SUCCESS) { + goto __EXIT; + } + HDF_LOGD("EmmcServiceGetCid: success"); + +__EXIT: + if (reply != NULL) { + HdfSBufRecycle(reply); + } + return ret; +} + +#else +static int32_t EmmcDeviceGetFromHandle(DevHandle handle, struct EmmcDevice **emmc) +{ + struct MmcDevice *mmc = NULL; + + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (emmc == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + mmc = MmcCntlrGetDevice((struct MmcCntlr *)handle); + if (mmc == NULL) { + return HDF_PLT_ERR_NO_DEV; + } + if (mmc->type != MMC_DEV_EMMC) { + MmcDevicePut(mmc); + return HDF_PLT_ERR_DEV_TYPE; + } + + *emmc = (struct EmmcDevice *)mmc; + return HDF_SUCCESS; +} + +#endif + +int32_t EmmcGetCid(DevHandle handle, uint8_t *cid, uint32_t size) +{ + if (handle == NULL) { + HDF_LOGE("EmmcGetCid: handle is NULL!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cid == NULL || size < EMMC_CID_LEN) { + HDF_LOGE("EmmcGetCid: error parms!"); + return HDF_ERR_INVALID_PARAM; + } +#ifdef __USER__ + return EmmcServiceGetCid((struct HdfIoService *)handle, cid, size); +#else + struct EmmcDevice *emmc = NULL; + int32_t ret; + + if (EmmcDeviceGetFromHandle(handle, &emmc) != HDF_SUCCESS) { + return HDF_ERR_INVALID_OBJECT; + } + ret = EmmcDeviceGetCid(emmc, cid, size); + MmcDevicePut((struct MmcDevice *)emmc); + return ret; +#endif +} + +void EmmcGetHuid(uint8_t *cid, uint32_t size) +{ + DevHandle handle = NULL; + if (cid == NULL || size == 0) { + HDF_LOGE("EmmcGetUdid: error parms!"); + return; + } + if (memset_s(cid, sizeof(uint8_t) * size, 0, sizeof(uint8_t) * size) != EOK) { + HDF_LOGE("EmmcGetUdid: memset_s fail!"); + return; + } + handle = EmmcOpen(0); + if (handle == NULL) { + HDF_LOGD("EmmcGetUdid: open fail, use default value!"); + return; + } + if (EmmcGetCid(handle, cid, size) != HDF_SUCCESS) { + HDF_LOGD("EmmcGetUdid: get fail, use default value!"); + } + EmmcClose(handle); +} diff --git a/support/platform/src/mmc/mmc_block.c b/support/platform/src/mmc/mmc_block.c new file mode 100644 index 00000000..2917a284 --- /dev/null +++ b/support/platform/src/mmc/mmc_block.c @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "storage_block.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "mmc_corex.h" +#include "mmc_sd.h" +#include "osal_mem.h" +#include "securec.h" + +static ssize_t MmcBlockRead(struct StorageBlock *sb, uint8_t *buf, size_t secStart, size_t nSec) +{ + if (sb == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (sb->type == MEDIA_MMC) { + return MmcDeviceRead((struct MmcDevice *)sb->media, buf, secStart, nSec); + } + return HDF_ERR_NOT_SUPPORT; +} + +static ssize_t MmcBlockWrite(struct StorageBlock *sb, const uint8_t *buf, size_t secStart, size_t nSec) +{ + if (sb == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (sb->type == MEDIA_MMC) { + return MmcDeviceWrite((struct MmcDevice *)sb->media, (uint8_t *)buf, secStart, nSec); + } + return HDF_ERR_NOT_SUPPORT; +} + +static ssize_t MmcBlockErase(struct StorageBlock *sb, size_t secStart, size_t nSec) +{ + if (sb == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (sb->type == MEDIA_MMC) { + return MmcDeviceErase((struct MmcDevice *)sb->media, secStart, nSec); + } + return HDF_ERR_NOT_SUPPORT; +} + +static uint32_t MmcBlockGetAuSize(struct StorageBlock *sb) +{ + struct MmcDevice *mmc = NULL; + struct SdDevice *sd = NULL; + + if (sb == NULL || sb->media == NULL) { + HDF_LOGE("MmcBlockGetAuSize: invalid sb or media!"); + return 0; + } + + if (sb->type != MEDIA_MMC) { + HDF_LOGE("MmcBlockGetAuSize: media is not mmc!"); + return 0; + } + + mmc = (struct MmcDevice *)sb->media; + if (mmc->type != MMC_DEV_SD) { + HDF_LOGE("MmcBlockGetAuSize: media is not sd!"); + return 0; + } + sd = (struct SdDevice *)mmc; + + return sd->reg.ssr.auSize; +} + +static bool MmcBlockIsPresent(struct StorageBlock *sb) +{ + return (sb != NULL && sb->type == MEDIA_MMC && + MmcDeviceIsPresent((struct MmcDevice *)sb->media)); +} + +static struct StorageBlockMethod g_mmcBlockOps = { + .read = MmcBlockRead, + .write = MmcBlockWrite, + .erase = MmcBlockErase, + .getAuSize = MmcBlockGetAuSize, + .isPresent = MmcBlockIsPresent, +}; + +static int32_t MmcBlockInit(struct StorageBlock *sb, struct MmcDevice *mmc) +{ + int32_t ret; + size_t nameSize; + + if (PlatformDeviceGet(&mmc->device) == NULL) { + return HDF_PLT_ERR_DEV_GET; + } + mmc->sb = sb; + sb->type = MEDIA_MMC; + sb->media = mmc; + sb->secSize = mmc->secSize; + sb->capacity = mmc->capacity; + sb->removeable = (mmc->state.bits.removeable == 0) ? false : true; + sb->ops = &g_mmcBlockOps; + nameSize = sizeof(sb->name); + ret = snprintf_s(sb->name, nameSize, nameSize - 1, "/dev/mmcblk%0d", mmc->cntlr->index); + if (ret <= 0) { + PlatformDevicePut(&mmc->device); + } + + return HDF_SUCCESS; +} + +static void MmcBlockUninit(struct StorageBlock *sb) +{ + struct MmcDevice *mmc = (struct MmcDevice *)sb->media; + + mmc->sb = NULL; + PlatformDevicePut(&mmc->device); +} + +int32_t MmcBlockAdd(struct MmcDevice *mmc) +{ + int32_t ret; + struct StorageBlock *sb = NULL; + + if (mmc == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + sb = (struct StorageBlock *)OsalMemCalloc(sizeof(*sb)); + if (sb == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + ret = MmcBlockInit(sb, mmc); + if (ret != HDF_SUCCESS) { + OsalMemFree(sb); + return ret; + } + + ret = StorageBlockAdd(sb); + if (ret != HDF_SUCCESS) { + MmcBlockUninit(sb); + OsalMemFree(sb); + return ret; + } + + return HDF_SUCCESS; +} + +void MmcBlockDel(struct MmcDevice *mmc) +{ + struct StorageBlock *sb = NULL; + + if (mmc == NULL) { + return; + } + sb = mmc->sb; + if (sb == NULL) { + return; + } + + StorageBlockDel(sb); + MmcBlockUninit(sb); + OsalMemFree(sb); +} diff --git a/support/platform/src/mmc/mmc_core.c b/support/platform/src/mmc/mmc_core.c new file mode 100644 index 00000000..6d2670b1 --- /dev/null +++ b/support/platform/src/mmc/mmc_core.c @@ -0,0 +1,1195 @@ + /* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "device_resource_if.h" +#include "hdf_dlist.h" +#include "hdf_log.h" +#include "mmc_block.h" +#include "mmc_corex.h" +#include "mmc_dispatch.h" +#include "mmc_emmc.h" +#include "mmc_sdio.h" +#include "osal_mem.h" +#include "osal_time.h" + +#define HDF_LOG_TAG mmc_core_c + +#define MMC_POWER_ON_DELAY_TIME 10 /* 10ms */ +#define MMC_OCR_MAX_VOLTAGE_BIT 23 +#define MMC_OCR_MAX_SHIFT_BITS 3 +#define MMC_DETECET_RETRY 5 +#define MMC_REQUEST_RETRY 3 +#define MMC_MAX_SECTOR_NUM 2048 +#define MMC_MAX_ERASE_SECTOR 0x100000 /* 512M */ +#define SDIO_IRQ_TASK_STACK_SIZE 0x2000 + +int32_t MmcCntlrDoRequest(struct MmcCntlr *cntlr, struct MmcCmd *cmd) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cmd == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->ops == NULL || cntlr->ops->request == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->ops->request(cntlr, cmd); +} + +static int32_t MmcCntlrExecRequest(struct MmcCntlr *cntlr, struct MmcCmd *cmd) +{ + uint32_t i; + int32_t ret; + + for (i = 0; i < MMC_REQUEST_RETRY; i++) { + MmcCntlrLock(cntlr); + ret = MmcCntlrDoRequest(cntlr, cmd); + MmcCntlrUnlock(cntlr); + if (ret != HDF_SUCCESS) { + continue; + } + if (cmd->returnError != HDF_SUCCESS) { + continue; + } + if (cmd->data != NULL && cmd->data->returnError != HDF_SUCCESS) { + continue; + } + break; + } + return ret; +} + +static int32_t MmcCntlrPlug(struct MmcCntlr *cntlr) +{ + uint32_t i; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (MmcCntlrDevPluged(cntlr) != true) { + HDF_LOGD("MmcCntlrPlug: dev is not plugged!"); + return HDF_SUCCESS; + } + + /* dev not delete. */ + if (cntlr->curDev != NULL) { + MmcCntlrLock(cntlr); + MmcDeleteDev(cntlr); + MmcCntlrUnlock(cntlr); + } + + if (cntlr->ops != NULL && cntlr->ops->systemInit != NULL) { + if (cntlr->ops->systemInit(cntlr) != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrPlug: system init fail!"); + return HDF_FAILURE; + } + } + + MmcCntlrLock(cntlr); + for (i = 0; i < MMC_DETECET_RETRY; i++) { + cntlr->detecting = true; + if (MmcDoDetect(cntlr) == HDF_SUCCESS) { + MmcDeviceAddOps(cntlr->curDev, NULL); + cntlr->detecting = false; + MmcCntlrUnlock(cntlr); + return HDF_SUCCESS; + } + } + cntlr->detecting = false; + MmcCntlrUnlock(cntlr); + + return HDF_FAILURE; +} + +static int32_t MmcCntlrUnplug(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + HDF_LOGE("MmcCntlrUnplug: cntlr is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + MmcCntlrLock(cntlr); + MmcDeleteDev(cntlr); + MmcCntlrUnlock(cntlr); + HDF_LOGD("host%d: a dev is removed!", cntlr->index); + return HDF_SUCCESS; +} + +static int32_t MmcCntlrSdioRescanHandle(struct MmcCntlr *cntlr) +{ + uint8_t val; + int32_t error; + + if (cntlr == NULL) { + HDF_LOGE("MmcCntlrSdioRescanHandle: cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->curDev != NULL && cntlr->curDev->state.bits.present > 0) { + if (cntlr->curDev->type == MMC_DEV_SDIO || cntlr->curDev->type == MMC_DEV_COMBO) { + error = SdioReadCccrIoEnable(cntlr, &val); + if (error != HDF_SUCCESS) { + HDF_LOGD("re-detect sdio."); + MmcCntlrPlug(cntlr); + } else { + HDF_LOGD("sdio no need to rescan."); + return HDF_SUCCESS; + } + } else { + HDF_LOGD("sd/emmc rescan does not support."); + } + } else { + HDF_LOGD("init detect fail, re-detect sdio."); + MmcCntlrPlug(cntlr); + } + + if (cntlr->curDev == NULL) { + HDF_LOGE("sdio rescan fail, please reset card!"); + return HDF_ERR_DEVICE_BUSY; + } + return HDF_SUCCESS; +} + +static int32_t MmcMsgHandleDefault(struct PlatformQueue *queue, struct PlatformMsg *msg) +{ + int32_t ret; + struct MmcCntlr *cntlr = NULL; + struct MmcMsg *mmcMsg = NULL; + + if (queue == NULL || msg == NULL) { + HDF_LOGE("MmcMsgHandleDefault: msg or queue is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct MmcCntlr *)queue->data; + if (cntlr == NULL) { + HDF_LOGE("MmcMsgHandleDefault: cntlr is null!"); + return HDF_ERR_INVALID_OBJECT; + } + mmcMsg = (struct MmcMsg *)msg; + switch (msg->code) { + case MMC_MSG_PLUG: + ret = MmcCntlrPlug(cntlr); + break; + case MMC_MSG_UNPLUG: + ret = MmcCntlrUnplug(cntlr); + break; + case MMC_MSG_REQUEST: + ret = MmcCntlrExecRequest(cntlr, mmcMsg->mmcCmd); + break; + case MMC_MSG_SDIO_RESCAN: + ret = MmcCntlrSdioRescanHandle(cntlr); + break; + default: + ret = HDF_ERR_NOT_SUPPORT; + break; + } + + if (mmcMsg->msg.block == false) { + OsalMemFree(mmcMsg); + } + return ret; +} + +static int32_t MmcCntlrInit(struct MmcCntlr *cntlr) +{ + int32_t ret; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->index >= MMC_CNTLR_NR_MAX) { + HDF_LOGE("MmcCntlrInit: invalid cntlr index:%u", cntlr->index); + return HDF_ERR_INVALID_PARAM; + } + + if (cntlr->hdfDevObj == NULL) { + HDF_LOGE("MmcCntlrInit: no HdfDeviceObject attached!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = OsalMutexInit(&cntlr->mutex); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrInit: mutex init fail!"); + return ret; + } + + cntlr->msgQueue = PlatformQueueCreate(MmcMsgHandleDefault, NULL, cntlr); + if (cntlr->msgQueue == NULL) { + HDF_LOGE("MmcCntlrInit: failed to create msg queue!"); + return HDF_PLT_ERR_OS_API; + } + ret = PlatformQueueStart(cntlr->msgQueue); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrInit: failed to start msg queue!"); + PlatformQueueDestroy(cntlr->msgQueue); + return ret; + } + + cntlr->service.Dispatch = MmcIoDispatch; + cntlr->hdfDevObj->service = &(cntlr->service); + cntlr->device.magic = cntlr->index; + cntlr->device.hdfDev = cntlr->hdfDevObj; + return HDF_SUCCESS; +} + +static void MmcCntlrUninit(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL) { + (void)OsalMutexDestroy(&cntlr->mutex); + PlatformQueueDestroy(cntlr->msgQueue); + } +} + +int32_t MmcCntlrAdd(struct MmcCntlr *cntlr) +{ + int32_t ret; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + ret = MmcCntlrInit(cntlr); + if (ret != HDF_SUCCESS) { + return ret; + } + + cntlr->device.manager = PlatformManagerGet(PLATFORM_MODULE_MMC); + ret = PlatformDeviceAdd(&cntlr->device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrAdd: device add fail!"); + MmcCntlrUninit(cntlr); + return ret; + } + return HDF_SUCCESS; +} + +void MmcCntlrRemove(struct MmcCntlr *cntlr) +{ + if (cntlr != NULL) { + MmcCntlrUninit(cntlr); + PlatformDeviceDel(&cntlr->device); + } +} + +void MmcCntlrSetDevice(struct MmcCntlr *cntlr, struct MmcDevice *mmc) +{ + if (cntlr == NULL || mmc == NULL) { + return; + } + cntlr->curDev = mmc; +} + +struct MmcDevice *MmcCntlrGetDevice(struct MmcCntlr *cntlr) +{ + struct MmcDevice *mmc = NULL; + + if (cntlr != NULL) { + mmc = cntlr->curDev; + } + return MmcDeviceGet(mmc); +} + +static int32_t MmcCntlrPostMsg(struct MmcCntlr *cntlr, struct MmcMsg *mmcMsg) +{ + int32_t ret; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (mmcMsg == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + PlatformQueueAddMsg(cntlr->msgQueue, &mmcMsg->msg); + ret = PlatformMsgWait(&mmcMsg->msg); + if (mmcMsg->msg.block == true) { + (void)OsalSemDestroy(&mmcMsg->msg.sem); + OsalMemFree(mmcMsg); + } + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrPostMsg: wait mmc msg fail!"); + return ret; + } + return HDF_SUCCESS; +} + +void MmcCntlrSetClock(struct MmcCntlr *cntlr, uint32_t clock) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->setClock == NULL) { + return; + } + cntlr->curDev->workPara.clock = clock; + cntlr->ops->setClock(cntlr, clock); +} + +void MmcCntlrSetBusWidth(struct MmcCntlr *cntlr, enum MmcBusWidth width) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->setBusWidth == NULL) { + return; + } + cntlr->curDev->workPara.width = width; + cntlr->ops->setBusWidth(cntlr, width); +} + +void MmcCntlrSetBusTiming(struct MmcCntlr *cntlr, enum MmcBusTiming timing) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->setBusTiming == NULL) { + return; + } + cntlr->curDev->workPara.timing = timing; + cntlr->ops->setBusTiming(cntlr, timing); +} + +void MmcCntlrSetEnhanceSrobe(struct MmcCntlr *cntlr, bool enable) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->setEnhanceSrobe == NULL) { + return; + } + cntlr->ops->setEnhanceSrobe(cntlr, enable); +} + +int32_t MmcCntlrSwitchVoltage(struct MmcCntlr *cntlr, enum MmcVolt voltage) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->switchVoltage == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return cntlr->ops->switchVoltage(cntlr, voltage); +} + +bool MmcCntlrDevReadOnly(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->devReadOnly == NULL) { + return false; + } + return cntlr->ops->devReadOnly(cntlr); +} + +bool MmcCntlrDevPluged(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->devPluged == NULL) { + return false; + } + + if (cntlr->caps.bits.nonremovable > 0) { + return true; + } + return cntlr->ops->devPluged(cntlr); +} + +bool MmcCntlrDevBusy(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->devBusy == NULL) { + return true; + } + + return cntlr->ops->devBusy(cntlr); +} + +int32_t MmcCntlrTune(struct MmcCntlr *cntlr, uint32_t cmdCode) +{ + if (cntlr == NULL || cntlr->ops == NULL || cntlr->ops->tune == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return cntlr->ops->tune(cntlr, cmdCode); +} + +void MmcCntlrSelectWorkVoltage(struct MmcCntlr *cntlr, union MmcOcr *ocr) +{ + uint32_t tmpOcr; + uint32_t i; + + /* ignore reveserd. */ + if ((ocr->ocrData & 0x7F) > 0) { + ocr->ocrData &= (~0x7F); + } + /* use low voltage shuould both host and dev support. */ + if (cntlr->ocrDef.bits.vdd1v65To1v95 == 0) { + ocr->bits.vdd1v65To1v95 = 0; + } + + /* + * Based on the voltage range supported by the host and the voltage range read from the OCR register, + * obtain the voltage range supported by both the host and the OCR register, + * and then select the minimum voltage value. + */ + tmpOcr = ((ocr->ocrData) & (cntlr->ocrDef.ocrData)); + for (i = 0; i <= MMC_OCR_MAX_VOLTAGE_BIT; i++) { + if ((tmpOcr & (1 << i)) > 0) { + break; + } + } + + if (i > 0 && i <= MMC_OCR_MAX_VOLTAGE_BIT) { + tmpOcr &= (MMC_OCR_MAX_SHIFT_BITS << i); + cntlr->vddBit = i; + } else { + tmpOcr = 0; + } + cntlr->curDev->reg.ocr.ocrData = tmpOcr; +} + +void MmcCntlrPowerUp(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL) { + return; + } + + if (cntlr->ops->setEnhanceSrobe != NULL) { + cntlr->ops->setEnhanceSrobe(cntlr, false); + } + /* disable clock. */ + if (cntlr->ops->setClock != NULL) { + cntlr->ops->setClock(cntlr, 0); + } + /* power up. */ + if (cntlr->ops->setPowerMode != NULL) { + cntlr->ops->setPowerMode(cntlr, MMC_POWER_MODE_POWER_UP); + } + if (cntlr->ops->setBusWidth != NULL) { + cntlr->ops->setBusWidth(cntlr, BUS_WIDTH1); + } + if (cntlr->ops->setBusTiming != NULL) { + cntlr->ops->setBusTiming(cntlr, BUS_TIMING_MMC_DS); + } + OsalMDelay(MMC_POWER_ON_DELAY_TIME); + + /* enable clock. */ + if (cntlr->ops->setClock != NULL) { + cntlr->ops->setClock(cntlr, cntlr->freqDef); + } + /* power on. */ + if (cntlr->ops->setPowerMode != NULL) { + cntlr->ops->setPowerMode(cntlr, MMC_POWER_MODE_POWER_ON); + } + OsalMDelay(MMC_POWER_ON_DELAY_TIME); + + if (cntlr->ops->hardwareReset != NULL && cntlr->caps.bits.hardwareReset > 0) { + cntlr->ops->hardwareReset(cntlr); + } + /* init voltage 3.3v. */ + if (cntlr->ops->switchVoltage != NULL) { + cntlr->ops->switchVoltage(cntlr, cntlr->voltDef); + } +} + +void MmcCntlrPowerOff(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL) { + return; + } + + /* disable clock. */ + if (cntlr->ops->setClock != NULL) { + cntlr->ops->setClock(cntlr, 0); + } + /* power up. */ + if (cntlr->ops->setPowerMode != NULL) { + cntlr->ops->setPowerMode(cntlr, MMC_POWER_MODE_POWER_OFF); + } + if (cntlr->ops->setBusWidth != NULL) { + cntlr->ops->setBusWidth(cntlr, BUS_WIDTH1); + } +} + +int32_t MmcCntlrAllocDev(struct MmcCntlr *cntlr, enum MmcDevType devType) +{ + uint32_t len = 0; + struct MmcDevice *mmc = NULL; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (devType == MMC_DEV_SDIO || devType == MMC_DEV_COMBO) { + len = (uint32_t)sizeof(struct SdioDevice); + } else if (devType == MMC_DEV_SD) { + len = (uint32_t)sizeof(struct SdDevice); + } else if (devType == MMC_DEV_EMMC) { + len = (uint32_t)sizeof(struct EmmcDevice); + } + + if (len == 0) { + HDF_LOGE("MmcCntlrAllocDev: len is 0, type = %d!", (uint32_t)devType); + return HDF_ERR_INVALID_PARAM; + } + + mmc = (struct MmcDevice *)OsalMemCalloc(len); + if (mmc == NULL) { + HDF_LOGE("MmcCntlrAllocDev: OsalMemCalloc fail!"); + return HDF_ERR_MALLOC_FAIL; + } + mmc->type = devType; + mmc->cntlr = cntlr; + MmcCntlrSetDevice(cntlr, mmc); + return 0; +} + +void MmcCntlrFreeDev(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->curDev == NULL) { + return; + } + + OsalMemFree(cntlr->curDev); + cntlr->curDev = NULL; +} + +bool MmcCntlrSupportUhs(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return false; + } + + if (cntlr->caps.bits.uhsSdr12 > 0 || + cntlr->caps.bits.uhsSdr25 > 0 || + cntlr->caps.bits.uhsSdr50 > 0 || + cntlr->caps.bits.uhsSdr104 > 0 || + cntlr->caps.bits.uhsDdr50 > 0) { + return true; + } + return false; +} + +bool MmcCntlrSupportHighSpeed400EnhancedStrobe(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return false; + } + + if (cntlr->caps2.bits.hs400EnhancedStrobe > 0 && + cntlr->caps.bits.cap8Bit > 0 && + cntlr->caps2.bits.hs400Support1v2 > 0 && + cntlr->caps2.bits.hs400Support1v8 > 0) { + return true; + } + return false; +} + +bool MmcCntlrSupportHighSpeed400(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return false; + } + + if (cntlr->caps.bits.cap8Bit > 0 && + cntlr->caps2.bits.hs400Support1v2 > 0 && + cntlr->caps2.bits.hs400Support1v8 > 0) { + return true; + } + return false; +} + +bool MmcCntlrSupportHighSpeed200(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return false; + } + + if (cntlr->caps2.bits.hs200Sdr1v8 > 0 || + cntlr->caps2.bits.hs200Sdr1v2 > 0) { + return true; + } + return false; +} + +bool MmcCntlrSdSupportCmd23(struct MmcCntlr *cntlr) +{ + struct SdDevice *dev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return false; + } + if (cntlr->curDev->type != MMC_DEV_SD && cntlr->curDev->type != MMC_DEV_COMBO) { + return false; + } + + dev = (struct SdDevice *)cntlr->curDev; + if ((dev->reg.scr.cmdSupport & SD_SCR_SET_BLOCK_COUNT_SUPPORT) > 0) { + return true; + } + return false; +} + +bool MmcCntlrEmmcSupportCmd23(struct MmcCntlr *cntlr) +{ + struct EmmcDevice *dev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return false; + } + if (cntlr->curDev->type != MMC_DEV_EMMC) { + return false; + } + + dev = (struct EmmcDevice *)cntlr->curDev; + if ((dev->mmc.reg.csd.ccc & MMC_CSD_CCC_BLOCK_READ) > 0 || + (dev->mmc.reg.csd.ccc & MMC_CSD_CCC_BLOCK_WRITE) > 0) { + return true; + } + return false; +} + +int32_t MmcCntlrAddMsgToQueue(struct MmcCntlr *cntlr, struct MmcCmd *cmd, + int32_t code, bool block) +{ + struct MmcMsg *msg = NULL; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + msg = (struct MmcMsg *)OsalMemCalloc(sizeof(struct MmcMsg)); + if (msg == NULL) { + HDF_LOGE("MmcCntlrAddMsgToQueue: OsalMemCalloc fail!n"); + return HDF_ERR_MALLOC_FAIL; + } + msg->msg.code = code; + msg->msg.data = (void *)cntlr; + msg->msg.block = block; + msg->mmcCmd = cmd; + return MmcCntlrPostMsg(cntlr, msg); +} + +int32_t MmcCntlrAddRequestMsgToQueue(struct MmcCntlr *cntlr, struct MmcCmd *cmd) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->devPluged == NULL) { + return HDF_PLT_ERR_NO_DEV; + } + if (cntlr->ops->devPluged(cntlr) == false) { + HDF_LOGE("MmcCntlrAddRequestMsgToQueue: host%d dev is unplug!", cntlr->index); + return HDF_PLT_ERR_NO_DEV; + } + + return MmcCntlrAddMsgToQueue(cntlr, cmd, MMC_MSG_REQUEST, true); +} + +int32_t MmcCntlrAddDetectMsgToQueue(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->devPluged == NULL) { + return HDF_PLT_ERR_NO_DEV; + } + + if (cntlr->ops->devPluged(cntlr) == false) { + HDF_LOGD("MmcCntlrAddDetectMsgToQueue: host%d dev is not plugged!", cntlr->index); + return HDF_PLT_ERR_NO_DEV; + } + cntlr->devPluged = true; + return MmcCntlrAddMsgToQueue(cntlr, NULL, MMC_MSG_PLUG, false); +} + +int32_t MmcCntlrAddPlugMsgToQueue(struct MmcCntlr *cntlr) +{ + bool curStatus = false; + int32_t code; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->ops == NULL || cntlr->ops->devPluged == NULL) { + return HDF_PLT_ERR_NO_DEV; + } + + curStatus = cntlr->ops->devPluged(cntlr); + if (curStatus == cntlr->devPluged) { + HDF_LOGD("MmcCntlrAddPlugMsgToQueue: dev plug srtatus not change."); + return HDF_SUCCESS; + } + + if (curStatus == true) { + cntlr->devPluged = true; + code = MMC_MSG_PLUG; + HDF_LOGD("host%d: a dev is plugged!", cntlr->index); + } else { + cntlr->devPluged = false; + code = MMC_MSG_UNPLUG; + HDF_LOGD("host%d: a dev is unplugged!", cntlr->index); + } + return MmcCntlrAddMsgToQueue(cntlr, NULL, code, false); +} + +int32_t MmcCntlrAddSdioRescanMsgToQueue(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->devType != MMC_DEV_SDIO) { + HDF_LOGD("MmcCntlrAddSdioRescanMsgToQueue: not sdio card, do not handle rescan!"); + return HDF_FAILURE; + } + + return MmcCntlrAddMsgToQueue(cntlr, NULL, MMC_MSG_SDIO_RESCAN, true); +} + +static void SdioHandlePendingIrq(struct MmcCntlr *cntlr, struct SdioDevice *dev) +{ + uint8_t val; + int32_t ret; + uint32_t i; + struct SdioFunction *func = dev->curFunction; + + if (func == NULL) { + HDF_LOGE("MmcCntlrHandleSdioPendingIrq: cur func is NULL."); + return; + } + if (dev->irqPending == true && func->irqHandler != NULL) { + func->irqHandler(func); + return; + } + + ret = SdioReadCccrIntPending(cntlr, &val); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrHandleSdioPendingIrq: read cccr int pending fail! ret = %d.", ret); + return; + } + + for (i = 0; i < SDIO_MAX_FUNCTION_NUMBER; i++) { + if ((val & (1 << (i + 1))) == 0) { + continue; + } + func = dev->sdioFunc[i]; + if (func == NULL) { + HDF_LOGD("MmcCntlrHandleSdioPendingIrq: function%d not exist.", i + 1); + continue; + } + if (func->irqHandler == NULL) { + HDF_LOGD("MmcCntlrHandleSdioPendingIrq: function%d irq handler not exist.", i + 1); + continue; + } + func->irqHandler(func); + } +} + +static int32_t SdioIrqThreadWorker(void *data) +{ + int32_t ret; + struct SdioDevice *dev = (struct SdioDevice *)data; + struct MmcCntlr *cntlr = NULL; + + if (dev == NULL) { + HDF_LOGE("SdioIrqThreadWorker: data is NULL."); + return HDF_FAILURE; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioIrqThreadWorker: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + while (true) { + /* wait envent */ + ret = OsalSemWait(&dev->sem, HDF_WAIT_FOREVER); + if (ret != HDF_SUCCESS) { + continue; + } + SdioHandlePendingIrq(cntlr, dev); + dev->irqPending = false; + if (cntlr->caps.bits.sdioIrq > 0 && cntlr->ops != NULL && cntlr->ops->setSdioIrq != NULL) { + (void)cntlr->ops->setSdioIrq(cntlr, true); + } + } + + return HDF_SUCCESS; +} + +int32_t MmcCntlrCreatSdioIrqThread(struct MmcCntlr *cntlr) +{ + int32_t ret; + struct OsalThreadParam config = {0}; + struct SdioDevice *dev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + dev = (struct SdioDevice *)cntlr->curDev; + ret = OsalSemInit(&dev->sem, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrCreatSdioIrqThread: sem init fail."); + return ret; + } + + ret = OsalThreadCreate(&dev->thread, (OsalThreadEntry)SdioIrqThreadWorker, dev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrCreatSdioIrqThread: thread create fail."); + (void)OsalSemDestroy(&dev->sem); + return ret; + } + + config.name = "SdioIrqTask"; + config.priority = OSAL_THREAD_PRI_HIGHEST; + config.stackSize = SDIO_IRQ_TASK_STACK_SIZE; + ret = OsalThreadStart(&dev->thread, &config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrCreatSdioIrqThread: thread start fail."); + OsalThreadDestroy(&dev->thread); + (void)OsalSemDestroy(&dev->sem); + return ret; + } + dev->threadRunning = true; + if (cntlr->caps.bits.sdioIrq > 0 && cntlr->ops != NULL && cntlr->ops->setSdioIrq != NULL) { + (void)cntlr->ops->setSdioIrq(cntlr, true); + } + return HDF_SUCCESS; +} + +void MmcCntlrDestroySdioIrqThread(struct MmcCntlr *cntlr) +{ + struct SdioDevice *dev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return; + } + + dev = (struct SdioDevice *)cntlr->curDev; + (void)OsalThreadDestroy(&dev->thread); + (void)OsalSemDestroy(&dev->sem); + dev->threadRunning = true; +} + +void MmcCntlrNotifySdioIrqThread(struct MmcCntlr *cntlr) +{ + struct SdioDevice *dev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + HDF_LOGD("MmcCntlrNotifySdioIrqThread: cntlr or curDev is null!"); + return; + } + if (cntlr->curDev->type != MMC_DEV_SDIO && cntlr->curDev->type != MMC_DEV_COMBO) { + return; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev->threadRunning == true) { + dev->irqPending = true; + /* notify the worker thread */ + (void)OsalSemPost(&dev->sem); + } +} + +static void MmcCntlrParseCapability(const struct DeviceResourceNode *node, + struct DeviceResourceIface *drsOps, struct MmcCntlr *cntlr) +{ + int32_t ret; + + ret = drsOps->GetUint16(node, "voltDef", &(cntlr->voltDef), 0); + if (ret != HDF_SUCCESS) { + cntlr->voltDef = 0; + } + ret = drsOps->GetUint32(node, "freqMin", &(cntlr->freqMin), 0); + if (ret != HDF_SUCCESS) { + cntlr->freqMin = 0; + } + ret = drsOps->GetUint32(node, "freqMax", &(cntlr->freqMax), 0); + if (ret != HDF_SUCCESS) { + cntlr->freqMax = 0; + } + ret = drsOps->GetUint32(node, "freqDef", &(cntlr->freqDef), 0); + if (ret != HDF_SUCCESS) { + cntlr->freqDef = 0; + } + ret = drsOps->GetUint32(node, "ocrDef", &(cntlr->ocrDef.ocrData), 0); + if (ret != HDF_SUCCESS) { + cntlr->ocrDef.ocrData = 0; + } + + ret = drsOps->GetUint32(node, "caps", &(cntlr->caps.capsData), 0); + if (ret != HDF_SUCCESS) { + cntlr->caps.capsData = 0; + } + ret = drsOps->GetUint32(node, "caps2", &(cntlr->caps2.caps2Data), 0); + if (ret != HDF_SUCCESS) { + cntlr->caps2.caps2Data = 0; + } + + ret = drsOps->GetUint32(node, "maxBlkNum", &(cntlr->maxBlkNum), 0); + if (ret != HDF_SUCCESS) { + cntlr->maxBlkNum = 0; + } + ret = drsOps->GetUint32(node, "maxBlkSize", &(cntlr->maxBlkSize), 0); + if (ret != HDF_SUCCESS) { + cntlr->maxBlkSize = 0; + } + cntlr->maxReqSize = cntlr->maxBlkNum * cntlr->maxBlkSize; +} + +int32_t MmcCntlrParse(struct MmcCntlr *cntlr, struct HdfDeviceObject *obj) +{ + const struct DeviceResourceNode *node = NULL; + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (obj == NULL || cntlr == NULL) { + HDF_LOGE("MmcCntlrParse: input param is NULL."); + return HDF_FAILURE; + } + + node = obj->property; + if (node == NULL) { + HDF_LOGE("MmcCntlrParse: drs node is NULL."); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint16 == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("MmcCntlrParse: invalid drs ops fail!"); + return HDF_FAILURE; + } + + ret = drsOps->GetUint16(node, "hostId", &(cntlr->index), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrParse: read hostId fail!"); + return ret; + } + HDF_LOGD("MmcCntlrParse: hostId = %d", cntlr->index); + + ret = drsOps->GetUint32(node, "devType", &(cntlr->devType), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCntlrParse: read devType fail!"); + return ret; + } + HDF_LOGD("MmcCntlrParse: devType = %d", cntlr->devType); + + MmcCntlrParseCapability(node, drsOps, cntlr); + return HDF_SUCCESS; +} + +int32_t MmcDeviceAdd(struct MmcDevice *mmc) +{ + int32_t ret; + + if (mmc == NULL || mmc->cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (mmc->type >= MMC_DEV_INVALID) { + return HDF_PLT_ERR_DEV_TYPE; + } + if (mmc->secSize == 0) { + mmc->secSize = MMC_SEC_SIZE; + } else { + HDF_LOGE("MmcDeviceAdd: invalid sector size:%u", mmc->secSize); + return HDF_ERR_INVALID_PARAM; + } + if (mmc->type != MMC_DEV_SDIO && mmc->capacity == 0) { + HDF_LOGE("MmcDeviceAdd: invalid capacity:%u", mmc->capacity); + return HDF_ERR_INVALID_PARAM; + } + if (mmc->type != MMC_DEV_SDIO && mmc->eraseSize == 0) { + HDF_LOGE("MmcDeviceAdd: invalid erase size:%u", mmc->eraseSize); + return HDF_ERR_INVALID_PARAM; + } + mmc->device.magic = mmc->cntlr->device.magic + MMC_CNTLR_NR_MAX; + + if (MmcCntlrGet(mmc->cntlr) == NULL) { + return HDF_PLT_ERR_DEV_GET; + } + + mmc->device.manager = PlatformManagerGet(PLATFORM_MODULE_MMC); + ret = PlatformDeviceAdd(&mmc->device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcDeviceAdd: mmc device add fail"); + MmcCntlrPut(mmc->cntlr); + return ret; + } + + if (mmc->type == MMC_DEV_EMMC || mmc->type == MMC_DEV_SD || mmc->type == MMC_DEV_COMBO) { + ret = MmcBlockAdd(mmc); + if (ret != HDF_SUCCESS) { + MmcCntlrPut(mmc->cntlr); + PlatformDeviceDel(&mmc->device); + return ret; + } + } + return HDF_SUCCESS; +} + +void MmcDeviceRemove(struct MmcDevice *mmc) +{ + if (mmc == NULL) { + return; + } + if (mmc->type == MMC_DEV_EMMC || mmc->type == MMC_DEV_SD || mmc->type == MMC_DEV_COMBO) { + MmcBlockDel(mmc); + } + PlatformDeviceDel(&mmc->device); + MmcCntlrPut(mmc->cntlr); +} + +struct MmcDevice *MmcDeviceGet(struct MmcDevice *mmc) +{ + if (mmc == NULL) { + return NULL; + } + + if (PlatformDeviceGet(&mmc->device) == NULL) { + HDF_LOGE("MmcDeviceAdd: get device ref fail!"); + return NULL; + } + return mmc; +} + +void MmcDevicePut(struct MmcDevice *mmc) +{ + if (mmc == NULL) { + return; + } + PlatformDevicePut(&mmc->device); +} + +void MmcDeviceAddOps(struct MmcDevice *mmc, void *ops) +{ + if (mmc->type >= MMC_DEV_INVALID) { + HDF_LOGE("MmcDeviceAddOps: dev type error!"); + return; + } + + if (mmc->type == MMC_DEV_SDIO || mmc->type == MMC_DEV_COMBO) { + SdioDeviceAddOps((struct SdioDevice *)mmc, ops); + return; + } + + if (mmc->type == MMC_DEV_EMMC) { + EmmcDeviceAddOps((struct EmmcDevice *)mmc, ops); + } +} + +static void MmcDeviceFillRwInfo(struct MmcRwData *info, uint8_t *buf, + bool writeFlag, size_t startSec, size_t nSec) +{ + info->buf = buf; + info->writeFlag = writeFlag; + info->startSector = startSec; + info->sectors = nSec; +} + +ssize_t MmcDeviceRead(struct MmcDevice *mmc, uint8_t *buf, size_t startSec, size_t nSec) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + struct MmcRwData info = {0}; + size_t curSec = nSec; + size_t curStartSec = startSec; + size_t readSec; + ssize_t ret; + + if (mmc == NULL) { + HDF_LOGE("MmcDeviceRead: mmc is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (buf == NULL) { + HDF_LOGE("MmcDeviceRead: buf is null!"); + return HDF_ERR_INVALID_PARAM; + } + + do { + if (curSec >= MMC_MAX_SECTOR_NUM) { + readSec = MMC_MAX_SECTOR_NUM; + } else { + readSec = curSec; + } + MmcDeviceFillRwInfo(&info, buf, false, curStartSec, readSec); + if (mmc->cntlr->detecting == true) { + ret = MmcSendReadWriteBlocks(mmc->cntlr, &info); + } else { + cmd.data = &data; + MmcSetupReadWriteBlocksCmd(mmc, &cmd, &info); + ret = MmcCntlrAddRequestMsgToQueue(mmc->cntlr, &cmd); + } + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcDeviceRead: fail!"); + return ret; + } + curSec -= readSec; + curStartSec += readSec; + buf += (readSec * BYTES_PER_BLOCK); + } while (curSec > 0); + + return nSec; +} + +ssize_t MmcDeviceWrite(struct MmcDevice *mmc, uint8_t *buf, size_t startSec, size_t nSec) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + struct MmcRwData info = {0}; + size_t curSec = nSec; + size_t curStartSec = startSec; + size_t writeSec; + ssize_t ret; + + if (mmc == NULL) { + HDF_LOGE("MmcDeviceWrite: mmc is null!"); + return HDF_ERR_INVALID_OBJECT; + } + if (buf == NULL) { + HDF_LOGE("MmcDeviceWrite: buf is null!"); + return HDF_ERR_INVALID_PARAM; + } + + do { + if (curSec >= MMC_MAX_SECTOR_NUM) { + writeSec = MMC_MAX_SECTOR_NUM; + } else { + writeSec = curSec; + } + MmcDeviceFillRwInfo(&info, buf, true, curStartSec, writeSec); + if (mmc->cntlr->detecting == true) { + ret = MmcSendReadWriteBlocks(mmc->cntlr, &info); + } else { + cmd.data = &data; + MmcSetupReadWriteBlocksCmd(mmc, &cmd, &info); + ret = MmcCntlrAddRequestMsgToQueue(mmc->cntlr, &cmd); + } + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcDeviceWrite: fail!"); + return ret; + } + curSec -= writeSec; + curStartSec += writeSec; + buf += (writeSec * BYTES_PER_BLOCK); + } while (curSec > 0); + + return nSec; +} + +ssize_t MmcDeviceErase(struct MmcDevice *mmc, size_t startSec, size_t nSec) +{ + size_t curSec = nSec; + size_t curStartSec = startSec; + size_t eraseSec; + ssize_t ret; + + if (mmc == NULL) { + HDF_LOGE("MmcDeviceErase: mmc is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + do { + if (curSec > MMC_MAX_ERASE_SECTOR) { + eraseSec = MMC_MAX_ERASE_SECTOR; + } else { + eraseSec = curSec; + } + ret = MmcSendErase(mmc->cntlr, curStartSec, eraseSec); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcDeviceErase: fail!"); + return ret; + } + curSec -= eraseSec; + curStartSec += eraseSec; + } while (curSec > 0); + + return HDF_SUCCESS; +} diff --git a/support/platform/src/mmc/mmc_dispatch.c b/support/platform/src/mmc/mmc_dispatch.c new file mode 100644 index 00000000..2013b8ab --- /dev/null +++ b/support/platform/src/mmc/mmc_dispatch.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "mmc_dispatch.h" +#include "hdf_log.h" +#include "mmc_corex.h" +#include "mmc_emmc.h" +#include "mmc_sdio.h" + +static int32_t MmcCmdDevPresent(struct MmcCntlr *cntlr, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)data; + if (reply == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufWriteUint8(reply, MmcCntlrDevPresent(cntlr))) { + HDF_LOGE("MmcCmdDevPresent: write reply sbuf fail!"); + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t MmcDispatch(struct MmcCntlr *cntlr, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + + switch (cmd) { + case MMC_CMD_DEV_PRESENT: + ret = MmcCmdDevPresent(cntlr, data, reply); + break; + default: + ret = HDF_ERR_NOT_SUPPORT; + break; + } + return ret; +} + +static int32_t EmmcCmdGetCid(struct MmcCntlr *cntlr, struct HdfSBuf *reply) +{ + int32_t ret; + uint8_t cid[EMMC_CID_LEN] = {0}; + + if (reply == NULL || cntlr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + ret = EmmcDeviceGetCid((struct EmmcDevice *)cntlr->curDev, cid, EMMC_CID_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcCmdGetCid: get cid fail!"); + return ret; + } + + if (HdfSbufWriteBuffer(reply, cid, EMMC_CID_LEN) == false) { + HDF_LOGE("MmcCmdGetCid: write back cid fail!"); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +static int32_t EmmcDispatch(struct MmcCntlr *cntlr, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + (void)data; + + switch (cmd) { + case EMMC_CMD_GET_CID: + ret = EmmcCmdGetCid(cntlr, reply); + break; + default: + ret = HDF_ERR_NOT_SUPPORT; + break; + } + return ret; +} + +static int32_t SdioDispatch(struct MmcCntlr *cntlr, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)cntlr; + (void)cmd; + (void)data; + (void)reply; + return HDF_ERR_NOT_SUPPORT; +} + +int32_t MmcIoDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + struct MmcCntlr *cntlr = NULL; + + if (client == NULL || client->device == NULL) { + HDF_LOGE("MmcIoDispatch: client or hdf dev obj is NULL"); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = (struct MmcCntlr *)client->device->service; + if (cntlr == NULL) { + HDF_LOGE("MmcIoDispatch: service is NULL"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cmd < MMC_CMD_MAX) { + ret = MmcDispatch(cntlr, cmd, data, reply); + } else if (cmd < EMMC_CMD_MAX) { + ret = EmmcDispatch(cntlr, cmd, data, reply); + } else if (cmd < SDIO_CMD_MAX) { + ret = SdioDispatch(cntlr, cmd, data, reply); + } else { + ret = HDF_ERR_NOT_SUPPORT; + } + + return ret; +} diff --git a/support/platform/src/mmc/mmc_emmc.c b/support/platform/src/mmc/mmc_emmc.c new file mode 100644 index 00000000..e4495e3c --- /dev/null +++ b/support/platform/src/mmc/mmc_emmc.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "mmc_emmc.h" +#include "securec.h" + +#define HDF_LOG_TAG mmc_emmc_c + +static int32_t EmmcDeviceDefaultGetCid(struct EmmcDevice *dev, uint8_t *cid, uint32_t len) +{ + struct MmcDevice *mmc = (struct MmcDevice *)dev; + + if (memcpy_s(cid, sizeof(uint8_t) * len, (uint8_t *)(mmc->reg.rawCid), + sizeof(mmc->reg.rawCid)) != EOK) { + HDF_LOGE("EmmcDeviceDefaultGetCid: memcpy_s fail, size = %d!", len); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static struct EmmcDeviceOps g_emmcOps = { + .getCid = EmmcDeviceDefaultGetCid, +}; + +int32_t EmmcDeviceGetCid(struct EmmcDevice *dev, uint8_t *cid, uint32_t len) +{ + if (dev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (cid == NULL || len == 0) { + return HDF_ERR_INVALID_PARAM; + } + if (dev->emmcOps == NULL || dev->emmcOps->getCid == NULL) { + HDF_LOGE("EmmcDeviceGetCid: ops or getCid is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + return dev->emmcOps->getCid(dev, cid, len); +} + +void EmmcDeviceAddOps(struct EmmcDevice *dev, void *ops) +{ + if (dev == NULL) { + HDF_LOGE("EmmcDeviceAddOps: dev is NULL."); + return; + } + if (ops == NULL) { + dev->emmcOps = &g_emmcOps; + HDF_LOGD("EmmcDeviceAddOps: use default ops."); + } else { + dev->emmcOps = (struct EmmcDeviceOps *)ops; + } +} diff --git a/support/platform/src/mmc/mmc_if.c b/support/platform/src/mmc/mmc_if.c new file mode 100644 index 00000000..8b37d0d7 --- /dev/null +++ b/support/platform/src/mmc/mmc_if.c @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "mmc_if.h" +#ifndef __USER__ +#include "devsvc_manager_clnt.h" +#include "mmc_corex.h" +#endif +#include "hdf_base.h" +#ifdef __USER__ +#include "hdf_io_service_if.h" +#endif +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_LOG_TAG mmc_if_c + +#define MMC_SVC_NAME_LEN 32 + +static void *MmcCntlrObjGetByNumber(int16_t id) +{ + void *object = NULL; + char *serviceName = NULL; + + if (id < 0) { + HDF_LOGE("MmcCntlrObjGetByNumber: invalid id:%d", id); + return NULL; + } + serviceName = OsalMemCalloc(MMC_SVC_NAME_LEN + 1); + if (serviceName == NULL) { + HDF_LOGE("MmcCntlrObjGetByNumber: OsalMemCalloc fail!"); + return NULL; + } + if (snprintf_s(serviceName, MMC_SVC_NAME_LEN + 1, MMC_SVC_NAME_LEN, + "HDF_PLATFORM_MMC_%d", id) < 0) { + HDF_LOGE("MmcCntlrObjGetByNumber: format service name fail!"); + goto __ERR; + } + +#ifdef __USER__ + object = (void *)HdfIoServiceBind(serviceName); +#else + object = (void *)MmcCntlrGetByNr(id); +#endif + if (object == NULL) { + HDF_LOGE("MmcCntlrObjGetByNumber: get service fail!"); + } else { + HDF_LOGD("MmcCntlrObjGetByNumber: success"); + } + +__ERR: + OsalMemFree(serviceName); + return object; +} + +DevHandle MmcOpen(int16_t id) +{ + return (DevHandle)MmcCntlrObjGetByNumber(id); +} + +void MmcClose(DevHandle handle) +{ + if (handle != NULL) { +#ifdef __USER__ + HdfIoServiceRecycle((struct HdfIoService *)handle); +#endif + } +} + +bool MmcDevPresent(DevHandle handle) +{ + if (handle == NULL) { + return false; + } +#ifdef __USER__ + int32_t ret; + uint8_t present = 0; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = (struct HdfIoService *)handle; + + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + HDF_LOGE("MmcDevPresent: failed to obtain reply!"); + return false; + } + + if (service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("MmcDevPresent: dispatcher or Dispatch is NULL!"); + goto __EXIT; + } + ret = service->dispatcher->Dispatch(&service->object, MMC_CMD_DEV_PRESENT, + NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("MmcDevPresent: failed to send service call:%d", ret); + goto __EXIT; + } + + if (HdfSbufReadUint8(reply, &present) == false) { + HDF_LOGE("MmcDevPresent: read present fail!"); + goto __EXIT; + } +__EXIT: + HdfSBufRecycle(reply); + return (present != 0); +#else + return MmcCntlrDevPresent((struct MmcCntlr *)handle); +#endif +} diff --git a/support/platform/src/mmc/mmc_protocol.c b/support/platform/src/mmc/mmc_protocol.c new file mode 100644 index 00000000..304c3e12 --- /dev/null +++ b/support/platform/src/mmc/mmc_protocol.c @@ -0,0 +1,4119 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "mmc_emmc.h" +#include "mmc_sd.h" +#include "mmc_sdio.h" +#include "securec.h" + +#define HDF_LOG_TAG mmc_protocol_c + +#define INIT_CMD_RETRY_TIMES 100 +#define MMC_CMD_DEFAULT_RETRY_TIMES 3 +#define SEND_STATUS_CMD_RETRY_TIMES 100 +#define STOP_TRANSMISSION_CMD_RETRY_TIMES 5 +#define BITS_NUMBER_OF_4_BYTES 32 + +/* TRAN_SPEED: Frequency unit 0 = 100KHz, 1 = 1MHz, 2 = 10MHz, 3 = 100MHz, 4...7 = reserved */ +uint32_t g_tranSpeedUnit[] = { 10000, 100000, 1000000, 10000000, 0, 0, 0, 0 }; + +/* TAAC: Time unit 0 = 1ns, 1 = 10ns, 2 = 100ns, 3 = 1us, 4 = 10us, 5 = 100us, 6 = 1ms, 7 = 10ms */ +uint32_t g_taccUnit[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; + +/* + * TRAN_SPEED/TAAC: Multiplier factor 0 = reserved, 1 = 1.0, 2 = 1.2, 3 = 1.3, 4 = 1.5, 5 = 2.0, 6 = 2.5, + * 7 = 3.0, 8 = 3.5, 9 = 4.0, A = 4.5, B = 5.0, C = 5.5, D = 6.0, E = 7.0, F = 8.0 + */ +uint32_t g_commFactor[] = { 0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80 }; + +/* Little-endian and Big-endian interconversion. */ +static uint32_t MmcEndianConversion(uint32_t x) +{ + uint32_t val = x; + + return (uint32_t)( + (((uint32_t)(val) & (uint32_t)0x000000ffUL) << 24) | + (((uint32_t)(val) & (uint32_t)0x0000ff00UL) << 8) | + (((uint32_t)(val) & (uint32_t)0x00ff0000UL) >> 8) | + (((uint32_t)(val) & (uint32_t)0xff000000UL) >> 24)); +} + +/* Decoding algorithm */ +static uint32_t MmcParseBits(uint32_t *data, uint32_t bitsLen, uint32_t start, uint32_t size) +{ + uint32_t index; + uint32_t shift; + uint32_t ret; + + if (start >= bitsLen || size == 0) { + HDF_LOGE("MmcParseBits: input invalid!"); + return 0; + } + if (size > BITS_NUMBER_OF_4_BYTES) { + HDF_LOGE("MmcParseBits: not support!"); + return 0; + } + + index = (bitsLen / BITS_NUMBER_OF_4_BYTES) - (start / BITS_NUMBER_OF_4_BYTES) - 1; + shift = start & (BITS_NUMBER_OF_4_BYTES - 1); + ret = data[index] >> shift; + if (size + shift > BITS_NUMBER_OF_4_BYTES) { + ret |= data[index - 1] << (BITS_NUMBER_OF_4_BYTES - shift); + } + + if (size < BITS_NUMBER_OF_4_BYTES) { + return (ret & ((1u << size) - 1)); + } + return (ret & 0xFFFFFFFF); +} + +static int32_t MmcSendCmd(struct MmcCntlr *cntlr, struct MmcCmd *cmd, struct MmcData *data, uint32_t retryTimes) +{ + uint32_t i; + int32_t ret; + + if (cntlr == NULL || cmd == NULL || retryTimes == 0) { + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->ops == NULL || cntlr->ops->request == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + cmd->data = data; + for (i = 0; i < retryTimes; i++) { + ret = MmcCntlrDoRequest(cntlr, cmd); + if (ret != HDF_SUCCESS) { + continue; + } + if (cmd->returnError != HDF_SUCCESS) { + continue; + } + if (data != NULL && data->returnError != HDF_SUCCESS) { + continue; + } + break; + } + if (data == NULL) { + return cmd->returnError; + } + if (cmd->returnError != HDF_SUCCESS) { + return cmd->returnError; + } + if (data->returnError != HDF_SUCCESS) { + return data->returnError; + } + return HDF_SUCCESS; +} + +static void MmcGoIdleState(struct MmcCntlr *cntlr) +{ + struct MmcCmd cmd = {0}; + + /* Command GO_IDLE_STATE (CMD0) is the software reset command and sets all cards into Idle State. */ + cmd.cmdCode = GO_IDLE_STATE; + /* [31:0] stuff bits. */ + cmd.argument = 0; + /* Broadcast Commands (bc), no response. */ + cmd.respType = MMC_RESP_SPI_R1 | MMC_RESP_NONE | MMC_CMD_TYPE_BC; + (void)MmcSendCmd(cntlr, &cmd, NULL, 1); + OsalMDelay(1); +} + +static int32_t MmcSendOpCond(struct MmcCntlr *cntlr, uint32_t arg, uint32_t *ocr) +{ + struct MmcCmd cmd = {0}; + int32_t err; + uint32_t i; + + /* + * The SEND_OP_COND (CMD1) command is designed to provide MultiMediaCard hosts with a mechanism + * to identify and reject cards which do not match the VDD range desired by the host. + */ + cmd.cmdCode = SEND_OP_COND; + /* [31:0] OCR. */ + cmd.argument = arg; + cmd.respType = MMC_RESP_SPI_R1 | MMC_RESP_R3 | MMC_CMD_TYPE_BCR; + /* + * The host must poll the card (by repeatedly sending CMD1 or ACMD41) until the 'in-idle-state' bit in + * the card response indicates (by being set to 0) that the card completed its initialization processes + * and is ready for the next command. + */ + for (i = 0; i < INIT_CMD_RETRY_TIMES; i++) { + err = MmcSendCmd(cntlr, &cmd, NULL, 1); + if (err != HDF_SUCCESS) { + break; + } + if (arg == 0 || (cmd.resp[0] & MMC_CARD_BUSY_STATUS) > 0) { + break; + } + + err = HDF_ERR_TIMEOUT; + OsalMDelay(10); + } + + if (ocr != NULL) { + *ocr = cmd.resp[0]; + } + return err; +} + +static int32_t MmcAllSendCid(struct MmcCntlr *cntlr) +{ + struct MmcCmd cmd = {0}; + uint32_t *cid = NULL; + int32_t err; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = ALL_SEND_CID; + /* [31:0] stuff bits. */ + cmd.argument = 0; + /* Broadcast Commands with Response(bcr). */ + cmd.respType = MMC_RESP_R2 | MMC_CMD_TYPE_BCR; + err = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (err != HDF_SUCCESS) { + return err; + } + cid = cntlr->curDev->reg.rawCid; + if (memcpy_s(cid, sizeof(cntlr->curDev->reg.rawCid), cmd.resp, sizeof(cmd.resp)) != EOK) { + HDF_LOGE("MmcAllSendCid: memcpy_s fail!"); + return HDF_FAILURE; + } + return err; +} + +static int32_t MmcSetRelativeAddr(struct MmcCntlr *cntlr) +{ + struct MmcCmd cmd = {0}; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = SET_RELATIVE_ADDR; + /* [31:16] RCA, [15:0] stuff bits. */ + cmd.argument = (cntlr->curDev->reg.rca << 16); + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + return MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); +} + +static int32_t MmcSelectCard(struct MmcCntlr *cntlr) +{ + struct MmcCmd cmd = {0}; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = SELECT_CARD; + /* [31:16] RCA, [15:0] stuff bits. */ + cmd.argument = (cntlr->curDev->reg.rca << 16); + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + return MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); +} + +static int32_t MmcSendExtCsd(struct MmcCntlr *cntlr, uint8_t *extCsd, uint32_t len) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + + cmd.cmdCode = SEND_EXT_CSD; + cmd.argument = 0; + cmd.respType = MMC_RESP_SPI_R1 | MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + + /* The card sends the EXT_CSD register as a block of data, 512 bytes long. */ + data.blockSize = len; + data.blockNum = 1; + data.dataFlags = DATA_READ; + data.dataBuffer = extCsd; + + return MmcSendCmd(cntlr, &cmd, &data, 1); +} + +static int32_t MmcSendCsd(struct MmcCntlr *cntlr) +{ + struct MmcCmd cmd = {0}; + uint32_t *csd = NULL; + int32_t err; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = SEND_CSD; + cmd.argument = (cntlr->curDev->reg.rca << 16); + cmd.respType = MMC_RESP_R2 | MMC_CMD_TYPE_AC; + err = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (err != HDF_SUCCESS) { + return err; + } + csd = cntlr->curDev->reg.rawCsd; + if (memcpy_s(csd, sizeof(cntlr->curDev->reg.rawCsd), cmd.resp, sizeof(cmd.resp)) != EOK) { + HDF_LOGE("memcpy_s fail!"); + return HDF_FAILURE; + } + return err; +} + +int32_t MmcSendStatus(struct MmcCntlr *cntlr, uint32_t *status) +{ + struct MmcCmd cmd = {0}; + int32_t error; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = SEND_STATUS; + /* [31:16] RCA, [15:0] stuff bits. */ + cmd.argument = (cntlr->curDev->reg.rca << 16); + cmd.respType = MMC_RESP_SPI_R2 | MMC_RESP_R1 | MMC_CMD_TYPE_AC; + error = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (error != HDF_SUCCESS) { + return error; + } + if (status != NULL) { + *status = cmd.resp[0]; + } + return error; +} + +static int32_t MmcSwitch(struct MmcCntlr *cntlr, uint8_t set, uint8_t index, uint8_t value) +{ + int32_t error; + struct MmcCmd cmd = {0}; + uint32_t status; + + cmd.cmdCode = SWITCH; + /* + * [31:26] Set to 0; [25:24] Access; [23:16] Index; + * [15:8] Value; [7:3] Set to 0; [2:0] Cmd Set. + */ + cmd.argument = (EMMC_EXT_CSD_WRITE_BYTE << 24) + | (index << 16) + | (value << 8) + | set; + cmd.respType = MMC_RESP_SPI_R1B | MMC_RESP_R1B | MMC_CMD_TYPE_AC; + error = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (error != HDF_SUCCESS) { + HDF_LOGE("MmcSwitch: send cmd fail!"); + return error; + } + + /* + * The SWITCH command response is of type R1b, therefore, the host should read the card status, using + * SEND_STATUS command, after the busy signal is de-asserted, to check the result of the SWITCH operation. + */ + do { + error = MmcSendStatus(cntlr, &status); + if (error != HDF_SUCCESS) { + HDF_LOGE("MmcSwitch: send status cmd fail!"); + return error; + } + } while ((!(status & READY_FOR_DATA)) || MmcCntlrDevBusy(cntlr) == true); + + /* + * When the host tries to access a partition which has not been created before, the devices sets the + * SWITCH_ERROR bit in the status register and will not change the PARTITION_ACCESS bits. + */ + if ((status & SWITCH_ERROR) > 0) { + return HDF_MMC_ERR_SWITCH_FAIL; + } + return error; +} + +static int32_t MmcAppCmd(struct MmcCntlr *cntlr, uint32_t acmd) +{ + int32_t err; + struct MmcCmd cmd = {0}; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* + * After the bus is activated the host will request the cards to send their valid operation conditions + * (ACMD41 preceding with APP_CMD - CMD55 with RCA = 0x0000). + */ + cmd.cmdCode = APP_CMD; + if (acmd != SD_ACMD_OP_COND) { + /* [31:16] RCA, [15:0] stuff bits */ + cmd.argument = (cntlr->curDev->reg.rca << 16); + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + } else { + cmd.argument = 0; + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_BCR; + } + err = MmcSendCmd(cntlr, &cmd, NULL, 1); + if (err != HDF_SUCCESS) { + return err; + } + if (!(cmd.resp[0] & IS_APP_CMD)) { + return HDF_FAILURE; + } + return err; +} + +static int32_t MmcWaitCardReady(struct MmcCntlr *cntlr) +{ + int error; + uint32_t status; + int32_t retryTimes = SEND_STATUS_CMD_RETRY_TIMES; + + do { + error = MmcSendStatus(cntlr, &status); + if (error != HDF_SUCCESS) { + return error; + } + + if (retryTimes >= 0) { + retryTimes--; + OsalMSleep(10); + } else { + return HDF_ERR_TIMEOUT; + } + } while (!(status & READY_FOR_DATA) || (MMC_CARD_CURRENT_STATE(status) == STATE_PRG)); + return error; +} + +int32_t MmcStopTransmission(struct MmcCntlr *cntlr, bool writeFlag, uint32_t *stopStatus) +{ + int32_t err; + struct MmcCmd cmd = {0}; + + cmd.cmdCode = STOP_TRANSMISSION; + /* R1 for read cases and R1b for write cases. */ + if (writeFlag == true) { + cmd.respType = MMC_RESP_R1B | MMC_CMD_TYPE_AC; + } else { + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + } + err = MmcSendCmd(cntlr, &cmd, NULL, STOP_TRANSMISSION_CMD_RETRY_TIMES); + if (err != HDF_SUCCESS) { + return err; + } + + *stopStatus = cmd.resp[0]; + /* No need to check card status in case of read. */ + if (writeFlag == false) { + return err; + } + return MmcWaitCardReady(cntlr); +} + +int32_t MmcSendTuning(struct MmcCntlr *cntlr, uint32_t cmdCode, bool sendStop) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + /* Tuning Block Pattern UHS-I. */ + uint8_t tuningBlk4bit[] = { + 0xFF, 0x0F, 0xFF, 0x00, 0xFF, 0xCC, 0xC3, 0xCC, 0xC3, 0x3C, 0xCC, 0xFF, + 0xFE, 0xFF, 0xFE, 0xEF, 0xFF, 0xDF, 0xFF, 0xDD, 0xFF, 0xFB, 0xFF, 0xFB, + 0xBF, 0xFF, 0x7F, 0xFF, 0x77, 0xF7, 0xBD, 0xEF, 0xFF, 0xF0, 0xFF, 0xF0, + 0x0F, 0xFC, 0xCC, 0x3C, 0xCC, 0x33, 0xCC, 0xCF, 0xFF, 0xEF, 0xFF, 0xEE, + 0xFF, 0xFD, 0xFF, 0xFD, 0xDF, 0xFF, 0xBF, 0xFF, 0xBB, 0xFF, 0xF7, 0xFF, + 0xF7, 0x7f, 0x7B, 0xDE, + }; + /* Tuning block pattern for 8 bit mode for HS200. */ + uint8_t tuningBlk8bit[] = { + 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xCC, 0xCC, + 0xCC, 0x33, 0xCC, 0xCC, 0xCC, 0x33, 0x33, 0xCC, 0xCC, 0xCC, 0xFF, 0xFF, + 0xFF, 0xEE, 0xFF, 0xFF, 0xFF, 0xEE, 0xEE, 0xFF, 0xFF, 0xFF, 0xDD, 0xFF, + 0xFF, 0xFF, 0xDD, 0xDD, 0xFF, 0xFF, 0xFF, 0xBB, 0xFF, 0xFF, 0xFF, 0xBB, + 0xBB, 0xFF, 0xFF, 0xFF, 0x77, 0xFF, 0xFF, 0xFF, 0x77, 0x77, 0xFF, 0x77, + 0xBB, 0xDD, 0xEE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, + 0x00, 0xFF, 0xFF, 0xCC, 0xCC, 0xCC, 0x33, 0xCC, 0xCC, 0xCC, 0x33, 0x33, + 0xCC, 0xCC, 0xCC, 0xFF, 0xFF, 0xFF, 0xEE, 0xFF, 0xFF, 0xFF, 0xEE, 0xEE, + 0xFF, 0xFF, 0xFF, 0xDD, 0xFF, 0xFF, 0xFF, 0xDD, 0xDD, 0xFF, 0xFF, 0xFF, + 0xBB, 0xFF, 0xFF, 0xFF, 0xBB, 0xBB, 0xFF, 0xFF, 0xFF, 0x77, 0xFF, 0xFF, + 0xFF, 0x77, 0x77, 0xFF, 0x77, 0xBB, 0xDD, 0xEE, + }; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.cmdCode = cmdCode; + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + + if (cntlr->curDev->workPara.width == BUS_WIDTH4) { + data.blockSize = sizeof(tuningBlk4bit); + data.dataBuffer = tuningBlk4bit; + } else if (cntlr->curDev->workPara.width == BUS_WIDTH8) { + data.blockSize = sizeof(tuningBlk8bit); + data.dataBuffer = tuningBlk8bit; + } else { + HDF_LOGE("MmcSendTuning: work width is 1, can not tune!"); + return HDF_FAILURE; + } + data.blockNum = 1; + data.dataFlags = DATA_READ; + if (sendStop == true) { + data.sendStopCmd = true; + data.stopCmd.cmdCode = STOP_TRANSMISSION; + data.stopCmd.respType = MMC_RESP_R1B | MMC_CMD_TYPE_AC; + } + + return MmcSendCmd(cntlr, &cmd, &data, 1); +} + +static int32_t MmcSendEraseStartCmd(struct MmcCntlr *cntlr, uint32_t arg) +{ + struct MmcCmd cmd = {0}; + struct MmcDevice *dev = cntlr->curDev; + + if (dev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* SD: CMD32; EMMC: CMD35 */ + if (dev->type == MMC_DEV_SD) { + cmd.cmdCode = SD_CMD_ERASE_WR_BLK_START; + } else { + cmd.cmdCode = ERASE_GROUP_START; + } + /* [31:0]data address. */ + cmd.argument = arg; + /* + * Data address for media =<2GB is a 32bit byte address and data address for media > 2GB is + * a 32bit sector (512B) address. + */ + if (dev->state.bits.blockAddr == 0) { + cmd.argument <<= MMC_MAX_BLOCKSIZE_SHIFT; + } + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + return MmcSendCmd(cntlr, &cmd, NULL, 1); +} + +static int32_t MmcSendEraseEndCmd(struct MmcCntlr *cntlr, uint32_t arg) +{ + struct MmcCmd cmd = {0}; + struct MmcDevice *dev = cntlr->curDev; + + if (dev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* SD: CMD33; EMMC: CMD36 */ + if (dev->type == MMC_DEV_SD) { + cmd.cmdCode = SD_CMD_ERASE_WR_BLK_END; + } else { + cmd.cmdCode = ERASE_GROUP_END; + } + /* [31:0]data address. */ + cmd.argument = arg; + /* + * Data address for media =<2GB is a 32bit byte address and data address for media > 2GB is + * a 32bit sector (512B) address. + */ + if (dev->state.bits.blockAddr == 0) { + cmd.argument <<= MMC_MAX_BLOCKSIZE_SHIFT; + } + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + return MmcSendCmd(cntlr, &cmd, NULL, 1); +} + +static int32_t MmcSendEraseCmd(struct MmcCntlr *cntlr, uint32_t arg) +{ + struct MmcCmd cmd = {0}; + struct MmcDevice *dev = cntlr->curDev; + + if (dev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* ERASE cmd38 */ + cmd.cmdCode = MMC_ERASE; + cmd.argument = arg; + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + return MmcSendCmd(cntlr, &cmd, NULL, 1); +} + +static int32_t MmcAlignEraseSize(struct MmcCntlr *cntlr, uint32_t *start, uint32_t *end, uint32_t size) +{ + uint32_t curSize = size; + uint32_t tmp; + + if (cntlr->curDev->eraseSize == 0) { + return HDF_ERR_NOT_SUPPORT; + } + + /* align start. */ + tmp = (*start) % cntlr->curDev->eraseSize; + if (tmp > 0) { + tmp = cntlr->curDev->eraseSize - tmp; + (*start) += tmp; + if (curSize > tmp) { + curSize -= tmp; + } else { + return HDF_ERR_NOT_SUPPORT; + } + } + + /* align size. */ + tmp = curSize % cntlr->curDev->eraseSize; + if (tmp > 0) { + curSize -= tmp; + } + if (curSize == 0) { + return HDF_ERR_NOT_SUPPORT; + } + + (*end) = (*start) + curSize; + return HDF_SUCCESS; +} + +int32_t MmcSendErase(struct MmcCntlr *cntlr, uint32_t startSec, uint32_t nSec) +{ + int32_t ret; + uint32_t start = startSec; + uint32_t end = start + nSec; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->curDev->eraseSize == 0 || + (cntlr->curDev->reg.csd.ccc & MMC_CSD_CCC_ERASE) == 0) { + return HDF_ERR_NOT_SUPPORT; + } + + ret = MmcAlignEraseSize(cntlr, &start, &end, nSec); + if (ret != HDF_SUCCESS) { + /* after align, no need to erase. */ + return HDF_SUCCESS; + } + + /* + * emmc: + * Starting the erase process is a three steps sequence. + * First the host defines the start address of the range using the ERASE_GROUP_START (CMD35) command, + * next it defines the last address of the range using the ERASE_GROUP_END (CMD36) command and + * finally it starts the erase process by issuing the ERASE (CMD38) command with argument bits set to zero. + * sd: + * The host should adhere to the following command sequence: ERASE_WR_BLK_START(cmd32), ERASE_WR_BLK_END(cmd33) + * and ERASE(CMD38). + */ + ret = MmcSendEraseStartCmd(cntlr, start); + if (ret != HDF_SUCCESS) { + HDF_LOGE("send erase start cmd fail, err = %d!", ret); + return ret; + } + + ret = MmcSendEraseEndCmd(cntlr, end); + if (ret != HDF_SUCCESS) { + HDF_LOGE("send erase end cmd fail, err = %d!", ret); + return ret; + } + + ret = MmcSendEraseCmd(cntlr, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("send erase cmd fail, err = %d!", ret); + return ret; + } + + return MmcWaitCardReady(cntlr); +} + +void MmcSetupReadWriteBlocksCmd(struct MmcDevice *mmc, struct MmcCmd *cmd, struct MmcRwData *info) +{ + cmd->data->blockSize = BYTES_PER_BLOCK; + cmd->data->blockNum = info->sectors; + cmd->data->dataBuffer = info->buf; + + cmd->respType = MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + /* [31:0]data address. */ + cmd->argument = info->startSector; + if (mmc->state.bits.blockAddr == 0) { + /* SDSC Card uses byte unit address and SDHC and SDXC Cards use block unit address(512 Bytes unit). */ + cmd->argument <<= MMC_MAX_BLOCKSIZE_SHIFT; + } + if (info->writeFlag == true) { + cmd->data->dataFlags = DATA_WRITE; + cmd->cmdCode = WRITE_BLOCK; + if (info->sectors > 1) { + cmd->cmdCode = WRITE_MULTIPLE_BLOCK; + } + } else { + cmd->data->dataFlags = DATA_READ; + cmd->cmdCode = READ_SINGLE_BLOCK; + if (info->sectors > 1) { + cmd->cmdCode = READ_MULTIPLE_BLOCK; + } + } + if ((info->sectors > 1) && (mmc->cntlr->caps.bits.cmdStop > 0)) { + cmd->data->stopCmd.cmdCode = STOP_TRANSMISSION; + cmd->data->sendStopCmd = true; + } +} + +int32_t MmcSendReadWriteBlocks(struct MmcCntlr *cntlr, struct MmcRwData *info) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + cmd.data = &data; + MmcSetupReadWriteBlocksCmd(cntlr->curDev, &cmd, info); + return MmcSendCmd(cntlr, &cmd, &data, 1); +} + +static int32_t EmmcDecodeCsd(struct MmcCntlr *cntlr) +{ + struct MmcCsd *csd = NULL; + uint32_t unit, factor; + uint32_t *rawCsd = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + rawCsd = cntlr->curDev->reg.rawCsd; + csd = &(cntlr->curDev->reg.csd); + + /* CSD_STRUCTURE: [127:126]. */ + csd->structure = MmcParseBits(rawCsd, CSD_BITS, 126, 2); + if (csd->structure == 0) { + HDF_LOGE("EmmcDecodeCsd: structure is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + /* SPEC_VERS: [125:122]. */ + csd->specVers = MmcParseBits(rawCsd, CSD_BITS, 122, 4); + /* TAAC: [119:112]; TAAC bit position-->Time unit: [2:0], Multiplier factor: [6:3]. */ + factor = MmcParseBits(rawCsd, CSD_BITS, 115, 4); + unit = MmcParseBits(rawCsd, CSD_BITS, 112, 3); + csd->taccNs = (g_taccUnit[unit] * g_commFactor[factor] + 9) / 10; + /* NSAC: [111:104] */ + csd->taccClks = MmcParseBits(rawCsd, CSD_BITS, 104, 8) * 100; + + /* TRAN_SPEED: [103:96]; TRAN_SPEED bit-->Frequency unit: [2:0], Multiplier factor: [6:3]. */ + factor = MmcParseBits(rawCsd, CSD_BITS, 99, 4); + unit = MmcParseBits(rawCsd, CSD_BITS, 96, 3); + csd->maxDtr = g_tranSpeedUnit[unit] * g_commFactor[factor]; + csd->ccc = MmcParseBits(rawCsd, CSD_BITS, 84, 12); + + /* C_SIZE: [73:62] */ + factor = MmcParseBits(rawCsd, CSD_BITS, 62, 12); + /* C_SIZE_MULT: [49:47] */ + unit = MmcParseBits(rawCsd, CSD_BITS, 47, 3); + csd->capacity = (1 + factor) << (unit + 2); + /* READ_BL_LEN: [83:80]. */ + csd->readBlkLen = MmcParseBits(rawCsd, CSD_BITS, 80, 4); + /* READ_BL_PARTIAL: [79:79] */ + csd->rdPartial = MmcParseBits(rawCsd, CSD_BITS, 79, 1); + /* WRITE_BLK_MISALIGN: [78:78] */ + csd->wrMisalign = MmcParseBits(rawCsd, CSD_BITS, 78, 1); + /* READ_BLK_MISALIGN: [77:77] */ + csd->rdMisalign = MmcParseBits(rawCsd, CSD_BITS, 77, 1); + /* Write speed factor(R2W_FACTOR) :[28:26] */ + csd->r2wFactor = MmcParseBits(rawCsd, CSD_BITS, 26, 3); + /* WRITE_BL_LEN: [25:22] */ + csd->writeBlkLen = MmcParseBits(rawCsd, CSD_BITS, 22, 4); + /* WRITE_BL_PARTIAL: [21:21] */ + csd->wrPartial = MmcParseBits(rawCsd, CSD_BITS, 21, 1); + + /* + * Note that the support for 512B read access is mandatory for all cards. + * And that the cards has to be in 512B block length mode by default after power-on, or software reset. + */ + if (csd->writeBlkLen >= MMC_MAX_BLOCKSIZE_SHIFT) { + /* ERASE_GRP_SIZE: [46:42] */ + unit = MmcParseBits(rawCsd, CSD_BITS, 42, 5); + /* ERASE_GRP_MULT: [41:37] */ + factor = MmcParseBits(rawCsd, CSD_BITS, 37, 5); + /* size of erasable unit = (ERASE_GRP_SIZE + 1) * (ERASE_GRP_MULT + 1) */ + csd->eraseSize = (unit + 1) * (factor + 1); + csd->eraseSize <<= (csd->writeBlkLen - MMC_MAX_BLOCKSIZE_SHIFT); + } + return HDF_SUCCESS; +} + +static int32_t EmmcDecodeCid(struct MmcCntlr *cntlr) +{ + uint32_t i; + struct MmcCid *cid = NULL; + uint32_t *rawCid = NULL; + uint8_t specVers, cbx; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + rawCid = cntlr->curDev->reg.rawCid; + cid = &(cntlr->curDev->reg.cid); + specVers = cntlr->curDev->reg.csd.specVers; + if (specVers > MMC_CSD_SPEC_VER_4) { + HDF_LOGE("EmmcDecodeCid: specVers is invalid!"); + return HDF_ERR_NOT_SUPPORT; + } + + /* + * The manufacturing date is composed of two hexadecimal digits, four bits each, + * representing a two digits date code m/y; + */ + cid->month = MmcParseBits(rawCid, CID_BITS, 12, 4); + /* The "y" field, least significant nibble, is the year code. 0 is 1997. */ + cid->year = MmcParseBits(rawCid, CID_BITS, 8, 4) + 1997; + + if (specVers == MMC_CSD_SPEC_VER_0 || specVers == MMC_CSD_SPEC_VER_1) { + cid->mid = MmcParseBits(rawCid, CID_BITS, 104, 24); + for (i = 0; i < 7; i++) { + cid->pnm[i] = MmcParseBits(rawCid, CID_BITS, 96 - (i * 8), 8); + } + cid->pnm[7] = '\0'; + cid->hwPrv = MmcParseBits(rawCid, CID_BITS, 44, 4); + cid->fwPrv = MmcParseBits(rawCid, CID_BITS, 40, 4); + cid->psn = MmcParseBits(rawCid, CID_BITS, 16, 24); + } else { + /* Manufacturer ID(MID): [127:120] */ + cid->mid = MmcParseBits(rawCid, CID_BITS, 120, 8); + /* OEM/Application ID(OID): [119:104] */ + cid->oid = MmcParseBits(rawCid, CID_BITS, 104, 16); + /* Product name(PNM): [103:56] */ + for (i = 0; i < 6; i++) { + cid->pnm[i] = MmcParseBits(rawCid, CID_BITS, 96 - (i * 8), 8); + } + cid->pnm[6] = '\0'; + /* Product serial number(PSN): [47:16] */ + cid->psn = MmcParseBits(rawCid, CID_BITS, 16, 32); + /* + * Card or BGA(CBX): [113:112] + * 00: Card (removable); 01: BGA (Discrete embedded); 10: POP; 11: Reserved. + */ + cbx = MmcParseBits(rawCid, CID_BITS, 112, 2); + if (cbx == 0) { + cntlr->curDev->state.bits.removeable = 1; + HDF_LOGD("Emmc is removeable!"); + } + } + return HDF_SUCCESS; +} + +static void EmmcDecodeExtCsdSector(struct EmmcDevice *emmcDev, struct EmmcExtCsd *extCsd) +{ + uint32_t i; + uint32_t shift = 0; + + extCsd->sectors = 0; + for (i = 0; i < EMMC_EXT_CSD_SEC_CNT_BYTES; i++) { + extCsd->sectors |= (uint32_t)(extCsd->rawSectors[i] << shift); + shift += BITS_PER_BYTE; + } + /* Device density > 2GiB are sector addressed. */ + if (extCsd->sectors > (2u * 1024 * 1024 * 1024) / 512) { + emmcDev->mmc.state.bits.blockAddr = 1; + } +} + +static void EmmcDecodeExtCsdCardType(struct EmmcExtCsd *extCsd) +{ + uint8_t cardType = extCsd->rawCardType & EMMC_EXT_CSD_CARD_TYPE_MASK; + + switch (cardType) { + case EMMC_EXT_CSD_CARD_TYPE_SDR_ALL: + case EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_1_8V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_1_2V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_ALL_DDR_52: + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_200; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_SDR_200; + break; + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_1_8V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_1_2V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V_ALL_DDR_52: + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_200; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V; + break; + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_1_8V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_1_2V: + case EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V_ALL_DDR_52: + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_200; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V; + break; + case (EMMC_EXT_CSD_CARD_TYPE_DDR_52 | EMMC_EXT_CSD_CARD_TYPE_52 | EMMC_EXT_CSD_CARD_TYPE_26): + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_52; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_DDR_52; + break; + case (EMMC_EXT_CSD_CARD_TYPE_DDR_1_2V | EMMC_EXT_CSD_CARD_TYPE_52 | EMMC_EXT_CSD_CARD_TYPE_26): + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_52; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_DDR_1_2V; + break; + case (EMMC_EXT_CSD_CARD_TYPE_DDR_1_8V | EMMC_EXT_CSD_CARD_TYPE_52 | EMMC_EXT_CSD_CARD_TYPE_26): + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_52; + extCsd->cardType = EMMC_EXT_CSD_CARD_TYPE_DDR_1_8V; + break; + case (EMMC_EXT_CSD_CARD_TYPE_52 | EMMC_EXT_CSD_CARD_TYPE_26): + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_52; + break; + case EMMC_EXT_CSD_CARD_TYPE_26: + extCsd->hsMaxDtr = EMMC_EXT_CSD_HIGH_SPEED_26; + break; + default: + HDF_LOGD("EmmcDecodeExtCsdCardType: not support high-speed!"); + break; + } +} + +static void EmmcDecodeExtCsdRev13Field(struct EmmcExtCsd *extCsd, uint8_t *rawExtCsd) +{ + uint8_t shift = rawExtCsd[EMMC_EXT_CSD_S_A_TIMEOUT]; + + extCsd->eraseGroupDef = rawExtCsd[EMMC_EXT_CSD_ERASE_GROUP_DEF]; + extCsd->partConfig = rawExtCsd[EMMC_EXT_CSD_PARTITION_CONFIG]; + extCsd->partSwitchTime = 10 * rawExtCsd[EMMC_EXT_CSD_PARTITION_SWITCH_TIME]; + + if (shift > 0 && shift <= MAX_S_A_TIMEOUT_VALUE) { + extCsd->saTimeout = 1 << shift; + } + extCsd->relWrSecorCount = rawExtCsd[EMMC_EXT_CSD_REL_WR_SEC_C]; + extCsd->hcEraseTimeout = 300 * rawExtCsd[EMMC_EXT_CSD_ERASE_TIMEOUT_MULT]; + extCsd->hcEraseSize = (extCsd->rawHcEraseGrpSize) << 10; + extCsd->bootSize = rawExtCsd[EMMC_EXT_CSD_BOOT_MULTI] << 17; +} + +static void EmmcDecodeExtCsdEnhanceArea(struct EmmcDevice *emmcDev, + struct EmmcExtCsd *extCsd, uint8_t *rawExtCsd) +{ + uint32_t i; + uint32_t shift = 0; + + extCsd->enhAreaEnable = true; + extCsd->enhAreaOffset = 0; + for (i = 0; i < EMMC_EXT_CSD_ENH_START_ADDR_BYTES; i++) { + extCsd->enhAreaOffset |= ((uint64_t)rawExtCsd[EMMC_EXT_CSD_ENH_START_ADDR + i] << shift); + shift += BITS_PER_BYTE; + } + /* + * Start address of the Enhanced User Data Area segment in the User Data Area + * (expressedin bytes or in sectors in case of high capacity devices). + */ + if (emmcDev->mmc.state.bits.blockAddr == 1) { + extCsd->enhAreaOffset <<= MMC_MAX_BLOCKSIZE_SHIFT; + } + + shift = 0; + extCsd->enhAreaSize = 0; + for (i = 0; i < EMMC_EXT_CSD_ENH_SIZE_MULT_BYTES; i++) { + extCsd->enhAreaSize |= (rawExtCsd[EMMC_EXT_CSD_ENH_SIZE_MULT + i] << shift); + shift += BITS_PER_BYTE; + } + /* Max Enhanced Area = MAX_ENH_SIZE_MULT * HC_WP_GRP_SIZE * HC_ERASE_GPR_SIZE * 512kBytes */ + extCsd->enhAreaSize *= (uint32_t)(extCsd->rawHcEraseGrpSize * rawExtCsd[EMMC_EXT_CSD_HC_WP_GRP_SIZE]); + extCsd->enhAreaSize <<= MMC_MAX_BLOCKSIZE_SHIFT; +} + +static void EmmcDecodeExtCsdPowerClassValue(struct EmmcExtCsd *extCsd, uint8_t *rawExtCsd) +{ + extCsd->pwrClF52V195 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_52_195]; + extCsd->pwrClF26V195 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_26_195]; + extCsd->pwrClF52V360 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_52_360]; + extCsd->pwrClF26V360 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_26_360]; + extCsd->pwrClF200V195 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_200_195]; + extCsd->pwrClF200V360 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_200_360]; + extCsd->pwrClDdrF52V195 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_DDR_52_195]; + extCsd->pwrClDdrF52V360 = rawExtCsd[EMMC_EXT_CSD_PWR_CL_DDR_52_360]; +} + +static void EmmcDecodeExtCsdRev14Field(struct EmmcDevice *emmcDev, + struct EmmcExtCsd *extCsd, uint8_t *rawExtCsd) +{ + if ((rawExtCsd[EMMC_EXT_CSD_PARTITIONING_SUPPORT] & PARTITIONING_SUPPORT_ENH_ATTRIBUTE_EN) > 0 && + (rawExtCsd[EMMC_EXT_CSD_PARTITIONS_ATTRIBUTE] & PARTITIONS_ATTRIBUTE_ENH_USR) > 0) { + EmmcDecodeExtCsdEnhanceArea(emmcDev, extCsd, rawExtCsd); + } + extCsd->secTrimMult = extCsd->rawSecTrimMult; + extCsd->secEraseMult = extCsd->rawSecEraseMult; + /* TRIM Timeout = 300ms x TRIM_MULT. */ + extCsd->trimTimeout = 300 * extCsd->rawTrimMult; + EmmcDecodeExtCsdPowerClassValue(extCsd, rawExtCsd); +} + +static void EmmcDecodeExtCsdRev15Field(struct EmmcExtCsd *extCsd, uint8_t *rawExtCsd) +{ + /* whether the eMMC card supports HPI. */ + if ((rawExtCsd[EMMC_EXT_CSD_HPI_FEATURES] & EMMC_EXT_CSD_HPI_SUPPORT) > 0) { + extCsd->hpi = true; + if ((rawExtCsd[EMMC_EXT_CSD_HPI_FEATURES] & EMMC_EXT_CSD_HPI_IMPLEMENTATION) > 0) { + extCsd->hpiCmd = STOP_TRANSMISSION; + } else { + extCsd->hpiCmd = SEND_STATUS; + } + /* + * This field indicates the maximum timeout to close a command interrupted by HPI –time between the end + * bit of CMD12/13 to the DAT0 release by the device. + * Time is expressed in units of 10-milliseconds. + */ + extCsd->outOfInterruptTime = rawExtCsd[EMMC_EXT_CSD_OUT_OF_INTERRUPT_TIME] * 10; + } + extCsd->wrRelParam = rawExtCsd[EMMC_EXT_CSD_WR_REL_PARAM]; +} + +static int32_t EmmcDecodeExtCsd(struct MmcCntlr *cntlr, uint8_t *rawExtCsd, uint32_t len) +{ + struct EmmcDevice *emmcDev = (struct EmmcDevice *)cntlr->curDev; + struct EmmcExtCsd *extCsd = &(emmcDev->emmcReg.extCsd); + uint32_t i; + + extCsd->rawCsdStructure = rawExtCsd[EMMC_EXT_CSD_STRUCTURE]; + if (emmcDev->mmc.reg.csd.structure == MMC_CSD_STRUCTURE_VER_OTHER) { + if (extCsd->rawCsdStructure > EMMC_EXT_CSD_STRUCTURE_VER_1_2) { + HDF_LOGE("EmmcDecodeExtCsd: rawCsdStructure is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + } + extCsd->rev = rawExtCsd[EMMC_EXT_CSD_REV]; + for (i = 0; i < EMMC_EXT_CSD_SEC_CNT_BYTES; i++) { + extCsd->rawSectors[i] = rawExtCsd[EMMC_EXT_CSD_SEC_CNT + i]; + } + if (extCsd->rev >= EMMC_EXT_CSD_REV_1_2) { + EmmcDecodeExtCsdSector(emmcDev, extCsd); + } + + extCsd->strobeSupport = rawExtCsd[EMMC_EXT_CSD_STROBE_SUPPORT]; + extCsd->rawCardType = rawExtCsd[EMMC_EXT_CSD_CARD_TYPE]; + EmmcDecodeExtCsdCardType(extCsd); + + extCsd->rawSaTimeout = rawExtCsd[EMMC_EXT_CSD_S_A_TIMEOUT]; + extCsd->rawEraseTimeoutMult = rawExtCsd[EMMC_EXT_CSD_ERASE_TIMEOUT_MULT]; + extCsd->rawHcEraseGrpSize = rawExtCsd[EMMC_EXT_CSD_HC_ERASE_GRP_SIZE]; + if (extCsd->rev >= EMMC_EXT_CSD_REV_1_3) { + EmmcDecodeExtCsdRev13Field(extCsd, rawExtCsd); + } + + extCsd->rawSecTrimMult = rawExtCsd[EMMC_EXT_CSD_SEC_TRIM_MULT]; + extCsd->rawSecEraseMult = rawExtCsd[EMMC_EXT_CSD_SEC_ERASE_MULT]; + extCsd->rawSecFeatureSupport = rawExtCsd[EMMC_EXT_CSD_SEC_FEATURE_SUPPORT]; + extCsd->rawTrimMult = rawExtCsd[EMMC_EXT_CSD_TRIM_MULT]; + if (extCsd->rev >= EMMC_EXT_CSD_REV_1_4) { + EmmcDecodeExtCsdRev14Field(emmcDev, extCsd, rawExtCsd); + } + + if (extCsd->rev >= EMMC_EXT_CSD_REV_1_5) { + EmmcDecodeExtCsdRev15Field(extCsd, rawExtCsd); + } + return HDF_SUCCESS; +} + +static void EmmcSetBlockCapacity(struct MmcCntlr *cntlr) +{ + struct EmmcDevice *emmcDev = (struct EmmcDevice *)cntlr->curDev; + uint32_t gibVal, mibVal; + + /* + * ERASE_GROUP_DEF Bit0: ENABLE: + * 0x0 : Use old erase group size and write protect group size definition (default) + * 0x1 : Use high-capacity erase unit size, high capacity erase timeout, and high-capacity write protect + * group size definition. + */ + if (emmcDev->emmcReg.extCsd.eraseGroupDef == 1) { + emmcDev->mmc.eraseSize = emmcDev->emmcReg.extCsd.hcEraseSize; + } else { + emmcDev->mmc.eraseSize = emmcDev->mmc.reg.csd.eraseSize; + } + + if (emmcDev->mmc.state.bits.blockAddr > 0) { + emmcDev->mmc.capacity = emmcDev->emmcReg.extCsd.sectors; + } else { + emmcDev->mmc.capacity = (size_t)emmcDev->mmc.reg.csd.capacity << + (emmcDev->mmc.reg.csd.readBlkLen - MMC_MAX_BLOCKSIZE_SHIFT); + } + + gibVal = emmcDev->mmc.capacity >> 21; + mibVal = (emmcDev->mmc.capacity & ~(gibVal << 21)) >> 11; + HDF_LOGD("Emmc dev capacity %d.%d Gib", gibVal, mibVal); +} + +static int32_t EmmcCheckExtCsd(struct MmcCntlr *cntlr, enum MmcBusWidth width) +{ + uint8_t extCsd[EXT_CSD_BYTES_LEN] = {0}; + + if (width == BUS_WIDTH1) { + return 0; + } + + return MmcSendExtCsd(cntlr, extCsd, EXT_CSD_BYTES_LEN); +} + +static int32_t EmmcSwitchVoltage(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev) +{ + uint32_t cardType = emmcDev->emmcReg.extCsd.cardType; + + /* Host Voltage Switch. */ + if (cntlr->caps2.bits.hs200Sdr1v2 == 1 && (cardType & EMMC_EXT_CSD_CARD_TYPE_SDR_1_2V) > 0) { + (void)MmcCntlrSwitchVoltage(cntlr, VOLT_1V2); + } + if (cntlr->caps2.bits.hs200Sdr1v8 && (cardType & EMMC_EXT_CSD_CARD_TYPE_SDR_1_8V) > 0) { + (void)MmcCntlrSwitchVoltage(cntlr, VOLT_1V8); + } + return HDF_SUCCESS; +} + +static int32_t EmmcSelectHighSpeedBusWidth(struct MmcCntlr *cntlr) +{ + int err = HDF_FAILURE; + enum MmcBusWidth width = BUS_WIDTH1; + + if (cntlr->caps.bits.cap8Bit > 0) { + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, EMMC_EXT_CSD_BUS_WIDTH_8); + if (err != HDF_SUCCESS) { + HDF_LOGD("EmmcSelectHighSpeedBusWidth: switch 8 bit bus width fail!"); + } else { + MmcCntlrSetBusWidth(cntlr, BUS_WIDTH8); + width = BUS_WIDTH8; + } + } + if (err != HDF_SUCCESS) { + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, EMMC_EXT_CSD_BUS_WIDTH_4); + if (err != HDF_SUCCESS) { + HDF_LOGD("EmmcSelectHighSpeedBusWidth: switch 4 bit bus width fail!"); + } else { + MmcCntlrSetBusWidth(cntlr, BUS_WIDTH4); + width = BUS_WIDTH4; + } + } + if (err != HDF_SUCCESS) { + return err; + } + + return EmmcCheckExtCsd(cntlr, width); +} + +static int32_t EmmcCheckSwitchStatus(struct MmcCntlr *cntlr) +{ + int err; + uint32_t status; + + err = MmcSendStatus(cntlr, &status); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcCheckSwitchStatus: send status cmd fail!"); + return err; + } + if ((status & SWITCH_ERROR) > 0) { + return HDF_MMC_ERR_SWITCH_FAIL; + } + return HDF_SUCCESS; +} + +static int32_t EmmcSwitchHighSpeed(struct MmcCntlr *cntlr) +{ + int err; + + /* + * Switch dev to HS mode. + * HS_TIMING must be set to "0x1" before setting BUS_WIDTH for dual data rate operation (values 5 or 6). + */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HS_TIMING, EMMC_EXT_CSD_BUS_TIMING_HS); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSwitchHighSpeed: switch hs fail!"); + return err; + } + /* change host freq to 52M according to JEDEC Standard No.84-B51, Page49. */ + MmcCntlrSetClock(cntlr, EMMC_EXT_CSD_HIGH_SPEED_52); + /* Set host controller to HS timing. */ + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_MMC_HS); + return HDF_SUCCESS; +} + +static int32_t EmmcSelectHs400(struct MmcCntlr *cntlr) +{ + int err; + + err = EmmcSwitchHighSpeed(cntlr); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400: switch hs fail!"); + return err; + } + + /* Switch dev to DDR. */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, EMMC_EXT_CSD_DDR_BUS_WIDTH_8); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400: switch to ddr fail!"); + return err; + } + /* Switch dev to HS400. */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HS_TIMING, EMMC_EXT_CSD_BUS_TIMING_HS400); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400: switch to hs400 fail!"); + return err; + } + MmcCntlrSetClock(cntlr, EMMC_EXT_CSD_HIGH_SPEED_200); + /* Set host controller to HS400 timing and frequency. */ + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_MMC_HS400); + return EmmcCheckSwitchStatus(cntlr); +} + +static int32_t EmmcSelectHs400es(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev) +{ + int err; + + err = EmmcSwitchVoltage(cntlr, emmcDev); + if (err != HDF_SUCCESS) { + return err; + } + + err = EmmcSelectHighSpeedBusWidth(cntlr); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400es: select hs width fail!"); + return err; + } + + err = EmmcSwitchHighSpeed(cntlr); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400es: switch hs fail!"); + return err; + } + + /* Switch dev to DDR with strobe bit. */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, + EMMC_EXT_CSD_DDR_BUS_WIDTH_8 | EMMC_EXT_CSD_BUS_WIDTH_STROBE); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400es: switch to ddr fail!"); + return err; + } + /* Switch dev to HS400. */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HS_TIMING, EMMC_EXT_CSD_BUS_TIMING_HS400); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs400es: switch to hs400 fail!"); + return err; + } + MmcCntlrSetClock(cntlr, EMMC_EXT_CSD_HIGH_SPEED_200); + /* Set host controller to HS400 timing and frequency. */ + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_MMC_HS400); + MmcCntlrSetEnhanceSrobe(cntlr, true); + return EmmcCheckSwitchStatus(cntlr); +} + +static int32_t EmmcSelectHs200(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev) +{ + int err; + + err = EmmcSwitchVoltage(cntlr, emmcDev); + if (err != HDF_SUCCESS) { + return err; + } + + err = EmmcSelectHighSpeedBusWidth(cntlr); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs200: select hs width fail!"); + return err; + } + + /* Switch dev to HS200. */ + err = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HS_TIMING, EMMC_EXT_CSD_BUS_TIMING_HS200); + if (err != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectHs200: switch to hs200 fail!"); + return err; + } + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_MMC_HS200); + return EmmcCheckSwitchStatus(cntlr); +} + +static uint32_t EmmcGetPowerClassValue(struct MmcCntlr *cntlr, struct EmmcExtCsd *extCsd) +{ + uint32_t val = 0; + uint32_t vdd, busWidthBit, clock; + + busWidthBit = (cntlr->curDev->workPara.width == BUS_WIDTH8) ? + EMMC_EXT_CSD_BUS_WIDTH_8 : EMMC_EXT_CSD_BUS_WIDTH_4; + vdd = 1 << (cntlr->vddBit); + clock = cntlr->curDev->workPara.clock; + + if (vdd == MMC_OCR_1V65_1V95) { + if (clock <= EMMC_EXT_CSD_HIGH_SPEED_26) { + val = extCsd->pwrClF26V195; + } else if (clock <= EMMC_EXT_CSD_HIGH_SPEED_52) { + val = extCsd->pwrClF52V195; + } else if (clock <= EMMC_EXT_CSD_HIGH_SPEED_200) { + val = extCsd->pwrClF200V195; + } + } else if (vdd >= MMC_OCR_2V7_2V8 && vdd <= MMC_OCR_3V5_3V6) { + if (clock <= EMMC_EXT_CSD_HIGH_SPEED_26) { + val = extCsd->pwrClF26V360; + } else if (clock <= EMMC_EXT_CSD_HIGH_SPEED_52) { + val = extCsd->pwrClF52V360; + } else if (clock <= EMMC_EXT_CSD_HIGH_SPEED_200) { + val = extCsd->pwrClF200V360; + } + } else { + return 0; + } + + if (busWidthBit == EMMC_EXT_CSD_BUS_WIDTH_8) { + val = (val & EMMC_EXT_CSD_PWR_CL_8BIT_MASK) >> EMMC_EXT_CSD_PWR_CL_8BIT_SHIFT; + } else { + val = (val & EMMC_EXT_CSD_PWR_CL_4BIT_MASK) >> EMMC_EXT_CSD_PWR_CL_4BIT_SHIFT; + } + return val; +} + +static int32_t EmmcSelectPowerClass(struct MmcCntlr *cntlr, struct EmmcExtCsd *extCsd) +{ + int32_t error = 0; + uint32_t val; + + if (cntlr->curDev->reg.csd.specVers < MMC_CSD_SPEC_VER_4) { + return HDF_SUCCESS; + } + + val = EmmcGetPowerClassValue(cntlr, extCsd); + if (val > 0) { + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_POWER_CLASS, val); + } + return error; +} + +static int32_t EmmcSelectActivateHighSpeed(struct MmcCntlr *cntlr, + struct EmmcDevice *emmcDev, struct EmmcExtCsd *extCsd) +{ + int32_t error; + + if (extCsd->hsMaxDtr > 0) { + error = HDF_SUCCESS; + if (MmcCntlrSupportHighSpeed200(cntlr) == true && + extCsd->hsMaxDtr > EMMC_EXT_CSD_HIGH_SPEED_52) { + error = EmmcSelectHs200(cntlr, emmcDev); + if (error == HDF_SUCCESS) { + emmcDev->mmc.state.bits.hs200 = 1; + } + } else if (cntlr->caps.bits.highSpeed == 1) { + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HS_TIMING, + EMMC_EXT_CSD_BUS_TIMING_HS); + if (error == HDF_SUCCESS) { + emmcDev->mmc.state.bits.highSpeed = 1; + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_MMC_HS); + } + } + if (error != HDF_SUCCESS && error != HDF_MMC_ERR_SWITCH_FAIL) { + return error; + } + } + + return HDF_SUCCESS; +} + +static int32_t EmmcSelectBusSpeedMode(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev, struct EmmcExtCsd *extCsd) +{ + int32_t error; + + /* HS400ES mode requires 8-bit bus width. */ + if (extCsd->strobeSupport > 0 && MmcCntlrSupportHighSpeed400EnhancedStrobe(cntlr) == true) { + error = EmmcSelectHs400es(cntlr, emmcDev); + if (error != HDF_SUCCESS) { + return error; + } + emmcDev->mmc.state.bits.hs400es = 1; + } else { + /* Activate high speed if supported. */ + error = EmmcSelectActivateHighSpeed(cntlr, emmcDev, extCsd); + if (error != HDF_SUCCESS) { + return error; + } + /* host set clock. */ + if (emmcDev->mmc.state.bits.hs200 == 1 || emmcDev->mmc.state.bits.highSpeed == 1) { + if (extCsd->hsMaxDtr > 0) { + MmcCntlrSetClock(cntlr, extCsd->hsMaxDtr); + } + } else if (emmcDev->mmc.reg.csd.maxDtr > 0) { + MmcCntlrSetClock(cntlr, emmcDev->mmc.reg.csd.maxDtr); + } + } + + if (emmcDev->mmc.state.bits.hs400es == 1) { + error = EmmcSelectPowerClass(cntlr, extCsd); + if (error != HDF_SUCCESS) { + HDF_LOGD("EmmcSelectBusSpeedMode: hs400es select power class fail!"); + } + } else if (emmcDev->mmc.state.bits.hs200 == 1) { + if ((cntlr->caps2.bits.hs200Sdr1v8 | cntlr->caps2.bits.hs200Sdr1v2) > 0) { + error = MmcCntlrTune(cntlr, SEND_TUNING_BLOCK_HS200); + if (error != HDF_SUCCESS) { + return error; + } + } + + if ((extCsd->rawCardType & EMMC_EXT_CSD_CARD_TYPE_HS400) > 0 && + MmcCntlrSupportHighSpeed400(cntlr) == true) { + error = EmmcSelectHs400(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + emmcDev->mmc.state.bits.hs400 = 1; + emmcDev->mmc.state.bits.hs200 = 0; + } + + error = EmmcSelectPowerClass(cntlr, extCsd); + if (error != HDF_SUCCESS) { + HDF_LOGD("EmmcSelectBusSpeedMode: hs200 select power class fail!"); + } + } + + return HDF_SUCCESS; +} + +static uint32_t EmmcGetDdrMode(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev, struct EmmcExtCsd *extCsd) +{ + uint32_t ddrMode = MMC_BUS_MODE_NULL; + + /* Indicate DDR mode (if supported). */ + if (emmcDev->mmc.state.bits.highSpeed == 1) { + if ((extCsd->cardType & EMMC_EXT_CSD_CARD_TYPE_DDR_1_8V) > 0 && + (cntlr->caps.bits.ddr1v8 > 0) && + (cntlr->caps.bits.uhsDdr50 > 0)) { + ddrMode = MMC_1_8V_DDR_MODE; + } else if ((extCsd->cardType & EMMC_EXT_CSD_CARD_TYPE_DDR_1_2V) > 0 && cntlr->caps.bits.ddr1v2 > 0) { + ddrMode = MMC_1_2V_DDR_MODE; + } + } + return ddrMode; +} + +static int32_t EmmcSwitchDdrMode(struct MmcCntlr *cntlr, uint32_t ddrMode, + enum MmcBusWidth width, uint32_t widthBit) +{ + int32_t error; + + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, widthBit); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcSwitchDdrMode: switch BUS_WIDTH fail!"); + return error; + } + + if (ddrMode == MMC_1_2V_DDR_MODE) { + error = MmcCntlrSwitchVoltage(cntlr, VOLT_1V2); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcSwitchDdrMode: switch 1.2V fail!"); + return error; + } + } + cntlr->curDev->state.bits.ddrMode = 1; + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_UHS_DDR50); + MmcCntlrSetBusWidth(cntlr, width); + return HDF_SUCCESS; +} + +static int32_t EmmcSelectSwitchDdrMode(struct MmcCntlr *cntlr, struct EmmcDevice *emmcDev, + struct EmmcExtCsd *extCsd) +{ + int32_t error; + uint32_t index, ddrMode; + enum MmcBusWidth width; + enum MmcBusWidth busWidths[] = { BUS_WIDTH8, BUS_WIDTH4, BUS_WIDTH1 }; + uint32_t busWidthBit[][2] = { + { EMMC_EXT_CSD_BUS_WIDTH_8, EMMC_EXT_CSD_DDR_BUS_WIDTH_8 }, + { EMMC_EXT_CSD_BUS_WIDTH_4, EMMC_EXT_CSD_DDR_BUS_WIDTH_4 }, + { EMMC_EXT_CSD_BUS_WIDTH_1, EMMC_EXT_CSD_BUS_WIDTH_1 }, + }; + + ddrMode = EmmcGetDdrMode(cntlr, emmcDev, extCsd); + if (emmcDev->mmc.state.bits.hs400es == 0 && + emmcDev->mmc.state.bits.hs400 == 0 && + emmcDev->mmc.state.bits.hs200 == 0 && + cntlr->curDev->reg.csd.specVers >= MMC_CSD_SPEC_VER_4 && + (cntlr->caps.bits.cap4Bit | cntlr->caps.bits.cap8Bit) > 0) { + index = 1; + if (cntlr->caps.bits.cap8Bit > 0) { + index = 0; + } + for (; index < sizeof(busWidthBit) / sizeof(busWidthBit[0]); index++) { + width = busWidths[index]; + /* no DDR for 1-bit width. */ + if (width == BUS_WIDTH1) { + ddrMode = MMC_BUS_MODE_NULL; + } + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_BUS_WIDTH, busWidthBit[index][0]); + if (error != HDF_SUCCESS) { + continue; + } + MmcCntlrSetBusWidth(cntlr, width); + error = EmmcCheckExtCsd(cntlr, width); + if (error == HDF_SUCCESS) { + break; + } + } + /* switch DDR mode. */ + if (error == HDF_SUCCESS && ddrMode > MMC_BUS_MODE_NULL) { + error = EmmcSwitchDdrMode(cntlr, ddrMode, width, busWidthBit[index][1]); + } + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcSelectSwitchDdrMode: switch ddr mode fail!"); + return error; + } + } + return HDF_SUCCESS; +} + +static int32_t EmmcActivateHpiMechanism(struct MmcCntlr *cntlr, struct EmmcExtCsd *extCsd) +{ + int32_t error; + + if (extCsd->hpi == true) { + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_HPI_MGMT, 1); + if (error == HDF_SUCCESS) { + extCsd->hpiEnable = true; + } else if (error != HDF_MMC_ERR_SWITCH_FAIL) { + HDF_LOGE("EmmcActivateHpiMechanism: switch HPI_MGMT fail!"); + return error; + } + } + return HDF_SUCCESS; +} + +static int32_t EmmcSwitchOperationMode(struct MmcCntlr *cntlr) +{ + struct EmmcDevice *emmcDev = (struct EmmcDevice *)cntlr->curDev; + struct EmmcExtCsd *extCsd = &(emmcDev->emmcReg.extCsd); + int32_t error; + + if (extCsd->enhAreaEnable == true) { + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_ERASE_GROUP_DEF, 1); + if (error == HDF_SUCCESS) { + extCsd->eraseGroupDef = 1; + } else if (error != HDF_MMC_ERR_SWITCH_FAIL) { + HDF_LOGE("EmmcSwitchOperationMode: switch ERASE_GROUP_DEF fail!"); + return error; + } + } + + if ((extCsd->partConfig & EMMC_EXT_CSD_PART_CONFIG_ACCESS_MASK) > 0) { + /* No access to boot partition (default). */ + extCsd->partConfig &= ~EMMC_EXT_CSD_PART_CONFIG_ACCESS_MASK; + error = MmcSwitch(cntlr, EMMC_EXT_CSD_CMD_SET_NORMAL, EMMC_EXT_CSD_PARTITION_CONFIG, extCsd->partConfig); + if (error != HDF_SUCCESS && error != HDF_MMC_ERR_SWITCH_FAIL) { + HDF_LOGE("EmmcSwitchOperationMode: switch PARTITION_CONFIG fail!"); + return error; + } + } + + error = EmmcSelectBusSpeedMode(cntlr, emmcDev, extCsd); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcSwitchOperationMode: select bus speed mode fail!"); + return error; + } + + error = EmmcSelectSwitchDdrMode(cntlr, emmcDev, extCsd); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcSwitchOperationMode: select switch ddr mode fail!"); + return error; + } + return EmmcActivateHpiMechanism(cntlr, extCsd); +} + +static int32_t EmmcReadExtCsd(struct MmcCntlr *cntlr) +{ + uint8_t extCsd[EXT_CSD_BYTES_LEN] = {0}; + int32_t error; + + if (cntlr->curDev->reg.csd.specVers < MMC_CSD_SPEC_VER_4) { + return HDF_SUCCESS; + } + + error = MmcSendExtCsd(cntlr, extCsd, EXT_CSD_BYTES_LEN); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcReadExtCsd: send cmd8 fail, error = %d.", error); + return error; + } + error = EmmcDecodeExtCsd(cntlr, extCsd, EXT_CSD_BYTES_LEN); + if (error != HDF_SUCCESS) { + HDF_LOGE("EmmcReadExtCsd: decode ext csd fail, error = %d.", error); + return error; + } + + return error; +} + +static int32_t EmmcSelect(struct MmcCntlr *cntlr, union MmcOcr ocr) +{ + union MmcOcr curOcr; + int32_t error; + + MmcGoIdleState(cntlr); + ocr.bits.hcs = 1; + /* set dev work voltage. */ + error = MmcSendOpCond(cntlr, ocr.ocrData, &curOcr.ocrData); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc cmd1(set voltage) fail, error = %d.", error); + return error; + } + + error = MmcAllSendCid(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc cmd2(get cid) fail, error = %d.", error); + return error; + } + + /* card is identified. */ + cntlr->curDev->reg.rca = 1; + error = MmcSetRelativeAddr(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc cmd3(set rca) fail, error = %d.", error); + return error; + } + + error = MmcSendCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc send cmd9(get csd) fail, error = %d.", error); + return error; + } + error = EmmcDecodeCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc decode csd fail, error = %d.", error); + return error; + } + error = EmmcDecodeCid(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc decode cid fail, error = %d.", error); + return error; + } + error = MmcSelectCard(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc send cmd7 fail, error = %d.", error); + return error; + } + error = EmmcReadExtCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Emmc read ext csd fail, error = %d.", error); + return error; + } + + return EmmcSwitchOperationMode(cntlr); +} + +static int32_t EmmcDeviceAdd(struct MmcCntlr *cntlr) +{ + EmmcSetBlockCapacity(cntlr); + /* add dev. */ + if (MmcDeviceAdd(cntlr->curDev) != HDF_SUCCESS) { + HDF_LOGE("EmmcDeviceAdd: Add device fail!"); + return HDF_FAILURE; + } + cntlr->curDev->state.bits.present = 1; + return HDF_SUCCESS; +} + +static int32_t EmmcInit(struct MmcCntlr *cntlr) +{ + int32_t error; + union MmcOcr ocr = {0}; + + /* cmd1, detect emmc dev and get the voltage range. */ + error = MmcSendOpCond(cntlr, 0, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd1(detect emmc) fail, error = %d.", error); + return error; + } + + MmcCntlrSelectWorkVoltage(cntlr, &ocr); + if (cntlr->curDev->reg.ocr.ocrData == 0) { + HDF_LOGE("Emmc select work voltage fail!"); + return HDF_ERR_INVALID_PARAM; + } + /* work voltage is low voltage, host should switch. */ + if (cntlr->curDev->reg.ocr.bits.vdd1v65To1v95 > 0) { + HDF_LOGD("Emmc switch to 1.8V!"); + MmcCntlrSwitchVoltage(cntlr, VOLT_1V8); + } + + error = EmmcSelect(cntlr, cntlr->curDev->reg.ocr); + if (error != HDF_SUCCESS) { + return error; + } + + return EmmcDeviceAdd(cntlr); +} + +static int32_t EmmcDetect(struct MmcCntlr *cntlr) +{ + int32_t ret; + + HDF_LOGD("Detect emmc dev start..."); + MmcGoIdleState(cntlr); + ret = EmmcInit(cntlr); + if (ret == HDF_SUCCESS) { + HDF_LOGD("Detect emmc dev success! %s dev at address 0x%x!", + cntlr->curDev->state.bits.uhs ? "Ultra high speed" : + (cntlr->curDev->state.bits.highSpeed ? "High speed" : ""), + cntlr->curDev->reg.rca); + } + return ret; +} + +static int32_t SdSendAppCmd(struct MmcCntlr *cntlr, struct MmcCmd *cmd, + struct MmcData *data, uint32_t retryTimes) +{ + uint32_t i; + int32_t err; + + if (cntlr == NULL || cmd == NULL || retryTimes == 0) { + return HDF_ERR_INVALID_PARAM; + } + + for (i = 0; i <= retryTimes; i++) { + err = MmcAppCmd(cntlr, cmd->cmdCode); + if (err != HDF_SUCCESS) { + continue; + } + err = MmcSendCmd(cntlr, cmd, data, 1); + if (err == HDF_SUCCESS) { + break; + } + } + return err; +} + +static int32_t SdAcmdOpCond(struct MmcCntlr *cntlr, uint32_t arg, uint32_t *ocr) +{ + struct MmcCmd cmd = {0}; + int32_t err; + uint32_t i; + + cmd.cmdCode = SD_ACMD_OP_COND; + /* [31]reserved bit, [30]HCS, [29]reserved for eSD, [28]XPC, [27:25]reserved bits, [24]S18R, [23:0]VDD voltage. */ + cmd.argument = arg; + /* Broadcast Commands with Response(bcr). */ + cmd.respType = MMC_RESP_R3 | MMC_CMD_TYPE_BCR; + /* + * The host must poll the card (by repeatedly sending CMD1 or ACMD41) until the 'in-idle-state' bit in + * the card response indicates (by being set to 0) that the card completed its initialization processes + * and is ready for the next command. + */ + for (i = 0; i < INIT_CMD_RETRY_TIMES; i++) { + err = SdSendAppCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (err != HDF_SUCCESS) { + break; + } + /* if probing, just single pass */ + if (arg == 0) { + break; + } + /* + * wait until init complete. + * 0--On Initialization; 1--Initialization Complete. + */ + if ((cmd.resp[0] & MMC_CARD_BUSY_STATUS) > 0) { + break; + } + err = HDF_ERR_TIMEOUT; + OsalMDelay(20); + } + if (ocr != NULL) { + *ocr = cmd.resp[0]; + } + + return err; +} + +static int32_t SdAcmdSdStatus(struct MmcCntlr *cntlr, uint32_t *ssr, uint32_t len) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + int32_t error; + uint32_t i; + + if (cntlr == NULL || ssr == NULL || len == 0) { + return HDF_ERR_INVALID_PARAM; + } + + cmd.cmdCode = SD_ACMD_SD_STATUS; + /* [31:0] stuff bits. */ + cmd.argument = 0; + /* Addressed (point-to-point) Data Transfer Commands (adtc), data transfer on DAT. */ + cmd.respType = MMC_RESP_SPI_R2 | MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + data.blockSize = SSR_BYTES_LEN; + data.blockNum = 1; + data.dataFlags = DATA_READ; + data.dataBuffer = (uint8_t *)ssr; + error = SdSendAppCmd(cntlr, &cmd, &data, 1); + if (error != HDF_SUCCESS) { + return error; + } + for (i = 0; i < len; i++) { + ssr[i] = MmcEndianConversion(ssr[i]); + } + return error; +} + +static int32_t SdAppSendScr(struct MmcCntlr *cntlr, uint32_t *scr, uint32_t len) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + int32_t error; + uint32_t i; + + if (cntlr == NULL || scr == NULL || len == 0) { + return HDF_ERR_INVALID_PARAM; + } + + cmd.cmdCode = SD_ACMD_SEND_SCR; + /* [31:0] stuff bits. */ + cmd.argument = 0; + /* Addressed (point-to-point) Data Transfer Commands (adtc), data transfer on DAT. */ + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + data.blockSize = SCR_BYTES_LEN; + data.blockNum = 1; + data.dataFlags = DATA_READ; + data.dataBuffer = (uint8_t *)scr; + error = SdSendAppCmd(cntlr, &cmd, &data, 1); + if (error != HDF_SUCCESS) { + return error; + } + for (i = 0; i < len; i++) { + scr[i] = MmcEndianConversion(scr[i]); + } + return error; +} + +static int32_t SdAcmdSetBusWidth(struct MmcCntlr *cntlr, uint32_t width) +{ + struct MmcCmd cmd = {0}; + + cmd.cmdCode = SD_ACMD_SET_BUS_WIDTH; + /* [31:2] stuff bits; [1:0]bus width: '00' = 1bit and '10' = 4bits. */ + cmd.argument = width; + /* Addressed (point-to-point) Commands(ac), no data transfer on DAT. */ + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + + return SdSendAppCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); +} + +static int32_t SdCmdSendIfCond(struct MmcCntlr *cntlr, uint32_t ocr) +{ + struct MmcCmd cmd = {0}; + int32_t err; + uint32_t vhs; + + cmd.cmdCode = SD_CMD_SEND_IF_COND; + /* + * [31:12]reserved bits, [11:8]supply voltage(VHS), [7:0]check pattern. + * VHS = 0001, 2.7-3.6V. + */ + vhs = ((ocr & 0xFF8000U) > 0) ? 1 : 0; + cmd.argument = (vhs << 8) | 0xAA; + cmd.respType = MMC_RESP_SPI_R7 | MMC_RESP_R7 | MMC_CMD_TYPE_BCR; + + err = MmcSendCmd(cntlr, &cmd, NULL, 1); + if (err != HDF_SUCCESS) { + return err; + } + /* + * Check pattern is used for the host to check validity of communication between the host and the card. + * In the Response, the card echoes back the check pattern set in argument. + * If check pattern is not matched, CMD8 communication is not valid. + */ + if ((cmd.resp[0] & 0xFF) != 0xAA) { + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t SdCmdSendRelativeAddr(struct MmcCntlr *cntlr, uint32_t *rca) +{ + int32_t error; + struct MmcCmd cmd = {0}; + + cmd.cmdCode = SD_CMD_SEND_RELATIVE_ADDR; + /* [31:0] stuff bits. */ + cmd.argument = 0; + cmd.respType = MMC_RESP_R6 | MMC_CMD_TYPE_BCR; + error = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (error != HDF_SUCCESS) { + return error; + } + if (rca != NULL) { + /* New published RCA [31:16] of the card. */ + *rca = cmd.resp[0] >> 16; + } + return error; +} + +static int32_t SdCmdSwitchVoltage(struct MmcCntlr *cntlr) +{ + int32_t error; + struct MmcCmd cmd = {0}; + + /* Voltage switch command to change signaling level 3.3V to 1.8V. */ + cmd.cmdCode = SD_CMD_SWITCH_VOLTAGE; + /* [31:0] stuff bits. */ + cmd.argument = 0; + cmd.respType = MMC_RESP_R1 | MMC_CMD_TYPE_AC; + error = MmcSendCmd(cntlr, &cmd, NULL, 1); + if (error != HDF_SUCCESS) { + return error; + } + if (cmd.resp[0] & GENERAL_ERROR) { + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t SdCmdSwitchFunc(struct MmcCntlr *cntlr, struct SdSwitchFuncParam *param, + uint8_t *status, uint32_t len) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + + cmd.cmdCode = SD_CMD_SWITCH_FUNC; + /* + * [31]Mode. The switch command can be used in two modes: + * Mode 0 (Check function) is used to query if the card supports a specific function or functions. + * Mode 1 (set function) is used to switch the functionality of the card. + */ + cmd.argument = (param->mode << 31) | 0x00FFFFFF; + /* + * [30:24] reserved(All '0'); [23:20] reserved for function group 6(All '0' or 0xF); + * [19:16] reserved for function group 5(All '0' or 0xF); [15:12] function group 4 for Power Limit; + * [11:8] function group 3 for Drive Strength; [7:4] function group 2 for command system; + * [3:0] function group 1 for access mode. + */ + cmd.argument &= ~(0xFU << (param->group * 4)); + cmd.argument |= (param->value & 0xF) << (param->group * 4); + cmd.respType = MMC_RESP_SPI_R1 | MMC_RESP_R1 | MMC_CMD_TYPE_ADTC; + /* + * As a response to the switch function command, the SD Memory Card will send R1 response on the CMD line, + * and 512 bits of status on the DAT lines. + */ + data.blockSize = len; + data.blockNum = 1; + data.dataFlags = DATA_READ; + data.dataBuffer = status; + + return MmcSendCmd(cntlr, &cmd, &data, 1); +} + +static int32_t SdDecodeScr(struct MmcCntlr *cntlr) +{ + struct SdScr *scr = NULL; + uint32_t *rawScr = NULL; + struct SdDevice *sdDev = NULL; + uint32_t scrStruct; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + sdDev = (struct SdDevice *)cntlr->curDev; + rawScr = sdDev->reg.rawScr; + scr = &(sdDev->reg.scr); + + /* + * SCR_STRUCTURE: [63:60]; + * SCR_STRUCTURE equal 0, SCR version 1.0; SCR_STRUCTURE equal 1-15, reserved. + */ + scrStruct = (uint8_t)MmcParseBits(rawScr, SCR_BITS, 60, 4); + if (scrStruct != 0) { + HDF_LOGE("SdDecodeScr: scrStruct is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + /* + * SD_SPEC: [59:56]. + * Describes the SD Memory Card Physical Layer Specification version supported by this card. + * SD_SPEC = 0 , Version 1.0-1.01; SD_SPEC = 1, Version 1.1; SD_SPEC = 2, Version >= 2.0. + */ + scr->sdSpec = (uint8_t)MmcParseBits(rawScr, SCR_BITS, 56, 4); + if (scr->sdSpec == SD_SCR_SPEC_2) { + /* SD_SPEC3: [47:47] */ + scr->sdSpec3 = (uint8_t)MmcParseBits(rawScr, SCR_BITS, 47, 1); + } + /* + * SD_BUS_WIDTHS: [51:48]. + * SD_BUS_WIDTHS equal 0, 1 bit (DAT0); SD_BUS_WIDTHS equal 2, 4 bit (DAT0-3). + */ + scr->sdBusWidths = (uint8_t)MmcParseBits(rawScr, SCR_BITS, 48, 4); + /* CMD_SUPPORT: [35:32] */ + scr->cmdSupport = (uint8_t)MmcParseBits(rawScr, SCR_BITS, 32, 2); + return HDF_SUCCESS; +} + +static int32_t SdDecodeSSr(struct MmcCntlr *cntlr, uint32_t *rawSsr, uint32_t len) +{ + struct SdSsr *ssr = NULL; + struct SdScr *scr = NULL; + struct SdDevice *sdDev = NULL; + uint32_t eraseSize, eraseTimeout; + + if (cntlr == NULL || cntlr->curDev == NULL || rawSsr == NULL || len == 0) { + return HDF_ERR_INVALID_PARAM; + } + + sdDev = (struct SdDevice *)cntlr->curDev; + ssr = &(sdDev->reg.ssr); + scr = &(sdDev->reg.scr); + /* SPEED_CLASS: [447:440] */ + ssr->speedClass = MmcParseBits(rawSsr, SSR_BITS, 440, 8); + /* AU_SIZE: [431: 428]. */ + ssr->auSize = MmcParseBits(rawSsr, SSR_BITS, 428, 4); + if (ssr->auSize > 0) { + if ((ssr->auSize <= MMC_MAX_BLOCKSIZE_SHIFT) || scr->sdSpec3 > 0) { + ssr->auValue = 1 << (ssr->auSize + 4); + /* + * ERASE_SIZE: [423:408]. If this field is set to 0, the erase timeout caculation is not supported. + * ERASE_SIZE = 1, value = 1AU; ERASE_SIZE = 2, value = 2AU... + */ + eraseSize = MmcParseBits(rawSsr, SSR_BITS, 408, 16); + /* ERASE_TIMEOUT: [407:402] */ + eraseTimeout = MmcParseBits(rawSsr, SSR_BITS, 402, 6); + if (eraseSize > 0) { + ssr->eraseTimeout = (eraseTimeout * 1000) / eraseSize; + /* ERASE_OFFSET: [401:400] */ + ssr->eraseOffset = 1000 * MmcParseBits(rawSsr, SSR_BITS, 400, 2); + } + } else { + HDF_LOGD("SD Status: Invalid AU."); + } + } + /* UHS_SPEED_GRADE: [399:396] */ + ssr->uhsSpeedGrade = MmcParseBits(rawSsr, SSR_BITS, 396, 4); + return HDF_SUCCESS; +} + +static void SdDecodeCid(struct MmcCntlr *cntlr) +{ + struct MmcCid *cid = NULL; + uint32_t *rawCid = NULL; + uint32_t i; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return; + } + + rawCid = cntlr->curDev->reg.rawCid; + cid = &(cntlr->curDev->reg.cid); + /* Manufacturer ID(MID): [127:120] */ + cid->mid = MmcParseBits(rawCid, CID_BITS, 120, 8); + /* OEM/Application ID(OID): [119:104] */ + cid->oid = MmcParseBits(rawCid, CID_BITS, 104, 16); + /* Product name(PNM): [103:64] */ + for (i = 0; i < 5; i++) { + cid->pnm[i] = MmcParseBits(rawCid, CID_BITS, 96 - (i * 8), 8); + } + cid->pnm[5] = '\0'; + /* + * Product revision(PRV): [63:56]. + * The product revision is composed of two Binary Coded Decimal (BCD) digits, four bits each, + * representingan "n.m" revision number. + */ + cid->hwPrv = MmcParseBits(rawCid, CID_BITS, 60, 4); + cid->fwPrv = MmcParseBits(rawCid, CID_BITS, 56, 4); + /* Product serial number(PSN): [55:24] */ + cid->psn = MmcParseBits(rawCid, CID_BITS, 24, 32); + /* + * Manufacturing date(MDT): [19:8]. + * The manufacturing date composed of two hexadecimal digits, one is 8 bit representing the year(y) + * and the other is four bits representing the month(m). + * The "m" field [11:8] is the month code. 1 = January. + * The "y" field [19:12] is the year code. 0 = 2000. + */ + cid->year = MmcParseBits(rawCid, CID_BITS, 12, 8) + 2000; + cid->month = MmcParseBits(rawCid, CID_BITS, 8, 4); +} + +static void SdSetBlockCapacity(struct MmcCntlr *cntlr) +{ + struct SdDevice *sdDev = (struct SdDevice *)cntlr->curDev; + uint32_t gibVal, mibVal; + + sdDev->mmc.eraseSize = sdDev->mmc.reg.csd.eraseSize; + sdDev->mmc.capacity = sdDev->mmc.reg.csd.capacity << + (sdDev->mmc.reg.csd.readBlkLen - MMC_MAX_BLOCKSIZE_SHIFT); + + gibVal = sdDev->mmc.capacity >> 21; + mibVal = (sdDev->mmc.capacity & ~(gibVal << 21)) >> 11; + HDF_LOGD("SD dev capacity %d.%d Gib", gibVal, mibVal); +} + +static void SdDecodeCsdRev1Field(struct MmcCntlr *cntlr, struct MmcCsd *csd, uint32_t *rawCsd) +{ + uint32_t unit, factor; + + /* TAAC: [119:112]; TAAC bit position-->Time unit: [2:0], Multiplier factor: [6:3]. */ + factor = MmcParseBits(rawCsd, CSD_BITS, 115, 4); + unit = MmcParseBits(rawCsd, CSD_BITS, 112, 3); + csd->taccNs = (g_taccUnit[unit] * g_commFactor[factor] + 9) / 10; + /* NSAC: [111:104], the unit for NSAC is 100 clock cycles */ + csd->taccClks = MmcParseBits(rawCsd, CSD_BITS, 104, 8) * 100; + + /* TRAN_SPEED: [103:96]; TRAN_SPEED bit-->Frequency unit: [2:0], Multiplier factor: [6:3]. */ + factor = MmcParseBits(rawCsd, CSD_BITS, 99, 4); + unit = MmcParseBits(rawCsd, CSD_BITS, 96, 3); + csd->maxDtr = g_tranSpeedUnit[unit] * g_commFactor[factor]; + /* card command classes: [95:84] */ + csd->ccc = MmcParseBits(rawCsd, CSD_BITS, 84, 12); + /* C_SIZE: [73:62] */ + unit = MmcParseBits(rawCsd, CSD_BITS, 62, 12); + /* C_SIZE_MULT: [49:47] */ + factor = MmcParseBits(rawCsd, CSD_BITS, 47, 3); + csd->capacity = (1 + unit) << (factor + 2); + /* READ_BL_LEN: [83:80]. */ + csd->readBlkLen = MmcParseBits(rawCsd, CSD_BITS, 80, 4); + /* READ_BL_PARTIAL: [79:79] */ + csd->rdPartial = MmcParseBits(rawCsd, CSD_BITS, 79, 1); + /* WRITE_BLK_MISALIGN: [78:78] */ + csd->wrMisalign = MmcParseBits(rawCsd, CSD_BITS, 78, 1); + /* READ_BLK_MISALIGN: [77:77] */ + csd->rdMisalign = MmcParseBits(rawCsd, CSD_BITS, 77, 1); + /* Write speed factor(R2W_FACTOR) :[28:26] */ + csd->r2wFactor = MmcParseBits(rawCsd, CSD_BITS, 26, 3); + /* WRITE_BL_LEN: [25:22] */ + csd->writeBlkLen = MmcParseBits(rawCsd, CSD_BITS, 22, 4); + /* WRITE_BL_PARTIAL: [21:21] */ + csd->wrPartial = MmcParseBits(rawCsd, CSD_BITS, 21, 1); + /* + * erase single block enable(ERASE_BLK_EN): [46:46] + * If ERASE_BLK_EN is '0' erase area is unit of SECTOR_SIZE. + * if ERASE_BLK_EN is '1' erase area is unit of SECTOR_SIZE or unit of WRITE_BL_LEN. + */ + if (MmcParseBits(rawCsd, CSD_BITS, 46, 1) == 1) { + csd->eraseSize = 1; + } else if (csd->writeBlkLen >= MMC_MAX_BLOCKSIZE_SHIFT) { + /* + * erase sector size(SECTOR_SIZE): [45:39]. + * The actual size is computed by increasing this number by one. + * A value of zero means 1 write block, 127 means 128 write blocks. + */ + csd->eraseSize = MmcParseBits(rawCsd, CSD_BITS, 39, 7) + 1; + csd->eraseSize <<= (csd->writeBlkLen - MMC_MAX_BLOCKSIZE_SHIFT); + } +} + +static void SdDecodeCsdRev2Field(struct MmcCntlr *cntlr, struct MmcCsd *csd, uint32_t *rawCsd) +{ + uint32_t unit, factor; + + cntlr->curDev->state.bits.blockAddr = 1; + /* TRAN_SPEED: [103:96]; TRAN_SPEED bit-->Frequency unit: [2:0], Multiplier factor: [6:3]. */ + factor = MmcParseBits(rawCsd, CSD_BITS, 99, 4); + unit = MmcParseBits(rawCsd, CSD_BITS, 96, 3); + csd->maxDtr = g_tranSpeedUnit[unit] * g_commFactor[factor]; + /* card command classes: [95:84] */ + csd->ccc = MmcParseBits(rawCsd, CSD_BITS, 84, 12); + /* device size(C_SIZE): [69:48] */ + csd->cSize = MmcParseBits(rawCsd, CSD_BITS, 48, 22); + /* The Minimum value of C_SIZE for SDXC in CSD Version 2.0 is 00FFFFh(65535). */ + if (csd->cSize >= 0xFFFF) { + cntlr->curDev->state.bits.sdxc = 1; + } + /* memory capacity = (C_SIZE + 1) * 512KByte */ + csd->capacity = (1 + csd->cSize) << 10; + + csd->taccNs = 0; + csd->taccClks = 0; + csd->rdPartial = 0; + csd->readBlkLen = MMC_MAX_BLOCKSIZE_SHIFT; + csd->rdMisalign = 0; + csd->wrMisalign = 0; + csd->writeBlkLen = MMC_MAX_BLOCKSIZE_SHIFT; + csd->wrPartial = 0; + csd->r2wFactor = 2; + csd->eraseSize = 1; +} + +static int32_t SdDecodeCsd(struct MmcCntlr *cntlr) +{ + struct MmcCsd *csd = NULL; + uint32_t *rawCsd = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + rawCsd = cntlr->curDev->reg.rawCsd; + csd = &(cntlr->curDev->reg.csd); + + /* CSD_STRUCTURE: [127:126]. */ + csd->structure = MmcParseBits(rawCsd, CSD_BITS, 126, 2); + if (csd->structure == 0) { + /* CSD Version 1.0 */ + SdDecodeCsdRev1Field(cntlr, csd, rawCsd); + } else if (csd->structure == 1) { + /* CSD Version 2.0 */ + SdDecodeCsdRev2Field(cntlr, csd, rawCsd); + } else { + HDF_LOGE("SdDecodeCsd: not support, structure = %d.", csd->structure); + return HDF_ERR_NOT_SUPPORT; + } + + return HDF_SUCCESS; +} + +static uint32_t SdGetMaxClock(struct MmcCntlr *cntlr) +{ + uint32_t clock = 0xFFFFFFFF; + struct MmcDevice *mmcDev = cntlr->curDev; + struct SdDevice *sdDev = (struct SdDevice *)mmcDev; + + if (mmcDev->state.bits.highSpeed == 1) { + if (sdDev->reg.swCaps.hsMaxDtr > 0) { + clock = sdDev->reg.swCaps.hsMaxDtr; + } + } else if (mmcDev->reg.csd.maxDtr > 0) { + clock = mmcDev->reg.csd.maxDtr; + } + + if (clock > cntlr->freqMax) { + clock = cntlr->freqMax; + } + + return clock; +} + +static int32_t SdSelect(struct MmcCntlr *cntlr, uint32_t *rocr) +{ + int err; + bool try = false; + union MmcOcr ocr = cntlr->curDev->reg.ocr; + + do { + /* dev state: ready -> idle. */ + MmcGoIdleState(cntlr); + /* dev state: idle -> idle. */ + err = SdCmdSendIfCond(cntlr, cntlr->curDev->reg.ocr.ocrData); + if (err == HDF_SUCCESS) { + ocr.bits.hcs = 1; + } + if (cntlr->caps.bits.xpc330 == 1 || cntlr->caps.bits.xpc300 == 1 || cntlr->caps.bits.xpc180 == 1) { + ocr.bits.sdXpc = 1; + } + if (MmcCntlrSupportUhs(cntlr) == true && try == false) { + ocr.bits.s18r = 1; + } + /* dev state: idle -> ready. */ + err = SdAcmdOpCond(cntlr, ocr.ocrData, rocr); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSelect: acmd41 fail, err = %d.", err); + return err; + } + + /* host not support sd procotol 3.0 */ + if (cntlr->caps.bits.sdSupportProtocol3 == 0) { + break; + } + try = false; + /* + * Send cmd 11 to switch the volt. If host or device do not support, + * we need set 3.3v again. + */ + if (rocr != NULL && (*rocr & 0x41000000) == 0x41000000) { + /* switch host and card to 1.8V + * dev state: ready -> ready. + */ + err = SdCmdSwitchVoltage(cntlr); + if (err == HDF_SUCCESS) { + err = MmcCntlrSwitchVoltage(cntlr, VOLT_1V8); + } + if (err != HDF_SUCCESS) { + ocr.bits.s18r = 0; + try = true; + } + } + }while (try == true); + + /* get cid, dev state: ready -> ident. */ + err = MmcAllSendCid(cntlr); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSelect: cmd2 fail, err = %d.", err); + return err; + } + SdDecodeCid(cntlr); + return err; +} + +static int32_t SdReadCsd(struct MmcCntlr *cntlr) +{ + int32_t error; + + error = MmcSendCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdReadCsd: cmd9 fail, error = %d.", error); + return error; + } + return SdDecodeCsd(cntlr); +} + +static int32_t SdReadScr(struct MmcCntlr *cntlr) +{ + int32_t error; + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + + error = SdAppSendScr(cntlr, dev->reg.rawScr, SCR_LEN); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdReadScr: acmd51 fail, error = %d.", error); + return error; + } + return SdDecodeScr(cntlr); +} + +static int32_t SdReadSsr(struct MmcCntlr *cntlr) +{ + int32_t err; + uint32_t rawSsr[SSR_LEN] = {0}; + + /* don't support ACMD. */ + if ((cntlr->curDev->reg.csd.ccc & MMC_CSD_CCC_APP_SPEC) == 0) { + return HDF_SUCCESS; + } + + err = SdAcmdSdStatus(cntlr, rawSsr, SSR_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdReadSsr: acmd13 fail, err = %d.", err); + return err; + } + return SdDecodeSSr(cntlr, rawSsr, SSR_LEN); +} + +static int32_t SdReadSwitchCapbility(struct MmcCntlr *cntlr) +{ + int32_t err; + uint8_t status[SD_SWITCH_FUNCTION_STATUS_BYTES_LEN] = {0}; + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + struct SdSwitchFuncParam param = {0}; + + if (dev->reg.scr.sdSpec < SD_SCR_SPEC_1) { + return HDF_SUCCESS; + } + if ((cntlr->curDev->reg.csd.ccc & MMC_CSD_CCC_SWITCH) == 0) { + return HDF_SUCCESS; + } + + param.mode = SD_SWITCH_FUNC_MODE_CHECK; + param.group = SD_SWITCH_FUNC_GROUP_1; + param.value = 1; + /* The data(status) is in reverse order relative to the protocol. */ + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdReadSwitchCapbility: swutch func group 1 fail, err = %d.", err); + return err; + } + /* [415:400]Function Group 1 information, [407:400]-->status[13]. */ + if ((status[13] & SD_BUS_SPEED_MODE_HS) > 0) { + dev->reg.swCaps.hsMaxDtr = SD_HIGH_SPEED_MAX_DTR; + } + + if (dev->reg.scr.sdSpec3 == 1) { + dev->reg.swCaps.sdSpec3BusMode.data = status[13]; + param.group = SD_SWITCH_FUNC_GROUP_3; + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdReadSwitchCapbility: swutch func group 3 fail!"); + return err; + } + /* [447:432]Function Group 3 information, [447:440]-->status[9]. */ + dev->reg.swCaps.sdSpec3DrvType = (enum SdDrvType)status[9]; + param.group = SD_SWITCH_FUNC_GROUP_4; + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdReadSwitchCapbility: swutch func group 4 fail!"); + return err; + } + /* [463:448]Function Group 4 information, [463:456]-->status[7]. */ + dev->reg.swCaps.sdSpec3CurrLimit = (enum SdMaxCurrentLimitBit)status[7]; + } + return HDF_SUCCESS; +} + +static void SdFillBusSpeedMode(struct MmcCntlr *cntlr) +{ + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + + if (MmcCntlrSupportUhs(cntlr) == false || dev->reg.scr.sdSpec3 == 0) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_DS; + return; + } + + /* select max speed mode supported by host and device. */ + if ((cntlr->caps.bits.uhsSdr104 == 1) && (dev->reg.swCaps.sdSpec3BusMode.bits.uhsSdr104 == 1)) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_UHS_SDR104; + } else if ((cntlr->caps.bits.uhsDdr50 == 1) && (dev->reg.swCaps.sdSpec3BusMode.bits.uhsDdr50 == 1)) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_UHS_DDR50; + } else if ((cntlr->caps.bits.uhsSdr104 == 1 || cntlr->caps.bits.uhsSdr50 == 1) && + (dev->reg.swCaps.sdSpec3BusMode.bits.uhsSdr50 == 1)) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_UHS_SDR50; + } else if ((cntlr->caps.bits.uhsSdr104 == 1 || cntlr->caps.bits.uhsSdr50 == 1 || + cntlr->caps.bits.uhsSdr25 == 1) && (dev->reg.swCaps.sdSpec3BusMode.bits.uhsSdr25 == 1)) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_UHS_SDR25; + } else if ((cntlr->caps.bits.uhsSdr104 == 1 || cntlr->caps.bits.uhsSdr50 == 1 || + cntlr->caps.bits.uhsSdr25 == 1 || cntlr->caps.bits.uhsSdr12 == 1) && + (dev->reg.swCaps.sdSpec3BusMode.bits.uhsSdr12 == 1)) { + dev->busSpeedMode = SD_BUS_SPEED_MODE_UHS_SDR12; + } +} + +static int32_t SdReadRegisters(struct MmcCntlr *cntlr) +{ + int32_t error; + + /* get SCR */ + error = SdReadScr(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + + /* get SSR */ + error = SdReadSsr(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + + /* get sw cap */ + error = SdReadSwitchCapbility(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + + if (MmcCntlrDevReadOnly(cntlr) == true) { + cntlr->curDev->state.bits.readonly = 1; + } + SdFillBusSpeedMode(cntlr); + return HDF_SUCCESS; +} + +static int32_t SdExecuteTuning(struct MmcCntlr *cntlr) +{ + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + + if (dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_DDR50) { + return MmcCntlrTune(cntlr, SD_CMD_SWITCH_FUNC); + } + if ((dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_SDR104) || + (dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_SDR50)) { + return MmcCntlrTune(cntlr, SD_CMD_SEND_TUNING_BLOCK); + } + return HDF_SUCCESS; +} + +static uint32_t SdGetDevMaxCurrentLimitValue(enum SdMaxCurrentLimitBit devCap) +{ + uint32_t currentLimit = 0; + + if (devCap == SD_MAX_CURRENT_LIMIT_800) { + currentLimit = SD_MAX_CURRENT_LIMIT_800_VALUE; + } else if (devCap == SD_MAX_CURRENT_LIMIT_600) { + currentLimit = SD_MAX_CURRENT_LIMIT_600_VALUE; + } else if (devCap == SD_MAX_CURRENT_LIMIT_400) { + currentLimit = SD_MAX_CURRENT_LIMIT_400_VALUE; + } else if (devCap == SD_MAX_CURRENT_LIMIT_200) { + currentLimit = SD_MAX_CURRENT_LIMIT_200_VALUE; + } + return currentLimit; +} + +static uint32_t SdGetMaxCurrentLimitValue(union MmcCaps *hostCap, enum SdMaxCurrentLimitBit devCap) +{ + uint32_t currentLimit; + + /* get max support by dev. */ + currentLimit = SdGetDevMaxCurrentLimitValue(devCap); + if (hostCap->bits.maxCurrentLimit800 == 1) { + currentLimit = ((currentLimit < SD_MAX_CURRENT_LIMIT_800_VALUE) ? + currentLimit : SD_MAX_CURRENT_LIMIT_800_VALUE); + } else if (hostCap->bits.maxCurrentLimit600 == 1) { + currentLimit = ((currentLimit < SD_MAX_CURRENT_LIMIT_600_VALUE) ? + currentLimit : SD_MAX_CURRENT_LIMIT_600_VALUE); + } else if (hostCap->bits.maxCurrentLimit400 == 1) { + currentLimit = ((currentLimit < SD_MAX_CURRENT_LIMIT_400_VALUE) ? + currentLimit : SD_MAX_CURRENT_LIMIT_400_VALUE); + } else if (hostCap->bits.maxCurrentLimit200 == 1) { + currentLimit = ((currentLimit < SD_MAX_CURRENT_LIMIT_200_VALUE) ? + currentLimit : SD_MAX_CURRENT_LIMIT_200_VALUE); + } + return currentLimit; +} + +static int32_t SdSetMaxCurrentLimit(struct MmcCntlr *cntlr) +{ + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + uint8_t status[SD_SWITCH_FUNCTION_STATUS_BYTES_LEN] = {0}; + struct SdSwitchFuncParam param = {0}; + uint32_t currentLimit; + int32_t err; + + if ((dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_SDR104) || + (dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_DDR50) || + (dev->busSpeedMode == SD_BUS_SPEED_MODE_UHS_SDR50)) { + currentLimit = SdGetMaxCurrentLimitValue(&(cntlr->caps), dev->reg.swCaps.sdSpec3CurrLimit); + } else { + currentLimit = SD_MAX_CURRENT_LIMIT_200_VALUE; + } + + param.mode = SD_SWITCH_FUNC_MODE_SET; + param.group = SD_SWITCH_FUNC_GROUP_4; + param.value = currentLimit; + /* Current Limit is selected by CMD6 Function Group 4. */ + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSetMaxCurrentLimit: swutch func group 3 fail!"); + return err; + } + if (((status[15] >> 4) & 0x0F) != currentLimit) { + HDF_LOGD("SdSetMaxCurrentLimit: status not match!"); + } + + return HDF_SUCCESS; +} + +static int32_t SdSetBusSpeedMode(struct MmcCntlr *cntlr) +{ + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + uint8_t status[SD_SWITCH_FUNCTION_STATUS_BYTES_LEN] = {0}; + struct SdSwitchFuncParam param = {0}; + int32_t err; + enum MmcBusTiming timing; + + switch (dev->busSpeedMode) { + case SD_BUS_SPEED_MODE_UHS_SDR104: + timing = BUS_TIMING_UHS_SDR104; + dev->reg.swCaps.uhsMaxDtr = SD_UHS_SDR104_MAX_DTR; + break; + case SD_BUS_SPEED_MODE_UHS_DDR50: + timing = BUS_TIMING_UHS_DDR50; + dev->reg.swCaps.uhsMaxDtr = SD_UHS_DDR50_MAX_DTR; + break; + case SD_BUS_SPEED_MODE_UHS_SDR50: + timing = BUS_TIMING_UHS_SDR50; + dev->reg.swCaps.uhsMaxDtr = SD_UHS_SDR50_MAX_DTR; + break; + case SD_BUS_SPEED_MODE_UHS_SDR25: + timing = BUS_TIMING_UHS_SDR25; + dev->reg.swCaps.uhsMaxDtr = SD_UHS_SDR25_MAX_DTR; + break; + case SD_BUS_SPEED_MODE_UHS_SDR12: + timing = BUS_TIMING_UHS_SDR12; + dev->reg.swCaps.uhsMaxDtr = SD_UHS_SDR12_MAX_DTR; + break; + default: + return HDF_SUCCESS; + } + /* Bus Speed Mode is selected by CMD6 Function Group 1. */ + param.mode = SD_SWITCH_FUNC_MODE_SET; + param.group = SD_SWITCH_FUNC_GROUP_1; + param.value = dev->busSpeedMode; + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSetBusSpeedMode: swutch func group 1 fail!"); + return err; + } + if ((status[16] & 0xF) != dev->busSpeedMode) { + HDF_LOGD("SdSetBusSpeedMode: status not match!"); + } else { + MmcCntlrSetBusTiming(cntlr, timing); + MmcCntlrSetClock(cntlr, dev->reg.swCaps.uhsMaxDtr); + } + + return HDF_SUCCESS; +} + +static int32_t SdSwitch4BitBusWidth(struct MmcCntlr *cntlr, struct SdDevice *dev) +{ + int32_t err = HDF_SUCCESS; + + if ((dev->reg.scr.sdBusWidths & SD_SCR_BUS_WIDTHS_4) > 0 && + (cntlr->caps.bits.cap4Bit > 0)) { + err = SdAcmdSetBusWidth(cntlr, BUS_WIDTH4); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSwitch4BitBusWidth: set 4-bits bus width fail!"); + return err; + } + MmcCntlrSetBusWidth(cntlr, BUS_WIDTH4); + } + return err; +} + +static int32_t SdUltraHighSpeedDevInit(struct MmcCntlr *cntlr) +{ + int32_t err; + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + + if (dev->reg.scr.sdSpec3 == 0) { + return HDF_SUCCESS; + } + if ((cntlr->curDev->reg.csd.ccc & MMC_CSD_CCC_SWITCH) == 0) { + return HDF_SUCCESS; + } + + err = SdSwitch4BitBusWidth(cntlr, dev); + if (err != HDF_SUCCESS) { + return err; + } + err = SdSetMaxCurrentLimit(cntlr); + if (err != HDF_SUCCESS) { + return err; + } + err = SdSetBusSpeedMode(cntlr); + if (err != HDF_SUCCESS) { + return err; + } + return SdExecuteTuning(cntlr); +} + +static int32_t SdSwitchHighSpeed(struct MmcCntlr *cntlr) +{ + int32_t err; + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + uint8_t status[SD_SWITCH_FUNCTION_STATUS_BYTES_LEN] = {0}; + struct SdSwitchFuncParam param = {0}; + + if (dev->reg.swCaps.hsMaxDtr == 0) { + return HDF_ERR_NOT_SUPPORT; + } + if (dev->reg.scr.sdSpec < SD_SCR_SPEC_1) { + return HDF_ERR_NOT_SUPPORT; + } + if (cntlr->caps.bits.highSpeed == 0) { + return HDF_ERR_NOT_SUPPORT; + } + if ((cntlr->curDev->reg.csd.ccc & MMC_CSD_CCC_SWITCH) == 0) { + return HDF_ERR_NOT_SUPPORT; + } + /* Bus Speed Mode is selected by CMD6 Function Group 1. */ + param.mode = SD_SWITCH_FUNC_MODE_SET; + param.group = SD_SWITCH_FUNC_GROUP_1; + param.value = SD_BUS_SPEED_MODE_HS; + err = SdCmdSwitchFunc(cntlr, ¶m, status, SD_SWITCH_FUNCTION_STATUS_BYTES_LEN); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdSwitchHighSpeed: switch func group 1 fail!"); + return err; + } + if ((status[16] & 0xF) != SD_BUS_SPEED_MODE_HS) { + return HDF_ERR_NOT_SUPPORT; + } + return HDF_SUCCESS; +} + +static int32_t SdHighSpeedDevInit(struct MmcCntlr *cntlr) +{ + int err; + struct SdDevice *sdDev = (struct SdDevice *)cntlr->curDev; + + err = SdSwitchHighSpeed(cntlr); + if (err == HDF_SUCCESS) { + cntlr->curDev->state.bits.highSpeed = 1; + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_SD_HS); + } else if (err != HDF_ERR_NOT_SUPPORT) { + HDF_LOGE("SdHighSpeedDevInit: switch high speed fail!"); + return err; + } + MmcCntlrSetClock(cntlr, SdGetMaxClock(cntlr)); + return SdSwitch4BitBusWidth(cntlr, sdDev); +} + +static int32_t SdDeviceAdd(struct MmcCntlr *cntlr) +{ + /* The SD dev must be removable. */ + cntlr->curDev->state.bits.removeable = 1; + SdSetBlockCapacity(cntlr); + /* add dev. */ + if (MmcDeviceAdd(cntlr->curDev) != HDF_SUCCESS) { + HDF_LOGE("SdDeviceAdd: add device fail!"); + return HDF_FAILURE; + } + cntlr->curDev->state.bits.present = 1; + return HDF_SUCCESS; +} + +static int32_t SdInit(struct MmcCntlr *cntlr) +{ + int32_t error; + union MmcOcr ocr = {0}; + + /* acmd41, detect sd dev and get the voltage range. dev state: idle -> ready. */ + error = SdAcmdOpCond(cntlr, 0, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + HDF_LOGE("acmd41(detect sd) fail, err = %d!", error); + return error; + } + + MmcCntlrSelectWorkVoltage(cntlr, &ocr); + if (cntlr->curDev->reg.ocr.ocrData == 0) { + HDF_LOGE("SD work voltage is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + error = SdSelect(cntlr, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + return error; + } + /* get RCA. dev state: ident -> stby. */ + error = SdCmdSendRelativeAddr(cntlr, &(cntlr->curDev->reg.rca)); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd3(get RCA) fail!, error = %d.", error); + return error; + } + /* get CSD, CMD9 should send in stby. dev state: stby -> stby. */ + error = SdReadCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("sd read csd fail!, error = %d.", error); + return error; + } + /* select card. dev state: stby -> tran. */ + error = MmcSelectCard(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd7(select card) fail!, error = %d.", error); + return error; + } + /* dev state: tran -> tran. */ + error = SdReadRegisters(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + + if (ocr.bits.s18r == 1) { + /* uhs dev set */ + error = SdUltraHighSpeedDevInit(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + cntlr->curDev->state.bits.uhs = 1; + } else { + /* highspeed dev set */ + error = SdHighSpeedDevInit(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + } + + return SdDeviceAdd(cntlr); +} + +static int32_t SdDetect(struct MmcCntlr *cntlr) +{ + int32_t ret; + + HDF_LOGD("Detect sd dev start..."); + /* dev state: idle. */ + MmcGoIdleState(cntlr); + /* dev state: idle -> idle. */ + (void)SdCmdSendIfCond(cntlr, cntlr->ocrDef.ocrData); + /* Initialize SD. */ + ret = SdInit(cntlr); + if (ret == HDF_SUCCESS) { + HDF_LOGD("Detect sd dev success! %s dev at address 0x%x!", + cntlr->curDev->state.bits.uhs ? "Ultra high speed" : + (cntlr->curDev->state.bits.highSpeed ? "High speed" : ""), + cntlr->curDev->reg.rca); + } + return ret; +} + +static int32_t SdioSendOpCond(struct MmcCntlr *cntlr, uint32_t arg, uint32_t *ocr) +{ + struct MmcCmd cmd = {0}; + int32_t err; + uint32_t i; + + /* + * An SDIO aware host will send CMD5 prior to the CMD55/ACMD41 pair, and thus would receive a valid OCR in + * the R4 response to CMD5 and continue to initialize the card. + */ + cmd.cmdCode = SDIO_SEND_OP_COND; + /* [23:0] OCR; [24] S18R(Switching to 1.8V Request); [31:25] Stuff Bits. */ + cmd.argument = arg; + cmd.respType = MMC_RESP_R4 | MMC_CMD_TYPE_BCR; + for (i = 0; i < INIT_CMD_RETRY_TIMES; i++) { + err = MmcSendCmd(cntlr, &cmd, NULL, MMC_CMD_DEFAULT_RETRY_TIMES); + if (err != HDF_SUCCESS) { + break; + } + if (arg == 0) { + break; + } + if ((cmd.resp[0] & MMC_CARD_BUSY_STATUS) > 0) { + break; + } + + err = HDF_ERR_TIMEOUT; + OsalMDelay(10); + } + if (ocr != NULL) { + /* + * Response R4 in Sd mode: [23:0] OCR; [24] S18A; [26:25] Stuff Bits; + * [27] Memory Present; [30: 28] Number of I/O functions. + */ + *ocr = cmd.resp[0]; + } + + return err; +} + +static int32_t SdioRespR5Check(struct MmcCmd *cmd) +{ + if (cmd->resp[0] & SDIO_R5_ERROR) { + HDF_LOGE("R5: error!"); + return HDF_ERR_IO; + } + if (cmd->resp[0] & SDIO_R5_OUT_OF_RANGE) { + HDF_LOGE("R5: out of range error!"); + return HDF_ERR_INVALID_PARAM; + } + if (cmd->resp[0] & SDIO_R5_FUNCTION_NUMBER) { + HDF_LOGE("R5: func num error!"); + return HDF_ERR_INVALID_PARAM; + } + return HDF_SUCCESS; +} + +int32_t SdioRwDirect(struct MmcCntlr *cntlr, struct SdioCmdParam *param, uint8_t *out) +{ + struct MmcCmd cmd = {0}; + int32_t err; + + if (cntlr == NULL || param == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + /* + * The IO_RW_DIRECT is the simplest means to access a single register within the total 128K of register space + * in any I/O function, including the common I/O area (CIA). This command reads or writes 1 byte using only 1 + * command/response pair. A common use is to initialize registers or monitor status values for I/O functions. + */ + cmd.cmdCode = SDIO_RW_DIRECT; + /* [31] R/W flag. */ + cmd.argument = ((param->writeflag == true) ? 0x80000000 : 0x00000000); + /* [30:28] Function Number. */ + cmd.argument |= (param->funcNum << 28); + /* [25:9] Register Address. */ + cmd.argument |= (param->regAddr << 9); + /* [7:0] Write Data or Stuff Bits. */ + cmd.argument |= param->writeData; + cmd.respType = MMC_RESP_SPI_R5 | MMC_RESP_R5 | MMC_CMD_TYPE_AC; + err = MmcSendCmd(cntlr, &cmd, NULL, 1); + if (err != HDF_SUCCESS) { + return err; + } + + /* resp error check. */ + err = SdioRespR5Check(&cmd); + if (err != HDF_SUCCESS) { + return err; + } + if (out != NULL) { + *out = cmd.resp[0] & 0xFF; + } + return HDF_SUCCESS; +} + +int32_t SdioRwExtended(struct MmcCntlr *cntlr, struct SdioCmdParam *param, + uint8_t *buf, uint32_t blockNum, uint32_t blockSize) +{ + struct MmcCmd cmd = {0}; + struct MmcData data = {0}; + int32_t err; + + if (cntlr == NULL || param == NULL) { + return HDF_ERR_INVALID_PARAM; + } + /* Register Address: Start Address of I/O register to read or write. Range is [1FFFFh:0]. */ + if (param->regAddr != ((param->regAddr) & 0x1FFFF)) { + return HDF_ERR_INVALID_PARAM; + } + + cmd.cmdCode = SDIO_RW_EXTENDED; + /* [31] R/W flag. */ + cmd.argument = ((param->writeflag == true) ? 0x80000000 : 0x00000000); + /* [30:28] Function Number. */ + cmd.argument |= (param->funcNum << 28); + /* [26] Op Code. */ + cmd.argument |= ((param->incrAddrFlag == true) ? 0x04000000 : 0x00000000); + /* [25:9] Register Address. */ + cmd.argument |= (param->regAddr << 9); + /* + * [8:0] Byte/Block Count. + * If the command is operating on bytes(Block Mode = 0), this field contains the number of bytes + * to read or write. A value of 0 shall cause 512 bytes to be read or written. + * If the command is in block mode(Block Mode = 1), the Block Count field specifies the number + * of Data Blocks to be transferred following this command. + */ + if (blockNum == 1 && blockSize <= 512) { + cmd.argument |= ((blockSize == 512) ? 0 : blockSize); /* byte mode */ + } else { + /* [27] Block Mode. */ + cmd.argument |= (0x08000000 | blockNum); + } + cmd.respType = MMC_RESP_SPI_R5 | MMC_RESP_R5 | MMC_CMD_TYPE_ADTC; + + data.blockSize = blockSize; + data.blockNum = blockNum; + data.dataFlags = ((param->writeflag == true) ? DATA_WRITE : DATA_READ); + if (param->scatterFlag == false) { + data.dataBuffer = buf; + } else { + data.scatter = (void *)buf; + data.scatterLen = param->scatterLen; + } + + err = MmcSendCmd(cntlr, &cmd, &data, 1); + if (err != HDF_SUCCESS) { + return err; + } + + /* resp error check. */ + return SdioRespR5Check(&cmd); +} + +static void SdioIoReset(struct MmcCntlr *cntlr) +{ + struct SdioCmdParam param = {0}; + uint8_t out = 0; + int32_t error; + + /* + * In order to reset an I/O only card or the I/O portion of a combo card, + * use CMD52 to write a 1 to the RES bit in the CCCR(bit3 of register 6), + * because it can't issue CMD52 after CMD0. + */ + param.regAddr = IO_ABORT; + /* read register 6 of CCCR. */ + error = SdioRwDirect(cntlr, ¶m, &out); + if (error < 0) { + out = SDIO_CCCR_RES; + } else { + out |= SDIO_CCCR_RES; + } + /* write the RES bit to 1. */ + param.writeflag = true; + param.writeData = out; + (void)SdioRwDirect(cntlr, ¶m, NULL); +} + +int32_t SdioReadWriteByte(struct MmcCntlr *cntlr, bool writeFlag, + uint32_t funcNum, uint32_t addr, uint8_t *data) +{ + struct SdioCmdParam param = {0}; + + if (cntlr == NULL || data == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + param.regAddr = addr; + param.funcNum = funcNum; + if (writeFlag == true) { + param.writeflag = true; + param.writeData = *data; + return SdioRwDirect(cntlr, ¶m, NULL); + } + return SdioRwDirect(cntlr, ¶m, data); +} + +static int32_t SdioReadWriteRemainBytes(struct MmcCntlr *cntlr, struct SdioCmdParam *param, + uint8_t *data, uint32_t size, uint32_t addr) +{ + uint32_t maxBlkSize, curSize; + struct SdioDevice *dev = (struct SdioDevice *)cntlr->curDev; + uint32_t remLen = size; + uint32_t curAddr = addr; + uint8_t *buffer = data; + int32_t err; + + maxBlkSize = MMC_MIN(cntlr->maxBlkSize, dev->curFunction->maxBlkSize); + maxBlkSize = MMC_MIN(maxBlkSize, BYTES_PER_BLOCK); + if (maxBlkSize == 0) { + HDF_LOGE("max block size is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + while (remLen > 0) { + curSize = MMC_MIN(remLen, maxBlkSize); + param->regAddr = curAddr; + err = SdioRwExtended(cntlr, param, buffer, 1, curSize); + if (err != HDF_SUCCESS) { + HDF_LOGD("SdioReadWriteBlock: bytes mode, err = %d, addr = %d, curSize = %d!", err, addr, curSize); + return err; + } + buffer += curSize; + if (param->incrAddrFlag == true) { + curAddr += curSize; + } + remLen -= curSize; + } + return HDF_SUCCESS; +} + +static void SdioFillRwExtendedCmdParam(struct SdioCmdParam *param, + struct SdioDevice *dev, struct SdioRwBlockInfo *info) +{ + param->funcNum = dev->curFunction->funcNum; + param->incrAddrFlag = info->incrAddrFlag; + param->writeflag = info->writeFlag; + if (info->scatterFlag == true) { + param->scatterFlag = true; + param->scatterLen = info->scatterLen; + param->regAddr = info->addr; + } +} + +int32_t SdioReadWriteBlock(struct MmcCntlr *cntlr, struct SdioRwBlockInfo *info) +{ + uint32_t maxBlkNum, maxBlkSize, curblkNum, curSize, curAddr, remLen; + int32_t err; + struct SdioCmdParam param = {0}; + struct SdioDevice *dev = NULL; + uint8_t *buffer = NULL; + + if (cntlr == NULL || info == NULL) { + return HDF_ERR_INVALID_PARAM; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + maxBlkSize = MMC_MIN(cntlr->maxBlkSize, dev->curFunction->maxBlkSize); + maxBlkSize = MMC_MIN(maxBlkSize, BYTES_PER_BLOCK); + if (maxBlkSize == 0) { + return HDF_ERR_INVALID_PARAM; + } + if (dev->curFunction->curBlkSize == 0 || cntlr->maxBlkNum == 0) { + return HDF_ERR_INVALID_PARAM; + } + + remLen = info->size; + curAddr = info->addr; + buffer = info->buf; + SdioFillRwExtendedCmdParam(¶m, dev, info); + if (info->scatterFlag == true) { + return SdioRwExtended(cntlr, ¶m, buffer, MMC_MAX(1, remLen / maxBlkSize), MMC_MIN(remLen, maxBlkSize)); + } + /* send block. */ + if (dev->sdioReg.cccr.multiBlock > 0 && (remLen > maxBlkSize)) { + maxBlkNum = MMC_MIN((cntlr->maxReqSize / dev->curFunction->curBlkSize), cntlr->maxBlkNum); + maxBlkNum = MMC_MIN(maxBlkNum, SDIO_BLOCK_TRANSFER_MAX_BLKNUM); + while (remLen > dev->curFunction->curBlkSize) { + curblkNum = remLen / dev->curFunction->curBlkSize; + curblkNum = MMC_MIN(curblkNum, maxBlkNum); + curSize = curblkNum * dev->curFunction->curBlkSize; + param.regAddr = curAddr; + err = SdioRwExtended(cntlr, ¶m, buffer, curblkNum, dev->curFunction->curBlkSize); + if (err != HDF_SUCCESS) { + return err; + } + buffer += curSize; + if (info->incrAddrFlag == true) { + curAddr += curSize; + } + remLen -= curSize; + } + } + + /* send remaind bytes. */ + return SdioReadWriteRemainBytes(cntlr, ¶m, buffer, remLen, curAddr); +} + +static int32_t SdioCdDisable(struct MmcCntlr *cntlr) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t ctrl; + + param.regAddr = BUS_INTERFACE_CONTROL; + /* read register 7 of CCCR. */ + error = SdioRwDirect(cntlr, ¶m, &ctrl); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioCdDisable: read BIC fail!"); + return error; + } + /* + * write the CD Disable bit to 1. + * This bit shall be set to 1 before issuing CMD53. + */ + ctrl |= SDIO_CCCR_CD_DISABLE; + param.writeflag = true; + param.writeData = ctrl; + return SdioRwDirect(cntlr, ¶m, NULL); +} + +static int32_t SdioReadCccrSdioRev(struct MmcCntlr *cntlr, struct SdioCccr *cccr, uint8_t *cccrRev) +{ + struct SdioCmdParam param = {0}; + int32_t err; + uint8_t data; + + /* read register 0 of CCCR. */ + param.regAddr = CCCR_SDIO_REVISION; + err = SdioRwDirect(cntlr, ¶m, &data); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdioReadCccrSdioRev: read sdio rev fail!"); + return err; + } + /* bit3-bit0: CCCR_REVISION */ + *cccrRev = data & 0x0f; + if ((*cccrRev) > SDIO_CCCR_VERSION_3_00) { + HDF_LOGE("SdioReadCccrSdioRev: cccr rev error!"); + return HDF_FAILURE; + } + /* bit7-bit4: SDIO_REVISION */ + cccr->sdioRev = (data & 0xf0) >> 4; + return HDF_SUCCESS; +} + +static int32_t SdioReadCccrCapbility(struct MmcCntlr *cntlr, struct SdioCccr *cccr) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t cap; + + /* read register 8 of CCCR. */ + param.regAddr = CARD_CAPBILITY; + error = SdioRwDirect(cntlr, ¶m, &cap); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioReadCccrCapbility: read card cap fail!"); + return error; + } + + if ((cap & SDIO_CCCR_CAP_4BLS) > 0) { + cccr->lowSpeed4Bit = 1; + } + if ((cap & SDIO_CCCR_CAP_LSC) > 0) { + cccr->lowSpeed = 1; + } + if ((cap & SDIO_CCCR_CAP_SMB) > 0) { + cccr->multiBlock = 1; + } + return HDF_SUCCESS; +} + +static int32_t SdioReadCccrPowerControl(struct MmcCntlr *cntlr, struct SdioCccr *cccr) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t ctrl; + + /* read register 18 of CCCR. */ + param.regAddr = POWER_CONTROL; + error = SdioRwDirect(cntlr, ¶m, &ctrl); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioReadCccrPowerControl: read power control fail!"); + return error; + } + + if ((ctrl & SDIO_CCCR_POWER_SMPC) > 0) { + cccr->highPower = 1; + } + return HDF_SUCCESS; +} + +static int32_t SdioReadCccrBusSpeed(struct MmcCntlr *cntlr, struct SdioCccr *cccr) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t speed; + + /* read register 19 of CCCR. */ + param.regAddr = BUS_SPEED_SELECT; + error = SdioRwDirect(cntlr, ¶m, &speed); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioReadCccrBusSpeed: read bus speed select fail!"); + return error; + } + + if ((speed & SDIO_CCCR_BUS_SPEED_SHS) > 0) { + cccr->highSpeed = 1; + } + return HDF_SUCCESS; +} + +int32_t SdioReadCccrIoEnable(struct MmcCntlr *cntlr, uint8_t *val) +{ + struct SdioCmdParam param = {0}; + + if (cntlr == NULL || val == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + /* read register 2(IOEx) of CCCR. */ + param.regAddr = IO_ENABLE; + return SdioRwDirect(cntlr, ¶m, val); +} + +int32_t SdioCccrIoEnable(struct MmcCntlr *cntlr) +{ + struct SdioCmdParam param = {0}; + struct SdioDevice *dev = NULL; + int32_t err; + uint8_t data; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* read register 2(IOEx) of CCCR. */ + param.regAddr = IO_ENABLE; + err = SdioRwDirect(cntlr, ¶m, &data); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdioCccrIoEnable: read io enable fail! err = %d.", err); + return err; + } + /* + * IOEx:Enable Function x. + * If this bit is reset to 0, the function is disable. If this bit is set to 1, the function is enabled to start + * its initialization. The complation of initialization is indicated in IORx. On power up or after a reset, the + * card shall reset this bit to 0. The host can also use IOEx as a per function reset for error recovery. The host + * sequence for a per function reset is to reset IOEx to 0, wait until IORx becomes 0 and then set IOEx to 1 again. + */ + data |= (1 << dev->curFunction->funcNum); + param.writeflag = true; + param.writeData = data; + /* write register 2(IOEx) of CCCR. */ + return SdioRwDirect(cntlr, ¶m, NULL); +} + +int32_t SdioCccrIoDisable(struct MmcCntlr *cntlr) +{ + struct SdioCmdParam param = {0}; + struct SdioDevice *dev = NULL; + int32_t err; + uint8_t data; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* read register 2(IOEx) of CCCR. */ + param.regAddr = IO_ENABLE; + err = SdioRwDirect(cntlr, ¶m, &data); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdioCccrIoDisable: read io enable fail! err = %d.", err); + return err; + } + + data &= (~(1 << dev->curFunction->funcNum)); + param.writeflag = true; + param.writeData = data; + /* write register 2(IOEx) of CCCR. */ + return SdioRwDirect(cntlr, ¶m, NULL); +} + +int32_t SdioReadCccrIoReady(struct MmcCntlr *cntlr, uint8_t *val) +{ + struct SdioCmdParam param = {0}; + + if (cntlr == NULL || val == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + /* read register 3(IORx) of CCCR. */ + param.regAddr = IO_READY; + /* + * IORx: I/O Function x Ready. + * If this bit is set to 0, the function is not ready to operate. This may be caused by the function being + * disabled or not ready due to internal causes such as a built-in-self-test in progress. If this bit is set to 1, + * the function is ready to operate. On power up or after a reset, this bit shall be set to 0. + */ + return SdioRwDirect(cntlr, ¶m, val); +} + +int32_t SdioReadCccrIntPending(struct MmcCntlr *cntlr, uint8_t *val) +{ + struct SdioCmdParam param = {0}; + + if (cntlr == NULL || val == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + /* read register 5(INTx) of CCCR. */ + param.regAddr = INT_PENDING; + /* + * INTx: Interrupt Pending for Function x. + * If this bit is cleared to 0, this indicates that no Interrupts are pending from this function. + * If this bit is set to 1, then this function has Interrupt pending. + * Note that if the IENx or IENM bits are not set, the host cannot receive this pending Interrupt. + */ + return SdioRwDirect(cntlr, ¶m, val); +} + +int32_t SdioCccrIntEnable(struct MmcCntlr *cntlr) +{ + int32_t err; + uint8_t val; + struct SdioCmdParam param = {0}; + struct SdioDevice *dev = NULL; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* read register 4 of CCCR. */ + param.regAddr = INT_ENABLE; + err = SdioRwDirect(cntlr, ¶m, &val); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdioCccrIntEnable: read int enable fail! err = %d.", err); + return err; + } + /* + * [0]IENM: Interrupt Enable Master. + * If this bit is cleared to 0, no interrupts from this card shall be sent to the host. + * If this bit is set to 1, then any function's interrupt shall be sent to the host. + */ + val |= 1; + /* + * [1-7]IENx:Interrupt Enable for Function x. + * If this bit is cleared to 0, any interrupt form this function shall not be sent to the host. + * If this bit is set to 1, function's interrupt shall be sent to the host if the IENM is also set to 1. + */ + val |= (1 << dev->curFunction->funcNum); + param.writeflag = true; + param.writeData = val; + /* write register 4 of CCCR. */ + return SdioRwDirect(cntlr, ¶m, NULL); +} + +int32_t SdioCccrIntDisable(struct MmcCntlr *cntlr) +{ + struct SdioDevice *dev = (struct SdioDevice *)cntlr->curDev; + struct SdioCmdParam param = {0}; + int32_t err; + uint8_t val; + + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* read register 4 of CCCR. */ + param.regAddr = INT_ENABLE; + err = SdioRwDirect(cntlr, ¶m, &val); + if (err != HDF_SUCCESS) { + HDF_LOGE("SdioCccrIntDisable: read int enable fail! err = %d.", err); + return err; + } + /* clear the function's interrupt. */ + val &= (~(1U << dev->curFunction->funcNum)); + if ((val & 0xFE) == 0) { + val = 0; + } + param.writeflag = true; + param.writeData = val; + /* write register 4 of CCCR. */ + return SdioRwDirect(cntlr, ¶m, NULL); +} + +static int32_t SdioReadCccr(struct MmcCntlr *cntlr) +{ + int32_t ret; + uint8_t cccrRev; + struct SdioDevice *sdioDev = NULL; + struct SdioCccr *cccr = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + sdioDev = (struct SdioDevice *)cntlr->curDev; + cccr = &(sdioDev->sdioReg.cccr); + ret = SdioReadCccrSdioRev(cntlr, cccr, &cccrRev); + if (ret != HDF_SUCCESS) { + return ret; + } + ret = SdioReadCccrCapbility(cntlr, cccr); + if (ret != HDF_SUCCESS) { + return ret; + } + + if (cccrRev >= SDIO_CCCR_VERSION_1_10) { + ret = SdioReadCccrPowerControl(cntlr, cccr); + if (ret != HDF_SUCCESS) { + return ret; + } + } + /* SDIO version 1.20 cards indicate their support for High-Speed mode with the SHS bit in the CCCR. */ + if (cccrRev >= SDIO_CCCR_VERSION_1_20) { + ret = SdioReadCccrBusSpeed(cntlr, cccr); + } + return ret; +} + +static int32_t SdioBusSpeedSelect(struct MmcCntlr *cntlr, bool enableHighSpeed) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t speed; + + /* read register 19 of CCCR. */ + param.regAddr = BUS_SPEED_SELECT; + error = SdioRwDirect(cntlr, ¶m, &speed); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioBusSpeedSelect: read bus speed select fail! err = %d.", error); + return error; + } + /* fill BSS0. */ + if (enableHighSpeed == true) { + speed |= SDIO_CCCR_BUS_SPEED_EHS; + } else { + speed &= (~SDIO_CCCR_BUS_SPEED_EHS); + } + /* write BSS0. */ + param.writeflag = true; + param.writeData = speed; + return SdioRwDirect(cntlr, ¶m, NULL); +} + +static int32_t SdioSwitchHighSpeed(struct MmcCntlr *cntlr) +{ + struct SdioDevice *sdioDev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + sdioDev = (struct SdioDevice *)cntlr->curDev; + if (cntlr->caps.bits.highSpeed == 0 || sdioDev->sdioReg.cccr.highSpeed == 0) { + return HDF_ERR_NOT_SUPPORT; + } + return SdioBusSpeedSelect(cntlr, true); +} + +static int32_t SdioEnableHighSpeed(struct MmcCntlr *cntlr) +{ + int32_t err; + + err = SdioSwitchHighSpeed(cntlr); + if (cntlr->curDev->type == MMC_DEV_SDIO || err != HDF_SUCCESS) { + return err; + } + + /* COMBO card, need switch SD memory. */ + err = SdSwitchHighSpeed(cntlr); + if (err == HDF_SUCCESS) { + return err; + } + /* sd switch fail, need switch sdio to default speed. */ + if (SdioBusSpeedSelect(cntlr, false) != HDF_SUCCESS) { + HDF_LOGD("SdioEnableHighSpeed: switch sdio to default speed fail."); + } + return err; +} + +static int32_t SdioSetBusWidth(struct MmcCntlr *cntlr, uint8_t width) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t data; + + /* read register 7 of CCCR. */ + param.regAddr = BUS_INTERFACE_CONTROL; + error = SdioRwDirect(cntlr, ¶m, &data); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioSetBusWidth: read BIC fail, error = %d!", error); + return error; + } + + data |= width; + /* write bit1-bit0: Bus Width. */ + param.writeflag = true; + param.writeData = data; + return SdioRwDirect(cntlr, ¶m, NULL); +} + +static int32_t SdioSwitch4BitBusWidth(struct MmcCntlr *cntlr) +{ + struct SdioDevice *sdioDev = NULL; + + if (cntlr == NULL || cntlr->curDev == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + sdioDev = (struct SdioDevice *)cntlr->curDev; + if (cntlr->caps.bits.cap4Bit == 0) { + return HDF_ERR_NOT_SUPPORT; + } + /* + * Note that Low-Speed SDIO cards support 4-bit transfer as an optipn. When communicating with a + * Low-Speed SDIO card, the host shall fist determine if the card supports 4-bit transfer prior to + * attempting to select that mode. + */ + if (sdioDev->sdioReg.cccr.lowSpeed > 0 && sdioDev->sdioReg.cccr.lowSpeed4Bit == 0) { + return HDF_ERR_NOT_SUPPORT; + } + return SdioSetBusWidth(cntlr, SDIO_CCCR_WIDTH_4BIT); +} + +static int32_t SdioEnable4BitBusWidth(struct MmcCntlr *cntlr) +{ + int32_t error; + struct SdDevice *dev = (struct SdDevice *)cntlr->curDev; + + /* + * For an SD memory card, the bus width for SD mode is set using ACMD6. + * For an SDIO card a write to the CCCR usingCMD52 is used to select bus width. + * In the case of a combo card, both selection methods exist. + */ + error = SdioSwitch4BitBusWidth(cntlr); + if (cntlr->curDev->type == MMC_DEV_SDIO || error != HDF_SUCCESS) { + return error; + } + + /* COMBO card, need switch SD memory. */ + if ((dev->reg.scr.sdBusWidths & SD_SCR_BUS_WIDTHS_4) > 0 && + (cntlr->caps.bits.cap4Bit > 0)) { + error = SdAcmdSetBusWidth(cntlr, BUS_WIDTH4); + } + + return error; +} + +static int32_t SdioReadCisTplField(struct MmcCntlr *cntlr, uint32_t addr, uint8_t *data) +{ + struct SdioCmdParam param = {0}; + + param.regAddr = addr; + return SdioRwDirect(cntlr, ¶m, data); +} + +static void SdioDecodeCisTplManfId(struct MmcCntlr *cntlr, struct SdioFunction *function, + struct SdioCisTuple *tuple) +{ + uint16_t vendorId, deviceId; + struct SdioDevice *dev = NULL; + + if (tuple->tplLink < SDIO_CIS_TPL_MANFID_MIN_SIZE) { + return; + } + + /* + * CISTPL_MANFID Field: bit00[TPL_CODE(20)], bit01[TPL_LINK(at least 4)], bit02-03[SDIO Card manufacturer code], + * bit04-05[manufacturer information(Part Number and /or Revision)]. + * bit02-03-->tplBody[0:1], bit04-05-->tplBody[2:3]. + */ + vendorId = (tuple->tplBody[1] << BITS_PER_BYTE) | tuple->tplBody[0]; + deviceId = (tuple->tplBody[3] << BITS_PER_BYTE) | tuple->tplBody[2]; + HDF_LOGD("Sdio vendorId = 0x%x, deviceId = 0x%x.", vendorId, deviceId); + /* function CISTPL_MANFID. */ + if (function != NULL) { + function->deviceId = deviceId; + function->vendorId = vendorId; + return; + } + + /* common CISTPL_MANFID. */ + dev = (struct SdioDevice *)cntlr->curDev; + dev->sdioReg.cis.deviceId = deviceId; + dev->sdioReg.cis.vendorId = vendorId; +} + +static void SdioDecodeCisTplFunceCommon(struct MmcCntlr *cntlr, struct SdioCisTuple *tuple) +{ + struct SdioDevice *dev = (struct SdioDevice *)cntlr->curDev; + const uint8_t value[16] = { 0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80 }; + const uint32_t unit[8] = { 10000, 100000, 1000000, 10000000, 0, 0, 0, 0 }; + + if (tuple->tplLink < SDIO_CIS_TPL_FUNCE_COMMON_MIN_SIZE) { + return; + } + + /* + * CISTPL_FUNCE(common): bit00[TPL_CODE(22h)], bit01[TPL_LINK], bit02[TPLFE_TYPE(00h)], + * bit03-04[TPLFE_FN0_BLK_SIZE], bit05[TPLFE_MAX_TRAN_SPEED]. + * bit2-->tplBody[0], bit03-04-->tplBody[1:2], bit05-->tplBody[3]. + */ + dev->sdioReg.cis.blkSize = (tuple->tplBody[2] << BITS_PER_BYTE) | tuple->tplBody[1]; + + /* + * This byte indicates the maximum transfer rate per one data line during data transfer. This value applies to + * all functions in the SDIO card. This value shall be 25Mb/Sec(32h) for all Full-Speed SDIO card. The minimum + * value for Low-Speed SDIO cards shall be 400 Kb/Sec(48h). The format is identical to the TRAN_SPEED value stored + * in the CSD of SD memory cards. The maximum data transfer rate is coded according to the following method: + * Bits 2:0 contain the transfer rate unit coded as follows: + * 0=100kbit/s, 1=1Mbit/s, 2=10Mbit/s, 3=100Mbit/s, ... 7=reserved. + * Bits 6:3 contain the time value coded as follows: + * 0=reserved, 1=1.0, 2=1.2, 3=1.3, 4=1.5, 5=2.0, 6=2.5, 7=3.0, 8= 3.5, 9=4.0, A=4.5, B=5.0, C=5.5, D=6.0, E=7.0, + * F= 8.0. + * Bit 7 is reserved and shall be 0. + */ + dev->sdioReg.cis.maxDtr = unit[tuple->tplBody[3] & 7] * value[(tuple->tplBody[3] >> 3) & 15]; +} + +static void SdioDecodeCisTplFunceFunction(struct SdioFunction *function, struct SdioCisTuple *tuple) +{ + uint32_t minSize; + + /* Rev 1.0, TPL_LINK 28bytes; >Rev 1.0, TPL_LINK 42bytes. */ + minSize = (function->dev->sdioReg.cccr.sdioRev == SDIO_CCCR_SDIO_REV_1_00) ? + SDIO_CIS_TPL_FUNCE_FUNCTION_PC_MIN_SIZE : SDIO_CIS_TPL_FUNCE_FUNCTION_PC_MAX_SIZE; + if (tuple->tplLink < minSize) { + return; + } + + /* + * CISTPL_FUNCE(function): bit00[TPL_CODE(22h)], bit01[TPL_LINK], bit02[TPLFE_TYPE(01h)], + * bit0E-0F[TPLFE_MAX_BLK_SIZE], bit1E-1F[TPLFE_ENABLE_TIMEOUT_VAL]. + * bit2-->tplBody[0], bit0E-0F-->tplBody[12:13], bit1E-1F-->tplBody[28:29]. + */ + function->maxBlkSize = (tuple->tplBody[13] << BITS_PER_BYTE) | tuple->tplBody[12]; + + /* + * TPLFE_ENABLE_TIMEOUT_VAL is added in SDIO Rev 1.1. This 16-bit value indicates the function's required time-out + * value for coming ready after being enabled. This per-function value indicated the time a host should wait from + * asserting IOEx until expecting the card to indicate ready by asserting IORx. Different SDIO functions take + * different amounts of time to become raedy after being enabled due to different internal initialization + * requirements. The required time-out limit is in 10mS steps. If the card required no time-out, this field shall + * be set to 0000h. + */ + if (function->dev->sdioReg.cccr.sdioRev > SDIO_CCCR_SDIO_REV_1_00) { + function->timeOut = (tuple->tplBody[28] | (tuple->tplBody[29] << BITS_PER_BYTE)) * 10; + } else { + function->timeOut = SDIO_CIS_TPLFE_ENABLE_TIMEOUT_VAL_DEF; + } +} + +static void SdioDecodeCisTplFunce(struct MmcCntlr *cntlr, struct SdioFunction *function, + struct SdioCisTuple *tuple) +{ + /* + * The Function Extension Tuple provides standard information about the card(common) and each individual function. + * There shall be one CISTPL_FUNCE in each function's CIS. There are two versions of the CISTPL_FUNCE tuple, one + * for the common CIS(function 0) and a version uesd by the individual function's CIS(1-7). + */ + if (tuple->tplBody[0] == SDIO_CIS_TPL_FUNCE_COMMON) { + if (function != NULL) { + return; + } + SdioDecodeCisTplFunceCommon(cntlr, tuple); + return; + } + + if (tuple->tplBody[0] == SDIO_CIS_TPL_FUNCE_FUNCTION_PC) { + if (function == NULL) { + return; + } + SdioDecodeCisTplFunceFunction(function, tuple); + } +} + +static void SdioDecodeCisTplField(struct MmcCntlr *cntlr, struct SdioFunction *function, + struct SdioCisTuple *tuple) +{ + /* decode MANFID. */ + if (tuple->tplCode == SDIO_CIS_TPL_MANFID) { + SdioDecodeCisTplManfId(cntlr, function, tuple); + return; + } + /* decode FUNCE. */ + if (tuple->tplCode == SDIO_CIS_TPL_FUNCE) { + SdioDecodeCisTplFunce(cntlr, function, tuple); + } +} + +static int32_t SdioFillTplInfo(struct MmcCntlr *cntlr, struct SdioCisTuple *tuple, + uint32_t *addr, uint8_t tplCode, uint8_t tplLink) +{ + int32_t ret; + uint32_t i; + + tuple->tplCode = tplCode; + tuple->tplLink = tplLink; + /* read tuple body. */ + for (i = 0; i < tplLink; i++) { + (*addr)++; + ret = SdioReadCisTplField(cntlr, *addr, &(tuple->tplBody[i])); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioFillTplInfo: read tuple body fail, err = %d.", ret); + return ret; + } + } + return HDF_SUCCESS; +} + +static int32_t SdioDecodeCis(struct MmcCntlr *cntlr, struct SdioFunction *function, uint32_t cisStartAddr) +{ + int32_t ret = HDF_SUCCESS; + uint8_t tplCode, tplLink; + struct SdioCisTuple *tuple = NULL; + uint32_t addr = cisStartAddr; + + while (ret == HDF_SUCCESS) { + /* read TPL_CODE. */ + ret = SdioReadCisTplField(cntlr, addr, &tplCode); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDecodeCis: read TPL_CODE fail, err = %d.", ret); + return ret; + } + if (tplCode == SDIO_CIS_TPL_END || tplCode == SDIO_CIS_TPL_NULL) { + return HDF_SUCCESS; + } + /* read TPL_LINK. */ + addr++; + ret = SdioReadCisTplField(cntlr, addr, &tplLink); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDecodeCis: read TPL_LINK fail, err = %d.", ret); + return ret; + } + if (tplLink == SDIO_CIS_TPL_END) { + return HDF_SUCCESS; + } + /* If the link field is 0, the the tuple body is empty. */ + if (tplLink == SDIO_CIS_TPL_NULL) { + continue; + } + + tuple = (struct SdioCisTuple *)OsalMemCalloc(sizeof(*tuple) + tplLink); + if (tuple == NULL) { + HDF_LOGE("SdioDecodeCis: mem alloc fail!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = SdioFillTplInfo(cntlr, tuple, &addr, tplCode, tplLink); + if (ret != HDF_SUCCESS) { + OsalMemFree(tuple); + return ret; + } + /* decode. */ + SdioDecodeCisTplField(cntlr, function, tuple); + OsalMemFree(tuple); + tuple = NULL; + addr++; + } + return ret; +} + +static int32_t SdioReadCis(struct MmcCntlr *cntlr, struct SdioFunction *function) +{ + uint32_t funcNum, i, cisStartAddr; + uint8_t data; + int32_t ret; + struct SdioCmdParam param = {0}; + + if (function == NULL) { + funcNum = 0; + } else { + funcNum = function->funcNum; + } + + /* read CIS pointer. */ + cisStartAddr = 0; + for (i = 0; i < SDIO_CCCR_CIS_START_ADDR_BYTES; i++) { + /* read register 0xn09-0xn0B of FBR. */ + param.regAddr = SDIO_FBR_BASE_ADDR(funcNum) + SDIO_FBR_POINTER_CIS + i; + ret = SdioRwDirect(cntlr, ¶m, &data); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReadCis: read CIS pointer fail, err = %d.", ret); + return ret; + } + cisStartAddr |= data << (i * BITS_PER_BYTE); + } + return SdioDecodeCis(cntlr, function, cisStartAddr); +} + +static int32_t SdioReadFbr(struct MmcCntlr *cntlr, struct SdioFunction *func) +{ + struct SdioCmdParam param = {0}; + int32_t error; + uint8_t data; + + /* read register 0xn00 of FBR. */ + param.regAddr = SDIO_FBR_BASE_ADDR(func->funcNum) + SDIO_FBR_STD_FUNCTION_INTERFACE_CODE; + error = SdioRwDirect(cntlr, ¶m, &data); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioReadFbr: read SFIC fail, err = %d.", error); + return error; + } + + /* bit3-bit0: Standard SDIO Function Interface Code. */ + data &= 0x0f; + if (data == SDIO_FBR_STD_SDIO_IF) { + /* read register 0xn01 of FBR. */ + param.regAddr = SDIO_FBR_BASE_ADDR(func->funcNum) + SDIO_FBR_EXT_STD_FUNCTION_INTERFACE_CODE; + error = SdioRwDirect(cntlr, ¶m, &data); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioReadFbr: read ESFIC fail, err = %d.", error); + return error; + } + } + + func->funcClass = data; + return HDF_SUCCESS; +} + +int32_t SdioSetFbrIoBlockSize(struct MmcCntlr *cntlr, uint32_t blkSize) +{ + struct SdioCmdParam param = {0}; + struct SdioDevice *dev = NULL; + int32_t ret; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct SdioDevice *)cntlr->curDev; + if (dev == NULL || dev->curFunction == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* write register 0xn10 of FBR. */ + param.regAddr = SDIO_FBR_BASE_ADDR(dev->curFunction->funcNum) + SDIO_FBR_IO_BLOCK_SIZE; + param.writeflag = true; + /* + * Function 1-7 I/O Block Size. + * This 16-bit register sets the block size for I/O block operations for each function(1-7). + * The maximum block size is 2048 and the minimum is 1. At power-up or reset, this register + * shall be initially loaded with a value of 0. The host is responsible for setting the appropriate + * value for the block size supported by each function. This pointer is stored in little-endian format. + */ + param.writeData = (blkSize & 0xff); + ret = SdioRwDirect(cntlr, ¶m, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioSetFbrIoBlockSize: write I/O Block Size fail, err = %d.", ret); + return ret; + } + + /* write register 0xn11 of FBR. */ + param.regAddr++; + param.writeData = ((blkSize >> BITS_PER_BYTE) & 0xff); + return SdioRwDirect(cntlr, ¶m, NULL); +} + +static uint32_t SdioGetMaxClock(struct MmcCntlr *cntlr) +{ + uint32_t clock; + struct MmcDevice *mmcDev = cntlr->curDev; + struct SdioDevice *sdioDev = (struct SdioDevice *)mmcDev; + + if (mmcDev->state.bits.highSpeed == 1) { + /* The card operates in High-Speed timing mode with a clock rate up to 50MHz. */ + clock = 50000000; + } else { + clock = sdioDev->sdioReg.cis.maxDtr; + } + + if (mmcDev->type == MMC_DEV_COMBO) { + clock = (clock < SdGetMaxClock(cntlr)) ? clock : SdGetMaxClock(cntlr); + } + + if (clock > cntlr->freqMax) { + clock = cntlr->freqMax; + } + return clock; +} + +static struct SdioFunction *SdioAllocFunction(struct SdioDevice *sdioDev, uint32_t funcNum) +{ + struct SdioFunction *function = NULL; + + function = (struct SdioFunction *)OsalMemCalloc(sizeof(struct SdioFunction)); + if (function == NULL) { + HDF_LOGE("SdioAllocFunction: alloc fail!"); + return NULL; + } + function->dev = sdioDev; + function->funcNum = funcNum; + return function; +} + +static void SdioDeleteFunction(struct SdioFunction *function) +{ + if (function == NULL) { + return; + } + OsalMemFree(function); +} + +static int32_t SdioAddFunctions(struct MmcCntlr *cntlr, uint32_t funcs) +{ + struct SdioDevice *sdioDev = (struct SdioDevice *)cntlr->curDev; + struct SdioFunction *function = NULL; + uint32_t i; + int32_t ret; + + sdioDev->functions = 0; + for (i = 0; i < funcs; i++) { + function = SdioAllocFunction(sdioDev, i + 1); + if (function == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + ret = SdioReadFbr(cntlr, function); + if (ret != HDF_SUCCESS) { + return ret; + } + ret = SdioReadCis(cntlr, function); + if (ret != HDF_SUCCESS) { + SdioDeleteFunction(function); + return ret; + } + + if (function->vendorId == 0) { + function->vendorId = sdioDev->sdioReg.cis.vendorId; + function->deviceId = sdioDev->sdioReg.cis.deviceId; + } + /* A value of zero is not valid and shall not be used. */ + if (function->maxBlkSize == 0) { + function->maxBlkSize = sdioDev->sdioReg.cis.blkSize; + } + + sdioDev->sdioFunc[i] = function; + (sdioDev->functions)++; + } + return HDF_SUCCESS; +} + +static void SdioDelete(struct SdioDevice *sdioDev) +{ + uint32_t i; + + for (i = 0; i < sdioDev->functions; i++) { + SdioDeleteFunction(sdioDev->sdioFunc[i]); + sdioDev->sdioFunc[i] = NULL; + } +} + +static int32_t SdioDeviceAdd(struct MmcCntlr *cntlr) +{ + /* add dev. */ + if (MmcDeviceAdd(cntlr->curDev) != HDF_SUCCESS) { + HDF_LOGE("SdioDeviceAdd: Add device fail!"); + return HDF_FAILURE; + } + cntlr->curDev->state.bits.present = 1; + return HDF_SUCCESS; +} + +static int32_t SdioSelect(struct MmcCntlr *cntlr, uint32_t *rocr) +{ + int32_t error; + + /* cmd5, set the support voltage. */ + error = SdioSendOpCond(cntlr, cntlr->curDev->reg.ocr.ocrData, rocr); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd5(set voltage) fail, err = %d.", error); + return error; + } + + /* Judge Combo Card. */ + if (((*rocr) & SDIO_R4_MEMORY_PRESENT) > 0) { + if (SdSelect(cntlr, rocr) == 0) { + cntlr->curDev->type = MMC_DEV_COMBO; + HDF_LOGD("combo dev!!"); + } + } + /* get RCA. */ + error = SdCmdSendRelativeAddr(cntlr, &(cntlr->curDev->reg.rca)); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd3(get RCA) fail, err = %d.", error); + return error; + } + if (cntlr->curDev->type == MMC_DEV_COMBO) { + /* get CSD, CMD9 should send in stby. */ + error = SdReadCsd(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("combo dev, read csd fail, err = %d.", error); + return error; + } + } + /* select card. */ + error = MmcSelectCard(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd7(select card) fail, err = %d.", error); + return error; + } + + error = SdioReadCccr(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("read cccr fail, err = %d.", error); + return error; + } + /* read common CIS. */ + error = SdioReadCis(cntlr, NULL); + if (error != HDF_SUCCESS) { + HDF_LOGE("SdioInit: read cis fail, err = %d.", error); + return error; + } + if (cntlr->curDev->type == MMC_DEV_COMBO) { + error = SdReadRegisters(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("combo dev, read registers fail, err = %d.", error); + MmcGoIdleState(cntlr); + cntlr->curDev->type = MMC_DEV_SDIO; + } + } + return HDF_SUCCESS; +} + +static int32_t SdioInit(struct MmcCntlr *cntlr) +{ + int32_t error; + union MmcOcr ocr = {0}; + + /* cmd5, detect sdio dev and get the voltage range. */ + error = SdioSendOpCond(cntlr, 0, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + HDF_LOGE("cmd5(detect sdio) fail, err = %d", error); + return error; + } + + MmcCntlrSelectWorkVoltage(cntlr, &ocr); + if (cntlr->curDev->reg.ocr.ocrData == 0) { + HDF_LOGE("SdioInit: ocr is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + error = SdioSelect(cntlr, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + return error; + } + + error = SdioCdDisable(cntlr); + if (error != HDF_SUCCESS) { + HDF_LOGE("Cd disable fail, err = %d.", error); + return error; + } + error = SdioEnableHighSpeed(cntlr); + if (error == HDF_SUCCESS) { + cntlr->curDev->state.bits.highSpeed = 1; + MmcCntlrSetBusTiming(cntlr, BUS_TIMING_SD_HS); + } else if (error != HDF_ERR_NOT_SUPPORT) { + HDF_LOGE("Enable HS fail, err = %d.", error); + return error; + } + MmcCntlrSetClock(cntlr, SdioGetMaxClock(cntlr)); + + error = SdioEnable4BitBusWidth(cntlr); + if (error == HDF_SUCCESS) { + MmcCntlrSetBusWidth(cntlr, BUS_WIDTH4); + } else if (error != HDF_ERR_NOT_SUPPORT) { + HDF_LOGE("Enable 4-bits bus width fail, err = %d.", error); + return error; + } + /* R4, [30: 28] Number of I/O functions. */ + error = SdioAddFunctions(cntlr, ((ocr.ocrData >> 28) & SDIO_MAX_FUNCTION_NUMBER)); + if (error != HDF_SUCCESS) { + HDF_LOGE("Add functions fail, err = %d.", error); + return error; + } + + return SdioDeviceAdd(cntlr); +} + +int32_t SdioReinit(struct MmcCntlr *cntlr) +{ + union MmcOcr ocr = {0}; + int error; + + MmcGoIdleState(cntlr); + MmcCntlrSetClock(cntlr, cntlr->freqMin); + + /* cmd5, detect sdio dev and get the voltage range. */ + error = SdioSendOpCond(cntlr, 0, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + return error; + } + /* cmd5, set the support voltage. */ + error = SdioSendOpCond(cntlr, cntlr->curDev->reg.ocr.ocrData, &(ocr.ocrData)); + if (error != HDF_SUCCESS) { + return error; + } + /* get RCA. */ + error = SdCmdSendRelativeAddr(cntlr, &(cntlr->curDev->reg.rca)); + if (error != HDF_SUCCESS) { + return error; + } + /* select card. */ + error = MmcSelectCard(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + error = SdioEnableHighSpeed(cntlr); + if (error != HDF_SUCCESS) { + return error; + } + MmcCntlrSetClock(cntlr, SdioGetMaxClock(cntlr)); + + error = SdioEnable4BitBusWidth(cntlr); + if (error == HDF_SUCCESS) { + MmcCntlrSetBusWidth(cntlr, BUS_WIDTH4); + } + return error; +} + +static int32_t SdioDetect(struct MmcCntlr *cntlr) +{ + int32_t err; + + HDF_LOGD("Detect sdio dev start..."); + /* + * After reset or power-up, all I/O functions on the card are disabled and the I/O portion of the card shall + * not execute any operation except CMD5 or CMD0. If there is SD memory on the card, that memory shall + * respond normally to all mandatory memory commands. + */ + SdioIoReset(cntlr); + MmcGoIdleState(cntlr); + /* Initialize SDIO. */ + err = SdioInit(cntlr); + if (err == HDF_SUCCESS) { + HDF_LOGD("Detect sdio dev success! %s dev at address 0x%x!", + cntlr->curDev->state.bits.highSpeed ? "High speed" : "", cntlr->curDev->reg.rca); + return HDF_SUCCESS; + } + SdioDelete((struct SdioDevice *)cntlr->curDev); + return err; +} + +void MmcDeleteDev(struct MmcCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->curDev == NULL) { + return; + } + + if (cntlr->curDev->state.bits.present == 0) { + return; + } + cntlr->curDev->state.bits.present = 0; + + if (cntlr->curDev->type == MMC_DEV_SDIO || cntlr->curDev->type == MMC_DEV_COMBO) { + SdioDelete((struct SdioDevice *)cntlr->curDev); + } + + MmcDeviceRemove(cntlr->curDev); + MmcCntlrFreeDev(cntlr); +} + +int32_t MmcDoDetect(struct MmcCntlr *cntlr) +{ + int32_t error; + enum MmcDevType devType; + + if (cntlr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + devType = (enum MmcDevType)cntlr->devType; + if (devType >= MMC_DEV_COMBO) { + return HDF_ERR_INVALID_PARAM; + } + + if (MmcCntlrAllocDev(cntlr, devType) != HDF_SUCCESS) { + return HDF_ERR_INVALID_PARAM; + } + + MmcCntlrPowerUp(cntlr); + if (devType == MMC_DEV_SDIO) { + error = SdioDetect(cntlr); + } else if (devType == MMC_DEV_SD) { + error = SdDetect(cntlr); + } else { + error = EmmcDetect(cntlr); + } + + if (error == HDF_SUCCESS) { + HDF_LOGD("MmcDoDetect: host%d detect succ!", cntlr->index); + return error; + } + + HDF_LOGD("MmcDoDetect: host%d detect fail!", cntlr->index); + MmcCntlrFreeDev(cntlr); + MmcCntlrPowerOff(cntlr); + return error; +} diff --git a/support/platform/src/mmc/mmc_sdio.c b/support/platform/src/mmc/mmc_sdio.c new file mode 100644 index 00000000..9c39e7f5 --- /dev/null +++ b/support/platform/src/mmc/mmc_sdio.c @@ -0,0 +1,757 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "mmc_sdio.h" + +#define HDF_LOG_TAG mmc_sdio_c +#define SDIO_READ_IO_READY_RETRY_TIMES 10000 + +static int32_t SdioDeviceDefaultIncrAddrReadBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + struct SdioRwBlockInfo info = {0}; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrReadBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrReadBytes fail, data is null."); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrReadBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + if (size == 1) { + return SdioReadWriteByte(cntlr, false, func->funcNum, addr, data); + } else if (size > 1) { + info.addr = addr; + info.buf = data; + info.incrAddrFlag = true; + info.size = size; + info.writeFlag = false; + return SdioReadWriteBlock(cntlr, &info); + } + HDF_LOGE("SdioDeviceDefaultIncrAddrReadBytes fail, data size is 0."); + return HDF_ERR_INVALID_PARAM; +} + +static int32_t SdioDeviceDefaultIncrAddrWriteBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + struct SdioRwBlockInfo info = {0}; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrWriteBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrWriteBytes fail, data is null."); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultIncrAddrWriteBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + if (size == 1) { + return SdioReadWriteByte(cntlr, true, func->funcNum, addr, data); + } else if (size > 1) { + info.addr = addr; + info.buf = data; + info.incrAddrFlag = true; + info.size = size; + info.writeFlag = true; + return SdioReadWriteBlock(cntlr, &info); + } + HDF_LOGE("SdioDeviceDefaultIncrAddrWriteBytes fail, data size is 0."); + return HDF_ERR_INVALID_PARAM; +} + +static int32_t SdioDeviceDefaultFixedAddrReadBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + struct SdioRwBlockInfo info = {0}; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultFixedAddrReadBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL || size == 0) { + HDF_LOGE("SdioDeviceDefaultFixedAddrReadBytes fail, param is invalid."); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultFixedAddrReadBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + info.addr = addr; + info.buf = data; + info.incrAddrFlag = false; + info.size = size; + info.writeFlag = false; + if (scatterLen > 0) { + info.scatterFlag = true; + info.scatterLen = scatterLen; + } + return SdioReadWriteBlock(cntlr, &info); +} + +static int32_t SdioDeviceDefaultFixedAddrWriteBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + struct SdioRwBlockInfo info = {0}; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultFixedAddrWriteBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL || size == 0) { + HDF_LOGE("SdioDeviceDefaultFixedAddrWriteBytes fail, param is invalid."); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultFixedAddrWriteBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + info.addr = addr; + info.buf = data; + info.incrAddrFlag = false; + info.size = size; + info.writeFlag = true; + if (scatterLen > 0) { + info.scatterFlag = true; + info.scatterLen = scatterLen; + } + return SdioReadWriteBlock(cntlr, &info); +} + +static int32_t SdioDeviceDefaultFunc0ReadBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + uint32_t i; + int32_t ret; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0ReadBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0ReadBytes fail, data is null."); + return HDF_ERR_INVALID_PARAM; + } + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0ReadBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + for (i = 0; i < size; i++) { + ret = SdioReadWriteByte(cntlr, false, 0, (addr + i), &data[i]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDeviceDefaultFunc0ReadBytes fail, i = %d.", i); + return ret; + } + } + return HDF_SUCCESS; +} + +static int32_t SdioDeviceDefaultFunc0WriteBytes(struct SdioDevice *dev, + uint8_t *data, uint32_t addr, uint32_t size) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + int32_t ret; + uint32_t i; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0WriteBytes fail, func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (data == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0WriteBytes fail, data is null."); + return HDF_ERR_INVALID_PARAM; + } + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultFunc0WriteBytes fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + + for (i = 0; i < size; i++) { + ret = SdioReadWriteByte(cntlr, true, 0, (addr + i), &data[i]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDeviceDefaultFunc0WriteBytes fail, i = %d.", i); + return ret; + } + } + return HDF_SUCCESS; +} + +static int32_t SdioDeviceDefaultSetBlockSize(struct SdioDevice *dev, uint32_t blkSize) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + uint32_t blockSize = blkSize; + int32_t ret; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultSetBlockSize: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = dev->sd.mmc.cntlr; + if (blockSize == 0) { + blockSize = ((func->maxBlkSize < cntlr->maxBlkSize) ? func->maxBlkSize : cntlr->maxBlkSize); + } + blockSize = MMC_MIN(blockSize, MMC_SEC_SIZE); + + ret = SdioSetFbrIoBlockSize(cntlr, blockSize); + if (ret == HDF_SUCCESS) { + func->curBlkSize = blockSize; + } + return ret; +} + +static int32_t SdioDeviceDefaultGetCommonInfo(struct SdioDevice *dev, + SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + struct MmcCntlr *cntlr = NULL; + struct SdioFunction *func = dev->curFunction; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultGetCommonInfo: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (info == NULL) { + HDF_LOGE("SdioDeviceDefaultGetCommonInfo: info is null."); + return HDF_ERR_INVALID_PARAM; + } + if (infoType != SDIO_FUNC_INFO) { + HDF_LOGE("SdioDeviceDefaultGetCommonInfo: cur type %d is not support.", infoType); + return HDF_ERR_NOT_SUPPORT; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultGetCommonInfo fail, cntlr is null."); + return HDF_ERR_INVALID_PARAM; + } + info->funcInfo.enTimeout = func->timeOut; + info->funcInfo.maxBlockNum = cntlr->maxBlkNum; + info->funcInfo.maxBlockSize = cntlr->maxBlkSize; + info->funcInfo.maxRequestSize = cntlr->maxReqSize; + info->funcInfo.funcNum = func->funcNum; + info->funcInfo.irqCap = cntlr->caps.bits.sdioIrq; + info->funcInfo.data = (void *)func; + return HDF_SUCCESS; +} + +static int32_t SdioDeviceDefaultSetCommonInfo(struct SdioDevice *dev, + SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + struct MmcCntlr *cntlr = NULL; + struct SdioFunction *func = dev->curFunction; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultSetCommonInfo: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (info == NULL) { + HDF_LOGE("SdioDeviceDefaultSetCommonInfo: info is null."); + return HDF_ERR_INVALID_PARAM; + } + if (infoType != SDIO_FUNC_INFO) { + HDF_LOGE("SdioDeviceDefaultSetCommonInfo: cur type %d is not support.", infoType); + return HDF_ERR_NOT_SUPPORT; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultSetCommonInfo fail, cntlr is null."); + return HDF_ERR_INVALID_PARAM; + } + + func->timeOut = info->funcInfo.enTimeout; + cntlr->maxBlkNum = info->funcInfo.maxBlockNum; + cntlr->maxBlkSize = info->funcInfo.maxBlockSize; + cntlr->maxReqSize = info->funcInfo.maxRequestSize; + func->funcNum = info->funcInfo.funcNum; + return HDF_SUCCESS; +} + +static int32_t SdioDeviceDefaultFlushData(struct SdioDevice *dev) +{ + struct MmcCntlr *cntlr = NULL; + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultFlushData fail, cntlr is null."); + return HDF_ERR_INVALID_OBJECT; + } + return SdioReinit(cntlr); +} + +static int32_t SdioDeviceDefaultEnableFunc(struct SdioDevice *dev) +{ + struct SdioFunction *func = dev->curFunction; + int32_t ret; + uint32_t i; + uint8_t val; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultEnableFunc: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + ret = SdioCccrIoEnable(dev->sd.mmc.cntlr); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDeviceDefaultEnableFunc: Io Enable fail."); + return ret; + } + + for (i = 0; i < SDIO_READ_IO_READY_RETRY_TIMES; i++) { + ret = SdioReadCccrIoReady(dev->sd.mmc.cntlr, &val); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDeviceDefaultEnableFunc: read Io Ready fail."); + return ret; + } + if ((val & (1 << func->funcNum)) > 0) { + return HDF_SUCCESS; + } + } + + HDF_LOGE("SdioDeviceDefaultEnableFunc: Io not Ready."); + return HDF_ERR_TIMEOUT; +} + +static int32_t SdioDeviceDefaultDisableFunc(struct SdioDevice *dev) +{ + struct SdioFunction *func = dev->curFunction; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultDisableFunc: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + return SdioCccrIoDisable(dev->sd.mmc.cntlr); +} + +static int32_t SdioDeviceDefaultClaimIrq(struct SdioDevice *dev, SdioIrqHandler *irqHandler) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + int32_t ret; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultClaimIrq: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (func->irqHandler != NULL) { + HDF_LOGE("SdioDeviceDefaultClaimIrq: irq has been registered."); + return HDF_ERR_DEVICE_BUSY; + } + if (irqHandler == NULL) { + HDF_LOGE("SdioDeviceDefaultClaimIrq: irqHandler is NULL."); + return HDF_ERR_INVALID_PARAM; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultClaimIrq: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + ret = SdioCccrIntEnable(cntlr); + if (ret != HDF_SUCCESS) { + return ret; + } + + func->irqHandler = irqHandler; + if (cntlr->caps.bits.sdioIrq > 0) { + ret = MmcCntlrCreatSdioIrqThread(cntlr); + } + return ret; +} + +static int32_t SdioDeviceDefaultReleaseIrq(struct SdioDevice *dev) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultReleaseIrq: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultReleaseIrq: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + if (func->irqHandler != NULL) { + func->irqHandler = NULL; + MmcCntlrDestroySdioIrqThread(cntlr); + } + if (cntlr->caps.bits.sdioIrq > 0 && cntlr->ops != NULL && cntlr->ops->setSdioIrq != NULL) { + (void)cntlr->ops->setSdioIrq(cntlr, false); + } + return SdioCccrIntDisable(cntlr); +} + +static int32_t SdioDeviceDefaultFindFunc(struct SdioDevice *dev, struct SdioFunctionConfig *cfg) +{ + uint32_t i; + struct SdioFunction *func = NULL; + + if (dev->functions > SDIO_MAX_FUNCTION_NUMBER) { + HDF_LOGE("SdioDeviceDefaultFindFunc: functions = %d, error!", dev->functions); + return HDF_ERR_INVALID_PARAM; + } + + for (i = 0; i < dev->functions; i++) { + func = dev->sdioFunc[i]; + if (func == NULL) { + continue; + } + if (cfg->deviceId == func->deviceId && + cfg->vendorId == func->vendorId && + cfg->funcNr == func->funcNum) { + dev->curFunction = func; + return HDF_SUCCESS; + } + } + + HDF_LOGE("SdioDeviceDefaultFindFunc: find func fail!"); + return HDF_FAILURE; +} + +static int32_t SdioDeviceDefaultClaimHost(struct SdioDevice *dev) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultClaimHost: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultClaimHost: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + MmcCntlrLock(cntlr); + return HDF_SUCCESS; +} + +static int32_t SdioDeviceDefaultReleaseHost(struct SdioDevice *dev) +{ + struct SdioFunction *func = dev->curFunction; + struct MmcCntlr *cntlr = NULL; + + if (func == NULL) { + HDF_LOGE("SdioDeviceDefaultReleaseHost: func is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + cntlr = dev->sd.mmc.cntlr; + if (cntlr == NULL) { + HDF_LOGE("SdioDeviceDefaultReleaseHost: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + MmcCntlrUnlock(cntlr); + return HDF_SUCCESS; +} + +static struct SdioDeviceOps g_sdioDefaultOps = { + .incrAddrReadBytes = SdioDeviceDefaultIncrAddrReadBytes, + .incrAddrWriteBytes = SdioDeviceDefaultIncrAddrWriteBytes, + .fixedAddrReadBytes = SdioDeviceDefaultFixedAddrReadBytes, + .fixedAddrWriteBytes = SdioDeviceDefaultFixedAddrWriteBytes, + .func0ReadBytes = SdioDeviceDefaultFunc0ReadBytes, + .func0WriteBytes = SdioDeviceDefaultFunc0WriteBytes, + .setBlockSize = SdioDeviceDefaultSetBlockSize, + .getCommonInfo = SdioDeviceDefaultGetCommonInfo, + .setCommonInfo = SdioDeviceDefaultSetCommonInfo, + .flushData = SdioDeviceDefaultFlushData, + .enableFunc = SdioDeviceDefaultEnableFunc, + .disableFunc = SdioDeviceDefaultDisableFunc, + .claimIrq = SdioDeviceDefaultClaimIrq, + .releaseIrq = SdioDeviceDefaultReleaseIrq, + .findFunc = SdioDeviceDefaultFindFunc, + .claimHost = SdioDeviceDefaultClaimHost, + .releaseHost = SdioDeviceDefaultReleaseHost, +}; + +int32_t SdioDeviceFindFunction(struct SdioDevice *sdio, struct SdioFunctionConfig *config) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFindFunction: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->findFunc == NULL) { + HDF_LOGE("SdioDeviceFindFunction: func is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->findFunc(sdio, config); +} + +int32_t SdioDeviceIncrAddrReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceIncrAddrReadBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->incrAddrReadBytes == NULL) { + HDF_LOGE("SdioDeviceIncrAddrReadBytes: incrAddrReadBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->incrAddrReadBytes(sdio, data, addr, size); +} + +int32_t SdioDeviceIncrAddrWriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceIncrAddrWriteBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->incrAddrWriteBytes == NULL) { + HDF_LOGE("SdioDeviceIncrAddrWriteBytes: incrAddrWriteBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->incrAddrWriteBytes(sdio, data, addr, size); +} + +int32_t SdioDeviceFixedAddrReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFixedAddrReadBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->fixedAddrReadBytes == NULL) { + HDF_LOGE("SdioDeviceFixedAddrReadBytes: fixedAddrReadBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->fixedAddrReadBytes(sdio, data, addr, size, scatterLen); +} + +int32_t SdioDeviceFixedAddrWriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFixedAddrWriteBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->fixedAddrWriteBytes == NULL) { + HDF_LOGE("SdioDeviceFixedAddrWriteBytes: fixedAddrWriteBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->fixedAddrWriteBytes(sdio, data, addr, size, scatterLen); +} + +int32_t SdioDeviceFunc0ReadBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFunc0ReadBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->func0ReadBytes == NULL) { + HDF_LOGE("SdioDeviceFunc0ReadBytes: func0ReadBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->func0ReadBytes(sdio, data, addr, size); +} + +int32_t SdioDeviceFunc0WriteBytes(struct SdioDevice *sdio, + uint8_t *data, uint32_t addr, uint32_t size) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFunc0WriteBytes: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->func0WriteBytes == NULL) { + HDF_LOGE("SdioDeviceFunc0WriteBytes: func0WriteBytes is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->func0WriteBytes(sdio, data, addr, size); +} + +int32_t SdioDeviceSetBlockSize(struct SdioDevice *sdio, uint32_t blockSize) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceSetBlockSize: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->setBlockSize == NULL) { + HDF_LOGE("SdioDeviceSetBlockSize: setBlockSize is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->setBlockSize(sdio, blockSize); +} + +int32_t SdioDeviceGetCommonInfo(struct SdioDevice *sdio, + SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceGetCommonInfo: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->getCommonInfo == NULL) { + HDF_LOGE("SdioDeviceGetCommonInfo: getCommonInfo is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->getCommonInfo(sdio, info, infoType); +} + +int32_t SdioDeviceSetCommonInfo(struct SdioDevice *sdio, + SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceSetCommonInfo: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->setCommonInfo == NULL) { + HDF_LOGE("SdioDeviceSetCommonInfo: setCommonInfo is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->setCommonInfo(sdio, info, infoType); +} + +int32_t SdioDeviceFlushData(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceFlushData: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->flushData == NULL) { + HDF_LOGE("SdioDeviceFlushData: flushData is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->flushData(sdio); +} + +int32_t SdioDeviceClaimHost(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceClaimHost: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + if (sdio->sdioOps->claimHost != NULL) { + return sdio->sdioOps->claimHost(sdio); + } + return HDF_SUCCESS; +} + +int32_t SdioDeviceReleaseHost(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceReleaseHost: cntlr is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + + if (sdio->sdioOps->releaseHost != NULL) { + return sdio->sdioOps->releaseHost(sdio); + } + return HDF_SUCCESS; +} + +int32_t SdioDeviceEnableFunc(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceEnableFunc: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->enableFunc == NULL) { + HDF_LOGE("SdioDeviceEnableFunc: enableFunc is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->enableFunc(sdio); +} + +int32_t SdioDeviceDisableFunc(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceDisableFunc: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->disableFunc == NULL) { + HDF_LOGE("SdioDeviceDisableFunc: disableFunc is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->disableFunc(sdio); +} + +int32_t SdioDeviceClaimIrq(struct SdioDevice *sdio, SdioIrqHandler *irqHandler) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceClaimIrq: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->claimIrq == NULL) { + HDF_LOGE("SdioDeviceClaimIrq: claimIrq is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->claimIrq(sdio, irqHandler); +} + +int32_t SdioDeviceReleaseIrq(struct SdioDevice *sdio) +{ + if (sdio->sdioOps == NULL) { + HDF_LOGE("SdioDeviceReleaseIrq: ops is NULL."); + return HDF_ERR_INVALID_OBJECT; + } + if (sdio->sdioOps->releaseIrq == NULL) { + HDF_LOGE("SdioDeviceReleaseIrq: releaseIrq is NULL."); + return HDF_FAILURE; + } + return sdio->sdioOps->releaseIrq(sdio); +} + +void SdioDeviceAddOps(struct SdioDevice *sdio, void *ops) +{ + if (sdio == NULL) { + HDF_LOGE("SdioDeviceAddOps: sdio is NULL."); + return; + } + if (ops == NULL) { + sdio->sdioOps = &g_sdioDefaultOps; + HDF_LOGD("SdioDeviceAddOps: use default ops."); + } else { + sdio->sdioOps = (struct SdioDeviceOps *)ops; + } +} diff --git a/support/platform/src/mmc/sdio_if.c b/support/platform/src/mmc/sdio_if.c new file mode 100644 index 00000000..cd05ef45 --- /dev/null +++ b/support/platform/src/mmc/sdio_if.c @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "sdio_if.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "mmc_sdio.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_LOG_TAG sdio_if_c + +static int32_t SdioDeviceGetFromHandle(DevHandle handle, struct SdioDevice **sdio) +{ + struct MmcDevice *mmc = NULL; + + if (handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (sdio == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + mmc = MmcCntlrGetDevice((struct MmcCntlr *)handle); + if (mmc == NULL) { + return HDF_PLT_ERR_NO_DEV; + } + if (mmc->type != MMC_DEV_SDIO && mmc->type != MMC_DEV_COMBO) { + MmcDevicePut(mmc); + return HDF_PLT_ERR_DEV_TYPE; + } + + *sdio = (struct SdioDevice *)mmc; + return HDF_SUCCESS; +} + +DevHandle SdioOpen(int16_t mmcBusNum, struct SdioFunctionConfig *config) +{ + int32_t ret; + struct MmcCntlr *cntlr = NULL; + struct SdioDevice *sdio = NULL; + DevHandle handle = NULL; + + if (config == NULL) { + HDF_LOGE("SdioOpen: config can't be null!"); + return NULL; + } + + handle = MmcOpen(mmcBusNum); + if (handle == NULL) { + HDF_LOGE("SdioOpen: SdioGetCntlrByBusNum fail!"); + return NULL; + } + cntlr = (struct MmcCntlr *)handle; + if (cntlr != NULL && cntlr->ops != NULL && cntlr->ops->rescanSdioDev != NULL) { + ret = cntlr->ops->rescanSdioDev(cntlr); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioOpen: sdio rescan fail!"); + MmcClose(handle); + return NULL; + } + } + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioOpen: get sdio dev fail!"); + MmcClose(handle); + return NULL; + } + ret = SdioDeviceFindFunction(sdio, config); + MmcDevicePut((struct MmcDevice *)sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioOpen: set function fail!"); + MmcClose(handle); + return NULL; + } + + return (DevHandle)cntlr; +} + +void SdioClose(DevHandle handle) +{ + (void)handle; +} + +int32_t SdioReadBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReadBytes: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceIncrAddrReadBytes(sdio, data, addr, size); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioWriteBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioWriteBytes: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceIncrAddrWriteBytes(sdio, data, addr, size); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioReadBytesFromFixedAddr(DevHandle handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReadBytesFromFixedAddr: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceFixedAddrReadBytes(sdio, data, addr, size, scatterLen); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioWriteBytesToFixedAddr(DevHandle handle, uint8_t *data, + uint32_t addr, uint32_t size, uint32_t scatterLen) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioWriteBytesToFixedAddr: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceFixedAddrWriteBytes(sdio, data, addr, size, scatterLen); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioReadBytesFromFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReadBytesFromFunc0: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceFunc0ReadBytes(sdio, data, addr, size); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioWriteBytesToFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioWriteBytesToFunc0: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceFunc0WriteBytes(sdio, data, addr, size); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioSetBlockSize(DevHandle handle, uint32_t blockSize) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioSetBlockSize: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceSetBlockSize(sdio, blockSize); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioGetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioGetCommonInfo: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceGetCommonInfo(sdio, info, infoType); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioSetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioSetCommonInfo: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceSetCommonInfo(sdio, info, infoType); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioFlushData(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioFlushData: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceFlushData(sdio); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +void SdioClaimHost(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioClaimHost: get sdio dev fail!"); + return; + } + ret = SdioDeviceClaimHost(sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioClaimHost: claim host fail!"); + } + MmcDevicePut((struct MmcDevice *)sdio); +} + +void SdioReleaseHost(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReleaseHost: get sdio dev fail!"); + return; + } + ret = SdioDeviceReleaseHost(sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReleaseHost: claim host fail!"); + } + MmcDevicePut((struct MmcDevice *)sdio); +} + +int32_t SdioEnableFunc(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioEnableFunc: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceEnableFunc(sdio); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioDisableFunc(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioDisableFunc: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceDisableFunc(sdio); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler *irqHandler) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioClaimIrq: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceClaimIrq(sdio, irqHandler); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} + +int32_t SdioReleaseIrq(DevHandle handle) +{ + int32_t ret; + struct SdioDevice *sdio = NULL; + + ret = SdioDeviceGetFromHandle(handle, &sdio); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SdioReleaseIrq: get sdio dev fail!"); + return ret; + } + ret = SdioDeviceReleaseIrq(sdio); + MmcDevicePut((struct MmcDevice *)sdio); + return ret; +} diff --git a/support/platform/src/rtc_base.c b/support/platform/src/rtc_base.c index 9b63c970..5e671ac0 100644 --- a/support/platform/src/rtc_base.c +++ b/support/platform/src/rtc_base.c @@ -6,9 +6,9 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "rtc_base.h" #include "hdf_log.h" #include "plat_log.h" -#include "rtc_base.h" #define HDF_LOG_TAG rtc_base @@ -21,7 +21,7 @@ uint8_t RtcGetMonthDays(const uint8_t isLeapYear, const uint8_t month) return 0; } - if (RTC_FEBRUARY == month) { + if (month == RTC_FEBRUARY) { days = RTC_TWO_MONTH_DAY + isLeapYear; } else { oddMonth = (month >= RTC_AUGUST) ? (month - RTC_UNIT_DIFF) : month; diff --git a/support/platform/src/rtc_core.c b/support/platform/src/rtc_core.c index 3df837d3..93ae2173 100644 --- a/support/platform/src/rtc_core.c +++ b/support/platform/src/rtc_core.c @@ -6,9 +6,9 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "rtc_core.h" #include "hdf_log.h" #include "osal_mem.h" -#include "rtc_core.h" #define HDF_LOG_TAG rtc_core diff --git a/support/platform/src/rtc_if.c b/support/platform/src/rtc_if.c index 232126ca..140f3c3f 100644 --- a/support/platform/src/rtc_if.c +++ b/support/platform/src/rtc_if.c @@ -6,13 +6,13 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "rtc_if.h" +#include "devsvc_manager_clnt.h" #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 diff --git a/support/platform/src/sdio_core.c b/support/platform/src/sdio_core.c index 990c460d..737480a9 100644 --- a/support/platform/src/sdio_core.c +++ b/support/platform/src/sdio_core.c @@ -6,10 +6,10 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "sdio_core.h" #include "device_resource_if.h" #include "osal_mem.h" #include "plat_log.h" -#include "sdio_core.h" #define HDF_LOG_TAG sdio_core diff --git a/support/platform/src/spi_if.c b/support/platform/src/spi_if.c index 45eb03af..4fb01a58 100644 --- a/support/platform/src/spi_if.c +++ b/support/platform/src/spi_if.c @@ -6,12 +6,12 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include "securec.h" +#include "spi_if.h" #include "devsvc_manager_clnt.h" #include "hdf_log.h" #include "osal_mem.h" +#include "securec.h" #include "spi_core.h" -#include "spi_if.h" #define HDF_LOG_TAG spi_if #define HOST_NAME_LEN 32 @@ -128,17 +128,19 @@ DevHandle SpiOpen(const struct SpiDevInfo *info) return NULL; } - ret = SpiCntlrOpen(cntlr, info->csNum); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: SpiCntlrOpen error, ret is %d", __func__, ret); - return NULL; - } - object = (struct SpiObject *)OsalMemCalloc(sizeof(*object)); if (object == NULL) { HDF_LOGE("%s: object malloc error", __func__); return NULL; } + + ret = SpiCntlrOpen(cntlr, info->csNum); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SpiCntlrOpen error, ret is %d", __func__, ret); + OsalMemFree(object); + return NULL; + } + object->cntlr = cntlr; object->csNum = info->csNum; return (DevHandle)object; diff --git a/support/platform/src/uart_core.c b/support/platform/src/uart_core.c index 524ad61f..71cfcb05 100644 --- a/support/platform/src/uart_core.c +++ b/support/platform/src/uart_core.c @@ -154,7 +154,7 @@ static int32_t UartUserSetTransMode(struct UartHost *host, struct HdfSBuf *data) size_t size; enum UartTransMode *mode = NULL; - if (!HdfSbufReadBuffer(data, (const void **)&mode, &size)) { + if (!HdfSbufReadBuffer(data, (const void **)&mode, &size) || mode == NULL) { HDF_LOGE("%s: sbuf read buffer failed", __func__); return HDF_ERR_IO; } diff --git a/support/platform/src/uart_if.c b/support/platform/src/uart_if.c index 94eae00e..8ed38d0f 100644 --- a/support/platform/src/uart_if.c +++ b/support/platform/src/uart_if.c @@ -6,6 +6,7 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "uart_if.h" #include "securec.h" #ifndef __USER__ #include "devsvc_manager_clnt.h" @@ -17,7 +18,6 @@ #ifndef __USER__ #include "uart_core.h" #endif -#include "uart_if.h" #define HDF_LOG_TAG uart_if_c #define UART_HOST_NAME_LEN 32 @@ -128,7 +128,7 @@ static int32_t UartUserReceive(DevHandle handle, void *data, uint32_t size, enum HDF_LOGE("%s: service is invalid", __func__); return HDF_ERR_INVALID_PARAM; } - /* Four bits are used to store the buffer length, and four bits are used to align the memory. */ + /* Four bytes are used to store the buffer length, and four bytes are used to align the memory. */ reply = HdfSBufObtain(size + sizeof(uint64_t)); if (reply == NULL) { HDF_LOGE("%s: failed to obtain reply", __func__); diff --git a/support/platform/src/watchdog_if.c b/support/platform/src/watchdog_if.c index cf317f5f..b67506ee 100644 --- a/support/platform/src/watchdog_if.c +++ b/support/platform/src/watchdog_if.c @@ -46,7 +46,6 @@ static struct Watchdog *WatchdogGetById(int16_t wdtId) return service; } - DevHandle WatchdogOpen(int16_t wdtId) { struct Watchdog *service = NULL; diff --git a/support/platform/test/unittest/common/hdf_emmc_test.cpp b/support/platform/test/unittest/common/hdf_emmc_test.cpp index 9e1b51dd..ab10b066 100644 --- a/support/platform/test/unittest/common/hdf_emmc_test.cpp +++ b/support/platform/test/unittest/common/hdf_emmc_test.cpp @@ -56,7 +56,7 @@ static void TestUserEmmcGetCid(void) EmmcGetHuid(cid, EMMC_CID_LEN); for (i = 0; i < EMMC_CID_LEN; i++) { - printf("user interface get cid[%d] = 0x%x\n", i, cid[i]); + printf("user interface get cid[%u] = 0x%x\n", i, cid[i]); } } diff --git a/support/posix/src/osal_mutex.c b/support/posix/src/osal_mutex.c index 8ca66662..6769c921 100644 --- a/support/posix/src/osal_mutex.c +++ b/support/posix/src/osal_mutex.c @@ -106,7 +106,7 @@ int32_t OsalMutexTimedLock(struct OsalMutex *mutex, uint32_t ms) if (ret == ETIMEDOUT) { return HDF_ERR_TIMEOUT; } else { - HDF_LOGE("%s time_out time:%d ret:%d", __func__, ms, ret); + HDF_LOGE("%s time_out time:%u ret:%d", __func__, ms, ret); return HDF_FAILURE; } } diff --git a/support/posix/src/osal_spinlock.c b/support/posix/src/osal_spinlock.c new file mode 100644 index 00000000..e51b7ff9 --- /dev/null +++ b/support/posix/src/osal_spinlock.c @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "osal_spinlock.h" +#include +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG osal_spinlock + +int32_t OsalSpinInit(OsalSpinlock *spinlock) +{ + pthread_spinlock_t *spinTmp = NULL; + int ret; + + if (spinlock == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + spinlock->realSpinlock = NULL; + + spinTmp = (pthread_spinlock_t *)OsalMemCalloc(sizeof(pthread_spinlock_t)); + if (spinTmp == NULL) { + HDF_LOGE("malloc fail"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = pthread_spin_init(spinTmp, PTHREAD_PROCESS_PRIVATE); + if (ret != 0) { + HDF_LOGE("pthread_spin_init fail %d %d", ret, __LINE__); + OsalMemFree(spinTmp); + return HDF_FAILURE; + } + spinlock->realSpinlock = (void *)spinTmp; + + return HDF_SUCCESS; +} + +int32_t OsalSpinDestroy(OsalSpinlock *spinlock) +{ + int ret; + + if (spinlock == NULL || spinlock->realSpinlock == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = pthread_spin_destroy((pthread_spinlock_t *)spinlock->realSpinlock); + if (ret != 0) { + HDF_LOGE("pthread_spin_destroy fail %d %d", ret, __LINE__); + return HDF_FAILURE; + } + + OsalMemFree(spinlock->realSpinlock); + spinlock->realSpinlock = NULL; + + return HDF_SUCCESS; +} + +int32_t OsalSpinLock(OsalSpinlock *spinlock) +{ + int ret; + + if (spinlock == NULL || spinlock->realSpinlock == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = pthread_spin_lock((pthread_spinlock_t *)spinlock->realSpinlock); + if (ret != 0) { + HDF_LOGE("pthread_spin_lock fail %d %d", ret, __LINE__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +int32_t OsalSpinUnlock(OsalSpinlock *spinlock) +{ + int ret; + + if (spinlock == NULL || spinlock->realSpinlock == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = pthread_spin_unlock((pthread_spinlock_t *)spinlock->realSpinlock); + if (ret != 0) { + HDF_LOGE("pthread_spin_unlock fail %d %d", ret, __LINE__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + diff --git a/support/posix/src/osal_thread.c b/support/posix/src/osal_thread.c index fc621b42..12c162ff 100644 --- a/support/posix/src/osal_thread.c +++ b/support/posix/src/osal_thread.c @@ -11,8 +11,11 @@ #include "hdf_base.h" #include "hdf_log.h" #include "osal_mem.h" - +#ifndef PTHREAD_STACK_MIN #define OSAL_PTHREAD_STACK_MIN 4096 +#else +#define OSAL_PTHREAD_STACK_MIN PTHREAD_STACK_MIN +#endif #define HDF_LOG_TAG osal_thread @@ -75,7 +78,7 @@ int32_t OsalThreadCreate(struct OsalThread *thread, OsalThreadEntry threadEntry, int32_t OsalThreadDestroy(struct OsalThread *thread) { - if (thread->realThread != NULL) { + if (thread != NULL && thread->realThread != NULL) { OsalMemFree(thread->realThread); thread->realThread = NULL; } diff --git a/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.c b/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.c index 654698f2..b5757268 100644 --- a/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.c +++ b/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.c @@ -258,7 +258,7 @@ int HcsTestGetUint8ArrayElemSuccess(void) { uint8_t data[DATA_TEST_ARRAY_LENGTH] = { 0 }; // the test data is 0, 1, 2, 3, 4, 5, 6, 7. - uint8_t testData[DATA_TEST_ARRAY_LENGTH] = {0, 1, 2, 3, 4, 5, 6, 7}; + uint8_t testData[DATA_TEST_ARRAY_LENGTH] = { 0, 1, 2, 3, 4, 5, 6, 7 }; uint32_t i; if (!TestGetRootNode()) { return HDF_FAILURE; @@ -272,7 +272,7 @@ int HcsTestGetUint8ArrayElemSuccess(void) int32_t ret = g_devResInstance->GetUint8ArrayElem(dataType, TEST_U8_ELEM_DATA, i, &data[i], DEFAULT_UINT8_MAX); if ((ret != HDF_SUCCESS) || (data[i] != testData[i])) { - HDF_LOGE("%s failed, line: %d, ret = %d, i = %d, data = %u", __FUNCTION__, __LINE__, ret, i, data[i]); + HDF_LOGE("%s failed, line: %d, ret = %d, i = %u, data = %u", __FUNCTION__, __LINE__, ret, i, data[i]); return HDF_FAILURE; } } @@ -303,7 +303,7 @@ int HcsTestGetUint8ArrayElemFail(void) for (i = 0; i < count; i++) { ret = g_devResInstance->GetUint8ArrayElem(dataType, READ_FOUR_DATA_TYPE, i, &data1[i], DEFAULT_UINT8_MAX); } - // the 0~3 represents the loction in array. + // the 0~3 represents the location in array. if ((ret == HDF_SUCCESS) || (data1[0] != U8_DATA) || (data1[1] != DEFAULT_UINT8_MAX) || (data1[2] != DEFAULT_UINT8_MAX) || (data1[3] != DEFAULT_UINT8_MAX)) { HDF_LOGE("%s failed, line: %d, ret = %d, data = %x", __FUNCTION__, __LINE__, ret, data); @@ -321,7 +321,7 @@ int HcsTestGetUint8ArraySuccess(void) const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint8Array(dataType, TEST_U8_ELEM_DATA, data, DATA_TEST_ARRAY_LENGTH, DEFAULT_UINT8_MAX); - // the 0~7 represents the loction in array or the value in hcs file. + // the 0~7 represents the location in array or the value in hcs file. if ((ret != HDF_SUCCESS) || (data[0] != 0) || (data[1] != 1) || (data[2] != 2) || (data[3] != 3) || (data[4] != 4) || (data[5] != 5) || (data[6] != 6) || (data[7] != 7)) { return HDF_FAILURE; @@ -337,13 +337,13 @@ int HcsTestGetUint8ArrayFail(void) } const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint8Array(dataType, READ_FOUR_DATA_TYPE, data, 0, DEFAULT_UINT8_MAX); - // the 0, 1, 2 represents the loction in array, the 0 of second param is defalut value. + // the 0, 1, 2 represents the location in array, the 0 of second param is default value. if ((ret == HDF_SUCCESS) || (data[0] != 0) || (data[1] != 0) || (data[2] != 0)) { return HDF_FAILURE; } ret = g_devResInstance->GetUint8Array(dataType, READ_FOUR_DATA_TYPE, data, DATA_TYPE_NUM_U64 + 1, DEFAULT_UINT8_MAX); - // the 0, 1, 2, 3, 4 represents the loction in array + // the 0, 1, 2, 3, 4 represents the location in array if ((ret == HDF_SUCCESS) || (data[0] != U8_DATA) || (data[1] != DEFAULT_UINT8_MAX) || (data[2] != DEFAULT_UINT8_MAX) || (data[3] != DEFAULT_UINT8_MAX) || (data[4] != DEFAULT_UINT8_MAX)) { return HDF_FAILURE; @@ -402,7 +402,7 @@ int HcsTestGetUint16ArrayElemSuccess(void) // the length of data is 8. uint16_t data[DATA_TEST_ARRAY_LENGTH] = { 0 }; // the test data is 0, 1, 2, 3, 4, 5, 256, 257. - uint16_t testData[DATA_TEST_ARRAY_LENGTH] = {0, 1, 2, 3, 4, 5, 256, 257}; + uint16_t testData[DATA_TEST_ARRAY_LENGTH] = { 0, 1, 2, 3, 4, 5, 256, 257 }; uint32_t i; if (!TestGetRootNode()) { return HDF_FAILURE; @@ -444,7 +444,7 @@ int HcsTestGetUint16ArrayElemFail(void) for (i = 0; i < count; i++) { ret = g_devResInstance->GetUint16ArrayElem(dataType, READ_FOUR_DATA_TYPE, i, &data1[i], DEFAULT_UINT16_MAX); } - // the 0~3 represents the loction in array. + // the 0~3 represents the location in array. if ((ret == HDF_SUCCESS) || (data1[0] != U8_DATA) || (data1[1] != U16_DATA) || (data1[2] != DEFAULT_UINT16_MAX) || (data1[3] != DEFAULT_UINT16_MAX)) { return HDF_FAILURE; @@ -461,7 +461,7 @@ int HcsTestGetUint16ArraySuccess(void) const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint16Array(dataType, TEST_U16_ELEM_DATA, data, DATA_TEST_ARRAY_LENGTH, DEFAULT_UINT16_MAX); - // the data[0~7] represents the loction in array, the test data is 0, 1, 2, 3, 4, 5, 256, 257. + // the data[0~7] represents the location in array, the test data is 0, 1, 2, 3, 4, 5, 256, 257. if ((ret != HDF_SUCCESS) || (data[0] != 0) || (data[1] != 1) || (data[2] != 2) || (data[3] != 3) || (data[4] != 4) || (data[5] != 5) || (data[6] != 256) || (data[7] != 257)) { return HDF_FAILURE; @@ -477,13 +477,13 @@ int HcsTestGetUint16ArrayFail(void) } const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint16Array(dataType, READ_FOUR_DATA_TYPE, data, 0, DEFAULT_UINT16_MAX); - // the 0, 1, 2 represents the loction in array, the 0 of second param is defalut value. + // the 0, 1, 2 represents the location in array, the 0 of second param is default value. if ((ret == HDF_SUCCESS) || (data[0] != 0) || (data[1] != 0) || (data[2] != 0)) { return HDF_FAILURE; } ret = g_devResInstance->GetUint16Array(dataType, READ_FOUR_DATA_TYPE, data, DATA_TYPE_NUM_U64 + 1, DEFAULT_UINT16_MAX); - // the 0, 1, 2, 3, 4 represents the loction in array + // the 0, 1, 2, 3, 4 represents the location in array if ((ret == HDF_SUCCESS) || (data[0] != U8_DATA) || (data[1] != U16_DATA) || (data[2] != DEFAULT_UINT16_MAX) || (data[3] != DEFAULT_UINT16_MAX) || (data[4] != DEFAULT_UINT16_MAX)) { return HDF_FAILURE; @@ -537,7 +537,7 @@ int HcsTestGetUint32AttrValueFail(void) int HcsTestGetUint32ArrayElemSuccess(void) { uint32_t data[DATA_TYPE_NUM_U32] = { 0 }; - uint32_t testData[DATA_TYPE_NUM_U32] = {U8_DATA, U16_DATA, U32_DATA}; + uint32_t testData[DATA_TYPE_NUM_U32] = { U8_DATA, U16_DATA, U32_DATA }; int32_t i; if (!TestGetRootNode()) { return HDF_FAILURE; @@ -578,7 +578,7 @@ int HcsTestGetUint32ArraySuccess(void) return HDF_FAILURE; } int32_t ret = g_devResInstance->GetUint32Array(g_testRoot, BOARD_ID, data, BOARDID_LENGTH, DEFAULT_UINT32_MAX); - // the 0, 1 represents the loction in array. + // the 0, 1 represents the location in array. if ((ret != HDF_SUCCESS) || (data[0] != U32_DATA) || (data[1] != U16_DATA)) { return HDF_FAILURE; } @@ -592,12 +592,12 @@ int HcsTestGetUint32ArrayFail(void) return HDF_FAILURE; } int32_t ret = g_devResInstance->GetUint32Array(g_testRoot, BOARD_ID, data, 0, DEFAULT_UINT32_MAX); - // the 0, 1, 2 represents the loction in array, the 0 of second param is defalut value. + // the 0, 1, 2 represents the location in array, the 0 of second param is default value. if ((ret == HDF_SUCCESS) || (data[0] != 0) || (data[1] != 0) || (data[2] != 0)) { return HDF_FAILURE; } ret = g_devResInstance->GetUint32Array(g_testRoot, BOARD_ID, data, DATA_TYPE_NUM_U32, DEFAULT_UINT32_MAX); - // the 0, 1, 2 represents the loction in array + // the 0, 1, 2 represents the location in array if ((ret == HDF_SUCCESS) || (data[0] != U32_DATA) || (data[1] != U16_DATA) || (data[2] != DEFAULT_UINT32_MAX)) { return HDF_FAILURE; } @@ -655,7 +655,7 @@ int HcsTestGetUint64AttrValueFail(void) int HcsTestGetUint64ArrayElemSuccess(void) { uint64_t data[DATA_TYPE_NUM_U64] = { 0 }; - uint64_t testData[DATA_TYPE_NUM_U64] = {U8_DATA, U16_DATA, U32_DATA, U64_DATA}; + uint64_t testData[DATA_TYPE_NUM_U64] = { U8_DATA, U16_DATA, U32_DATA, U64_DATA }; uint32_t i; if (!TestGetRootNode()) { return HDF_FAILURE; @@ -699,7 +699,7 @@ int HcsTestGetUint64ArraySuccess(void) const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint64Array(dataType, READ_FOUR_DATA_TYPE, data, DATA_TYPE_NUM_U64, DEFAULT_UINT64_MAX); - // the 0, 1, 2 represents the loction in array. + // the 0, 1, 2 represents the location in array. if ((ret != HDF_SUCCESS) || (data[0] != U8_DATA) || (data[1] != U16_DATA) || (data[2] != U32_DATA) || (data[3] != U64_DATA)) { return HDF_FAILURE; @@ -715,13 +715,13 @@ int HcsTestGetUint64ArrayFail(void) } const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); int32_t ret = g_devResInstance->GetUint64Array(dataType, READ_FOUR_DATA_TYPE, data, 0, DEFAULT_UINT64_MAX); - // the 0, 1, 2 represents the loction in array, the 0 of second param is defalut value. + // the 0, 1, 2 represents the location in array, the 0 of second param is default value. if ((ret == HDF_SUCCESS) || (data[0] != 0) || (data[1] != 0) || (data[2] != 0)) { return HDF_FAILURE; } ret = g_devResInstance->GetUint64Array(dataType, READ_FOUR_DATA_TYPE, data, DATA_TYPE_NUM_U64 + 1, DEFAULT_UINT64_MAX); - // the 0, 1, 2, 3, 4 represents the loction in array + // the 0, 1, 2, 3, 4 represents the location in array if ((ret == HDF_SUCCESS) || (data[0] != U8_DATA) || (data[1] != U16_DATA) || (data[2] != U32_DATA) || (data[3] != U64_DATA) || (data[4] != DEFAULT_UINT64_MAX)) { return HDF_FAILURE; @@ -865,7 +865,7 @@ int HcsTestTraverseAttrInNodeFail(void) const struct DeviceResourceNode *childNode = NULL; DEV_RES_NODE_FOR_EACH_CHILD_NODE(fingerprintNode, childNode) { - if (childNode == NULL) { + if ((childNode == NULL) || (childNode->name == NULL)) { break; } if ((strcmp(childNode->name, "fingerprint_one") == 0) || (strcmp(childNode->name, "fingerprint_two") == 0)) { @@ -886,9 +886,9 @@ int HcsTestGetStringSuccess(void) return HDF_FAILURE; } const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); - const char *ptype = NULL; - int32_t readString = g_devResInstance->GetString(audioNode, "cust_name", &ptype, NULL); - if ((readString != HDF_SUCCESS) || (ptype == NULL) || (strcmp(ptype, "audio_custom_v2") != HDF_SUCCESS)) { + const char *type = NULL; + int32_t readString = g_devResInstance->GetString(audioNode, "cust_name", &type, NULL); + if ((readString != HDF_SUCCESS) || (type == NULL) || (strcmp(type, "audio_custom_v2") != HDF_SUCCESS)) { return HDF_FAILURE; } return HDF_SUCCESS; @@ -900,17 +900,17 @@ int HcsTestGetStringFail(void) return HDF_FAILURE; } const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); - const char *ptype = NULL; - int32_t testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, &ptype, STRING_ATTR_VALUE); - if ((testReadString == HDF_SUCCESS) || (ptype == NULL) || (strcmp(ptype, STRING_ATTR_VALUE) != HDF_SUCCESS)) { + const char *type = NULL; + int32_t testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, &type, STRING_ATTR_VALUE); + if ((testReadString == HDF_SUCCESS) || (type == NULL) || (strcmp(type, STRING_ATTR_VALUE) != HDF_SUCCESS)) { return HDF_FAILURE; } testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, NULL, STRING_ATTR_VALUE); - if ((testReadString == HDF_SUCCESS) || (ptype == NULL) || (strcmp(ptype, STRING_ATTR_VALUE) != HDF_SUCCESS)) { + if ((testReadString == HDF_SUCCESS) || (type == NULL) || (strcmp(type, STRING_ATTR_VALUE) != HDF_SUCCESS)) { return HDF_FAILURE; } - testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, &ptype, NULL); - if (testReadString == HDF_SUCCESS || ptype != NULL) { + testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, &type, NULL); + if ((testReadString == HDF_SUCCESS) || (type != NULL)) { return HDF_FAILURE; } return HDF_SUCCESS; @@ -923,17 +923,17 @@ int HcsTestGetStringArrayElemSuccess(void) } const char *rawDataDts = NULL; const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); - // the third param is the loction in string_list_names array. + // the third param(0) is the location in string_list_names array. int32_t ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 0, &rawDataDts, NULL); if ((ret != HDF_SUCCESS) || (strcmp(rawDataDts, "first") != HDF_SUCCESS)) { return HDF_FAILURE; } - // the third param is the loction in string_list_names array. + // the third param(1) is the location in string_list_names array. ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 1, &rawDataDts, NULL); if ((ret != HDF_SUCCESS) || (strcmp(rawDataDts, "second") != HDF_SUCCESS)) { return HDF_FAILURE; } - // the second param is 2, indicates the index, the third param is the loction in string_list_names array. + // the third param(2) is the location in string_list_names array. ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 2, &rawDataDts, NULL); if ((ret != HDF_SUCCESS) || (strcmp(rawDataDts, "third") != HDF_SUCCESS)) { return HDF_FAILURE; @@ -948,14 +948,14 @@ int HcsTestGetStringArrayElemFail(void) } const char *rawDataDts = NULL; const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); - // the third param(3) is the loction in string_list_names array. + // the third param(3) is the location in string_list_names array. int32_t ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 3, &rawDataDts, STRING_ATTR_VALUE); if ((ret == HDF_SUCCESS) || (strcmp(rawDataDts, STRING_ATTR_VALUE) != HDF_SUCCESS)) { return HDF_FAILURE; } - // the third param(1) is the loction in string_list_names array. + // the third param(1) is the location in string_list_names array. ret = g_devResInstance->GetStringArrayElem(fingerprintNode, READ_U32_INDEX, 1, &rawDataDts, STRING_ATTR_VALUE); if ((ret == HDF_SUCCESS) || (strcmp(rawDataDts, STRING_ATTR_VALUE) != HDF_SUCCESS)) { return HDF_FAILURE; @@ -1019,4 +1019,4 @@ int HcsTestGetNodeAttrRefFail(void) return HDF_FAILURE; } return HDF_SUCCESS; -} +} \ No newline at end of file diff --git a/test/unittest/common/hdf_common_test.c b/test/unittest/common/hdf_common_test.c index d3c9cf8b..075d51a3 100644 --- a/test/unittest/common/hdf_common_test.c +++ b/test/unittest/common/hdf_common_test.c @@ -69,7 +69,7 @@ int HdfTestSendMsgToService(struct HdfTestMsg *msg) } if (!HdfSbufReadBuffer(g_reply, (const void **)&testReply, &len)) { - printf("HdfTestSendMsgToService g_reply read failed\n\r"); + printf("HdfTestSendMsgToService g_reply read failed\n\r"); } if (testReply == NULL) { diff --git a/test/unittest/common/hdf_main_test.c b/test/unittest/common/hdf_main_test.c index 039fe902..ee5e4008 100644 --- a/test/unittest/common/hdf_main_test.c +++ b/test/unittest/common/hdf_main_test.c @@ -127,7 +127,7 @@ static int32_t HdfTestCaseProcess(struct HdfDeviceIoClient *client, replyMsg.cmd = msg->cmd; replyMsg.subCmd = msg->subCmd; - HDF_LOGE("%s::Hdf test receive cmd: command[%d], subCommand[%d]", __func__, msg->cmd, msg->subCmd); + HDF_LOGE("%s::Hdf test receive cmd: command[%u], subCommand[%u]", __func__, msg->cmd, msg->subCmd); replyMsg.result = HDF_FAILURE; for (i = 0; i < sizeof(g_hdfTestFuncList) / sizeof(g_hdfTestFuncList[0]); ++i) { diff --git a/test/unittest/manager/sample_driver_test.c b/test/unittest/manager/sample_driver_test.c index eac190dc..bf69825f 100644 --- a/test/unittest/manager/sample_driver_test.c +++ b/test/unittest/manager/sample_driver_test.c @@ -12,12 +12,10 @@ #define HDF_LOG_TAG sample_driver_test -#define SAMPLE_WRITE_READ 123 #ifndef INT32_MAX #define INT32_MAX 0x7fffffff #endif - void HdfSampleDriverRelease(struct HdfDeviceObject *deviceObject) { (void)deviceObject; diff --git a/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.c b/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.c index 76c57ff6..e82ab80d 100644 --- a/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.c +++ b/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.c @@ -860,7 +860,7 @@ pTestCaseFunc g_hdfNetBufQueueTestCaseLists[] = { HdfNetBufQueueTest009, }; -// HDFNetBuf test canse Entry +// HDFNetBuf test case Entry int32_t HdfNetBufTest(void) { int32_t ret, i; @@ -879,7 +879,7 @@ int32_t HdfNetBufTest(void) return HDF_SUCCESS; } -// HdfNetBufQueue test canse Entry +// HdfNetBufQueue test case Entry int32_t HdfNetBufQueueTest(void) { int32_t ret, i; diff --git a/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.c b/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.c index d44f0036..5d47a211 100644 --- a/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.c +++ b/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.c @@ -21,7 +21,10 @@ static bool WiFiNetDeviceTestEnv(void) { if (g_netDevice == NULL) { char devName[IFNAMSIZ] = {0}; - strncpy_s(devName, IFNAMSIZ, "wlan_test_0", strlen("wlan_test_0") + 1); + if (strncpy_s(devName, IFNAMSIZ, "wlan_test_0", strlen("wlan_test_0") + 1) != EOK) { + HDF_LOGE("%s: strcpy_s fail", __func__); + return false; + } g_netDevice = NetDeviceInit(devName, strlen(devName), LITE_OS); if (g_netDevice == NULL) { HDF_LOGE("%s fail ", __func__); @@ -117,6 +120,7 @@ int32_t WiFiNetDviceTestSetAddr(void) int32_t WiFiNetDviceTestRx(void) { NetBuf *buff = NULL; + int count = sizeof(g_filterData); buff = NetBufAlloc(count); if (buff == NULL) { diff --git a/test/unittest/model/network/wifi/unittest/qos/flow_control_test.c b/test/unittest/model/network/wifi/unittest/qos/flow_control_test.c index 1a4a0ba2..3b880ebf 100644 --- a/test/unittest/model/network/wifi/unittest/qos/flow_control_test.c +++ b/test/unittest/model/network/wifi/unittest/qos/flow_control_test.c @@ -154,7 +154,7 @@ int32_t WiFiFlowControlTestSendData(void) return HDF_FAILURE; } if (g_flowControlInstance->interface == NULL) { - HDF_LOGE("%s interface =null!", __func__); + HDF_LOGE("%s interface = null!", __func__); return HDF_FAILURE; } id = g_flowControlInstance->interface->getQueueIdByEtherBuff(buff); diff --git a/test/unittest/osal/osal_all_test.c b/test/unittest/osal/osal_all_test.c index 1efe4a73..2fa37275 100644 --- a/test/unittest/osal/osal_all_test.c +++ b/test/unittest/osal/osal_all_test.c @@ -158,7 +158,7 @@ int ThreadTest2(void *arg) OsalGetTime(&hdfTs2); OsalDiffTime(&hdfTs1, &hdfTs2, &hdfTsDiff); if (cnt % HDF_THREAD_TEST_MUX_CNT == 0) { - HDF_LOGE("%s %ds %dus", __func__, + HDF_LOGE("%s %us %uus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); } if (g_testEndFlag) { @@ -345,7 +345,7 @@ static void OsaFWTest(int flag) (void)memset_s(&fw, sizeof(fw), 0, sizeof(fw)); ret = OsalRequestFirmware(&fw, name, NULL); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_REQUEST); - HDF_LOGE("%s %d", name, fw.fwSize); + HDF_LOGE("%s %u", name, fw.fwSize); (void)memset_s(&block, sizeof(block), 0, sizeof(block)); ret = OsalReadFirmware(&fw, &block); @@ -355,10 +355,10 @@ static void OsaFWTest(int flag) #if defined(__LITEOS__) ret = OsalSeekFirmware(&fw, HDF_FILE_SEEK_TEST); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_SEEK); - HDF_LOGE("%s %d %d", name, block.dataSize, block.curOffset); + HDF_LOGE("%s %u %d", name, block.dataSize, block.curOffset); ret = OsalReadFirmware(&fw, &block); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_READ); - HDF_LOGE("%s %d %d", name, block.dataSize, block.curOffset); + HDF_LOGE("%s %u %d", name, block.dataSize, block.curOffset); fwBuf += HDF_FILE_SEEK_TEST; UT_TEST_CHECK_RET(memcmp(block.data, fwBuf, block.dataSize) != 0, OSAL_FW_DATA_CHECK); #endif @@ -367,8 +367,6 @@ static void OsaFWTest(int flag) ret = OsalReadFirmware(&fw, &block); UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_FW_READ_AFTER_RELEASE); HDF_LOGE("[OSAL_UT_TEST]%s end", __func__); - - return; } #define THREAD_TEST_TIMER_RUN 20 @@ -542,8 +540,6 @@ void OsaThreadTest1(void) UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); ret = OsalThreadStart(&thread, &threadCfg); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); - - return; } void OsaThreadTest(void) @@ -601,27 +597,27 @@ static void OsaTimeTest(void) ret = OsalGetTime(&hdfTs2); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIME_GETTIME); ret = OsalDiffTime(&hdfTs, &hdfTs2, &hdfTsDiff); - HDF_LOGE("%s %ds %dus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); + HDF_LOGE("%s %us %uus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); UT_TEST_CHECK_RET(!OsalCheckTime(&hdfTsDiff, TIME_TEST_SLEEP_S * HDF_KILO_UNIT), OSAL_TIME_DIFFTIME); OsalGetTime(&hdfTs); OsalUDelay(TIME_TEST_SLEEP_MS); (void)OsalGetTime(&hdfTs2); (void)OsalDiffTime(&hdfTs, &hdfTs2, &hdfTsDiff); - HDF_LOGE("%s %ds %dus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); + HDF_LOGE("%s %us %uus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); OsalGetTime(&hdfTs); OsalMDelay(TIME_TEST_SLEEP_MS); (void)OsalGetTime(&hdfTs2); (void)OsalDiffTime(&hdfTs, &hdfTs2, &hdfTsDiff); - HDF_LOGE("%s %ds %dus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); + HDF_LOGE("%s %us %uus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); OsalGetTime(&hdfTs); OsalMSleep(TIME_TEST_SLEEP_MS); ret = OsalGetTime(&hdfTs2); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIME_GETTIME); ret = OsalDiffTime(&hdfTs, &hdfTs2, &hdfTsDiff); - HDF_LOGE("%s %ds %dus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); + HDF_LOGE("%s %us %uus", __func__, (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIME_DIFFTIME); UT_TEST_CHECK_RET(!OsalCheckTime(&hdfTsDiff, TIME_TEST_SLEEP_MS), OSAL_TIME_DIFFTIME); } diff --git a/test/unittest/osal/osal_get_case_test.c b/test/unittest/osal/osal_get_case_test.c index 4a2db735..25b87dff 100644 --- a/test/unittest/osal/osal_get_case_test.c +++ b/test/unittest/osal/osal_get_case_test.c @@ -11,7 +11,7 @@ int OsalGetTestResult(uint32_t cmd) { - HDF_LOGD("[OSAL_UT_TEST]%s %d start", __func__, cmd); + HDF_LOGD("[OSAL_UT_TEST]%s %u start", __func__, cmd); return OSAL_TEST_CASE_CHECK(cmd); } diff --git a/test/unittest/osal/osal_test_entry.c b/test/unittest/osal/osal_test_entry.c index c53b3303..922e2f52 100644 --- a/test/unittest/osal/osal_test_entry.c +++ b/test/unittest/osal/osal_test_entry.c @@ -29,7 +29,7 @@ int32_t HdfOsalEntry(HdfTestMsg *msg) return HDF_FAILURE; } - HDF_LOGD("HdfTest:osal test result[%s-%d %d]", ((result != 0) ? "failed" : "pass"), result, msg->subCmd); + HDF_LOGD("HdfTest:osal test result[%s-%d %u]", ((result != 0) ? "failed" : "pass"), result, msg->subCmd); msg->result = (result != 0) ? HDF_FAILURE : HDF_SUCCESS; return HDF_SUCCESS; diff --git a/test/unittest/platform/common/emmc_test.c b/test/unittest/platform/common/emmc_test.c index 02dc29db..9aaab3e4 100644 --- a/test/unittest/platform/common/emmc_test.c +++ b/test/unittest/platform/common/emmc_test.c @@ -46,7 +46,7 @@ static int32_t TestEmmcGetCid(struct EmmcTester *tester) ret = EmmcGetCid(tester->handle, cid, EMMC_CID_LEN); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: EmmcGetCid fail! ret=%d.", __func__, ret); + HDF_LOGE("%s: EmmcGetCid failed ret=%d.", __func__, ret); return HDF_FAILURE; } for (i = 0; i < EMMC_CID_LEN; i++) { @@ -62,7 +62,7 @@ struct EmmcTestFunc g_emmcTestFunc[] = { static int32_t EmmcTestEntry(struct EmmcTester *tester, int32_t cmd) { int32_t i; - int32_t ret; + int32_t ret = HDF_SUCCESS; bool isFind = false; if (tester == NULL) { @@ -71,7 +71,7 @@ static int32_t EmmcTestEntry(struct EmmcTester *tester, int32_t cmd) } tester->handle = EmmcTestGetHandle(tester); if (tester->handle == NULL) { - HDF_LOGE("%s: emmc test get handle fail", __func__); + HDF_LOGE("%s: emmc test get handle failed", __func__); return HDF_FAILURE; } for (i = 0; i < sizeof(g_emmcTestFunc) / sizeof(g_emmcTestFunc[0]); i++) { @@ -81,9 +81,9 @@ static int32_t EmmcTestEntry(struct EmmcTester *tester, int32_t cmd) break; } } - if (isFind == false) { + if (!isFind) { ret = HDF_ERR_NOT_SUPPORT; - HDF_LOGE("%s: cmd %d not support", __func__, cmd); + HDF_LOGE("%s: cmd %d not supported", __func__, cmd); } EmmcTestReleaseHandle(tester->handle); return ret; @@ -96,19 +96,19 @@ static int32_t EmmcTestFillConfig(struct EmmcTester *tester, const struct Device drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); if (drsOps == NULL || drsOps->GetUint32 == NULL) { - HDF_LOGE("%s: invalid drs ops fail!", __func__); + HDF_LOGE("%s: invalid drs ops", __func__); return HDF_FAILURE; } ret = drsOps->GetUint32(node, "busNum", &(tester->busNum), 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: fill bus num fail!", __func__); + HDF_LOGE("%s: fill bus num failed", __func__); return ret; } ret = drsOps->GetUint32(node, "hostId", &(tester->hostId), 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: fill hostId fail!", __func__); + HDF_LOGE("%s: fill hostId failed", __func__); return ret; } @@ -147,7 +147,7 @@ static int32_t EmmcTestInit(struct HdfDeviceObject *device) } ret = EmmcTestFillConfig(tester, device->property); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read config fail!", __func__); + HDF_LOGE("%s: read config failed", __func__); return ret; } tester->TestEntry = EmmcTestEntry; diff --git a/test/unittest/platform/common/gpio_test.c b/test/unittest/platform/common/gpio_test.c index 7600efd6..658291b7 100644 --- a/test/unittest/platform/common/gpio_test.c +++ b/test/unittest/platform/common/gpio_test.c @@ -195,7 +195,7 @@ static int32_t TestCaseGpioIrq(struct GpioTester *tester, uint16_t mode, bool in } #endif if (tester->irqCnt <= 0) { - HDF_LOGE("%s: mode:%x on %u fail!", __func__, mode, tester->gpioIrq); + HDF_LOGE("%s: set mode:%x on %u failed", __func__, mode, tester->gpioIrq); return HDF_FAILURE; } return HDF_SUCCESS; diff --git a/test/unittest/platform/common/i2c_driver_test.c b/test/unittest/platform/common/i2c_driver_test.c index e5e28545..ed88adfb 100644 --- a/test/unittest/platform/common/i2c_driver_test.c +++ b/test/unittest/platform/common/i2c_driver_test.c @@ -24,7 +24,7 @@ static int32_t I2cTestDispatch(struct HdfDeviceIoClient *client, int cmd, struct return HDF_ERR_INVALID_PARAM; } if (!HdfSbufWriteBuffer(reply, &g_config, sizeof(g_config))) { - HDF_LOGE("%s: writ reply fail!", __func__); + HDF_LOGE("%s: write reply failed", __func__); return HDF_ERR_IO; } } else { @@ -41,37 +41,37 @@ static int32_t I2cTestReadConfig(struct I2cTestConfig *config, const struct Devi drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); if (drsOps == NULL || drsOps->GetUint32 == NULL) { - HDF_LOGE("%s: invalid drs ops fail!", __func__); + HDF_LOGE("%s: invalid drs ops", __func__); return HDF_FAILURE; } ret = drsOps->GetUint16(node, "bus_num", &config->busNum, 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read bus num fail!", __func__); + HDF_LOGE("%s: read bus num failed", __func__); return ret; } ret = drsOps->GetUint16(node, "dev_addr", &config->devAddr, 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read dev addr fail!", __func__); + HDF_LOGE("%s: read dev addr failed", __func__); return ret; } ret = drsOps->GetUint16(node, "reg_len", &config->regLen, 1); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read reg len fail!", __func__); + HDF_LOGE("%s: read reg len failed", __func__); return ret; } ret = drsOps->GetUint16(node, "reg_addr", &config->regAddr, 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read reg addr fail!", __func__); + HDF_LOGE("%s: read reg addr failed", __func__); return ret; } ret = drsOps->GetUint16(node, "buf_size", &config->bufSize, 0); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read buf size fail!", __func__); + HDF_LOGE("%s: read buf size failed", __func__); return ret; } @@ -90,7 +90,7 @@ static int32_t I2cTestBind(struct HdfDeviceObject *device) ret = I2cTestReadConfig(&g_config, device->property); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read config fail!", __func__); + HDF_LOGE("%s: read config failed", __func__); return ret; } diff --git a/test/unittest/platform/common/i2c_test.c b/test/unittest/platform/common/i2c_test.c index 47801f6e..cba586b2 100644 --- a/test/unittest/platform/common/i2c_test.c +++ b/test/unittest/platform/common/i2c_test.c @@ -23,7 +23,7 @@ #define I2C_TEST_BUF_SIZE_MAX 128 #define I2C_TEST_REG_LEN 2 #define I2C_TEST_MLTTHD_TIMES 1000 -#define I2C_TEST_STACK_SIZE (1024*100) +#define I2C_TEST_STACK_SIZE (1024 * 100) #define I2C_TEST_WAIT_TIMES 200 static struct I2cMsg g_msgs[I2C_TEST_MSG_NUM]; @@ -84,7 +84,7 @@ struct I2cTester *I2cTesterGet(void) static struct I2cTester tester; static bool hasInit = false; - if (hasInit == true) { + if (hasInit) { return &tester; } @@ -96,7 +96,7 @@ struct I2cTester *I2cTesterGet(void) tester.handle = I2cOpen(tester.config.busNum); if (tester.handle == NULL) { - HDF_LOGE("I2cTesterGet: open i2cBus:%u fail! handle:%p", tester.config.busNum, tester.handle); + HDF_LOGE("I2cTesterGet: open i2cBus:%u fail!", tester.config.busNum); return NULL; } @@ -217,14 +217,14 @@ int32_t I2cTestWriteRead(void) return HDF_SUCCESS; } -static int I2cTestThreadFunc(void *parm) +static int I2cTestThreadFunc(void *param) { int32_t i, ret; struct I2cTester *tester = NULL; tester = I2cTesterGet(); if (tester == NULL || tester->handle == NULL) { - *((int32_t *)parm) = 1; + *((int32_t *)param) = 1; return HDF_ERR_INVALID_OBJECT; } @@ -239,7 +239,7 @@ static int I2cTestThreadFunc(void *parm) } } - *((int32_t *)parm) = 1; + *((int32_t *)param) = 1; return HDF_SUCCESS; } diff --git a/test/unittest/platform/common/platform_driver_test.c b/test/unittest/platform/common/platform_driver_test.c index 55917a14..832be851 100644 --- a/test/unittest/platform/common/platform_driver_test.c +++ b/test/unittest/platform/common/platform_driver_test.c @@ -24,7 +24,7 @@ static void DoAllPlatformTest(void) static int32_t PlatformTestBind(struct HdfDeviceObject *device) { - struct IDeviceIoService service; + static struct IDeviceIoService service; if (device == NULL) { HDF_LOGE("%s: device is null!", __func__); diff --git a/test/unittest/platform/common/sdio_test.c b/test/unittest/platform/common/sdio_test.c index 800afbf8..f661c3fc 100644 --- a/test/unittest/platform/common/sdio_test.c +++ b/test/unittest/platform/common/sdio_test.c @@ -60,13 +60,13 @@ static int32_t TestSdioIncrAddrReadAndWriteOtherBytes(struct SdioTester *tester) HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: read, data[0]:%d\n", __func__, data[0]); + HDF_LOGE("%s: read, data[0]:%u\n", __func__, data[0]); ret = SdioWriteBytes(tester->handle, &data[0], addr, 1, 0); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: SdioWriteBytes fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: write, data[0]:%d\n", __func__, data[0]); + HDF_LOGE("%s: write, data[0]:%u\n", __func__, data[0]); return HDF_SUCCESS; } @@ -98,7 +98,7 @@ static int32_t TestSdioIncrAddrReadAndWriteOneByte(struct SdioTester *tester) HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: read, val:%d.", __func__, val); + HDF_LOGE("%s: read, val:%u.", __func__, val); /* read 1 bits */ addr++; ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); @@ -106,7 +106,7 @@ static int32_t TestSdioIncrAddrReadAndWriteOneByte(struct SdioTester *tester) HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: read, val:%d.", __func__, val); + HDF_LOGE("%s: read, val:%u.", __func__, val); return HDF_SUCCESS; } @@ -144,14 +144,14 @@ static int32_t TestSdioFixedAddrReadAndWriteOtherBytes(struct SdioTester *tester HDF_LOGE("%s: SdioReadBytesFromFixedAddr fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: read, data[0]:%d, data[1]:%d\n", __func__, data[0], data[1]); + HDF_LOGE("%s: read, data[0]:%u, data[1]:%u\n", __func__, data[0], data[1]); /* write bits */ ret = SdioWriteBytes(tester->handle, &data[0], addr, 1, 0); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: SdioWriteBytesToFixedAddr fail! ret=%d.", __func__, ret); return HDF_FAILURE; } - HDF_LOGE("%s: write, data[0]:%d, data[1]:%d.", __func__, data[0], data[1]); + HDF_LOGE("%s: write, data[0]:%u, data[1]:%u.", __func__, data[0], data[1]); return ret; } @@ -250,7 +250,7 @@ static int32_t TestSdioFunc0ReadAndWriteBytes(struct SdioTester *tester) } SdioReleaseHost(tester->handle); - HDF_LOGE("%s: Func0 Read, val :%d.", __func__, val); + HDF_LOGE("%s: Func0 Read, val:%u.", __func__, val); return ret; } @@ -264,7 +264,7 @@ static int32_t TestSdioSetAndGetFuncInfo(struct SdioTester *tester) HDF_LOGE("%s: SdioGetCommonInfo fail! ret=%d.", __func__, ret); return ret; } - HDF_LOGE("%s: succ! Timeout=%d.", __func__, info.funcInfo.enTimeout); + HDF_LOGE("%s: succ! Timeout=%u.", __func__, info.funcInfo.enTimeout); info.funcInfo.enTimeout = TEST_TIME_OUT; ret = SdioSetCommonInfo(tester->handle, &info, SDIO_FUNC_INFO); @@ -278,7 +278,7 @@ static int32_t TestSdioSetAndGetFuncInfo(struct SdioTester *tester) HDF_LOGE("%s: SdioGetCommonInfo fail! ret=%d.", __func__, ret); return ret; } - HDF_LOGE("%s: again succ! Timeout=%d.", __func__, info.funcInfo.enTimeout); + HDF_LOGE("%s: again succ! Timeout=%u.", __func__, info.funcInfo.enTimeout); return HDF_SUCCESS; } @@ -355,7 +355,7 @@ struct SdioTestFunc g_sdioTestFunc[] = { static int32_t SdioTestEntry(struct SdioTester *tester, int32_t cmd) { int32_t i; - int32_t ret; + int32_t ret = HDF_SUCCESS; bool isFind = false; if (tester == NULL) { @@ -374,7 +374,7 @@ static int32_t SdioTestEntry(struct SdioTester *tester, int32_t cmd) break; } } - if (isFind == false) { + if (!isFind) { ret = HDF_ERR_NOT_SUPPORT; HDF_LOGE("%s: cmd %d not support", __func__, cmd); } @@ -415,8 +415,8 @@ static int32_t SdioTestFillConfig(struct SdioTester *tester, const struct Device return ret; } - HDF_LOGE("%s: busNum:%d, funcNum:%d, vendorId:0x%x, deviceId:0x%x.", __func__, - tester->busNum, tester->funcNum, tester->vendorId, tester->deviceId); + HDF_LOGE("%s: busNum:%u, funcNum:%u, vendorId:0x%x.", __func__, + tester->busNum, tester->funcNum, tester->vendorId); return HDF_SUCCESS; } diff --git a/test/unittest/platform/common/uart_test.c b/test/unittest/platform/common/uart_test.c index 8808232f..ea7f59ff 100644 --- a/test/unittest/platform/common/uart_test.c +++ b/test/unittest/platform/common/uart_test.c @@ -62,7 +62,7 @@ static int32_t UartGetBaudTest(struct UartTest *test) HDF_LOGE("%s: error", __func__); return HDF_FAILURE; } - HDF_LOGE("%s: baud %d", __func__, baud); + HDF_LOGE("%s: baud %u", __func__, baud); HDF_LOGE("%s: success", __func__); return HDF_SUCCESS; } @@ -94,13 +94,13 @@ static int32_t UartGetAttributeTest(struct UartTest *test) HDF_LOGE("%s: error", __func__); return HDF_FAILURE; } - HDF_LOGE("dataBits %d", attribute.dataBits); - HDF_LOGE("parity %d", attribute.parity); - HDF_LOGE("stopBits %d", attribute.stopBits); - HDF_LOGE("rts %d", attribute.rts); - HDF_LOGE("cts %d", attribute.cts); - HDF_LOGE("fifoRxEn %d", attribute.fifoRxEn); - HDF_LOGE("fifoTxEn %d", attribute.fifoTxEn); + HDF_LOGE("dataBits %u", attribute.dataBits); + HDF_LOGE("parity %u", attribute.parity); + HDF_LOGE("stopBits %u", attribute.stopBits); + HDF_LOGE("rts %u", attribute.rts); + HDF_LOGE("cts %u", attribute.cts); + HDF_LOGE("fifoRxEn %u", attribute.fifoRxEn); + HDF_LOGE("fifoTxEn %u", attribute.fifoTxEn); HDF_LOGE("%s: success", __func__); return HDF_SUCCESS; } diff --git a/test/unittest/platform/common/watchdog_test.c b/test/unittest/platform/common/watchdog_test.c index 7d76b86b..ee2d9236 100644 --- a/test/unittest/platform/common/watchdog_test.c +++ b/test/unittest/platform/common/watchdog_test.c @@ -186,7 +186,7 @@ static int32_t TestCaseWatchdogReliability(struct WatchdogTester *tester) (void)WatchdogSetTimeout(NULL, WATCHDOG_TEST_TIMEOUT); /* invalid device handle */ (void)WatchdogGetTimeout(NULL, &timeout); - /* invalid timout pointer */ + /* invalid timeout pointer */ (void)WatchdogGetTimeout(tester->handle, NULL); HDF_LOGE("%s: test dfr for WatchdogFeed ...", __func__); diff --git a/test/unittest/platform/hdf_mipi_dsi_entry_test.c b/test/unittest/platform/hdf_mipi_dsi_entry_test.c index aab32cbf..c4001c21 100644 --- a/test/unittest/platform/hdf_mipi_dsi_entry_test.c +++ b/test/unittest/platform/hdf_mipi_dsi_entry_test.c @@ -23,7 +23,7 @@ int32_t HdfMipiDsiEntry(HdfTestMsg *msg) test = MipiDsiTestServiceGet(); if (test == NULL) { - HDF_LOGE("%s: get servie fail!\n", __func__); + HDF_LOGE("%s: get service fail!", __func__); return HDF_FAILURE; } diff --git a/test/unittest/platform/hdf_rtc_entry_test.c b/test/unittest/platform/hdf_rtc_entry_test.c index 1285bf9c..640bae98 100644 --- a/test/unittest/platform/hdf_rtc_entry_test.c +++ b/test/unittest/platform/hdf_rtc_entry_test.c @@ -36,7 +36,7 @@ static int8_t g_rtcIrqCallback = HDF_FAILURE; int32_t RtcAlarmACallback(enum RtcAlarmIndex alarmIndex) { if (alarmIndex == RTC_ALARM_INDEX_A) { - HDF_LOGE("RtcAlarmACallback alarm a success"); + HDF_LOGE("RtcAlarmACallback: alarm a callback success"); g_rtcIrqCallback = HDF_SUCCESS; } else { g_rtcIrqCallback = HDF_FAILURE; @@ -87,14 +87,14 @@ static int32_t RtcReadWriteTimeTest(struct RtcTime *writeTime) } ret = RtcWriteTime(g_rtcHandle, writeTime); if (ret != 0) { - HDF_LOGE("RtcReadWriteTimeTest write fail"); + HDF_LOGE("RtcReadWriteTimeTest write failed"); return -1; } OsalMSleep(RTC_TEST_WR_WAIT_MS); ret = RtcReadTime(g_rtcHandle, &readTime); if (ret != 0) { - HDF_LOGE("RtcReadWriteTimeTest read fail"); + HDF_LOGE("RtcReadWriteTimeTest read failed"); return -1; } @@ -116,14 +116,14 @@ static int32_t RtcReadWriteAlarmTimeTest(struct RtcTime *writeTime) ret = RtcWriteAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, writeTime); if (ret != 0) { - HDF_LOGE("RtcReadWriteAlarmTimeTest write fail"); + HDF_LOGE("RtcReadWriteAlarmTimeTest write failed"); return -1; } OsalMSleep(RTC_TEST_WR_WAIT_MS); ret = RtcReadAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, &readTime); if (ret != 0) { - HDF_LOGE("RtcReadWriteAlarmTimeTest read fail"); + HDF_LOGE("RtcReadWriteAlarmTimeTest read failed"); return -1; } @@ -152,7 +152,7 @@ static int32_t RtcReadWriteTime(void) ret = RtcReadWriteTimeTest(&tm); if (ret != 0) { - HDF_LOGE("RtcReadWriteTime fail"); + HDF_LOGE("RtcReadWriteTime failed"); return -1; } @@ -176,7 +176,7 @@ static int32_t RtcReadWriteMaxTime(void) tm.weekday = weekday; ret = RtcReadWriteTimeTest(&tm); if (ret == 0) { - HDF_LOGE("RtcReadWriteMaxTime fail"); + HDF_LOGE("RtcReadWriteMaxTime failed"); return -1; } @@ -200,7 +200,7 @@ static int32_t RtcReadWriteMinTime(void) tm.weekday = weekday; ret = RtcReadWriteTimeTest(&tm); if (ret == 0) { - HDF_LOGE("RtcReadWriteMinTime fail"); + HDF_LOGE("RtcReadWriteMinTime failed"); return -1; } @@ -225,7 +225,7 @@ static int32_t RtcReadWriteAlarmTime(void) tm.weekday = weekday; ret = RtcReadWriteAlarmTimeTest(&tm); if (ret != 0) { - HDF_LOGE("RtcReadWriteAlarmTime read fail"); + HDF_LOGE("RtcReadWriteAlarmTime read failed"); return -1; } @@ -249,7 +249,7 @@ static int32_t RtcReadWriteMaxAlarmTime(void) tm.weekday = weekday; ret = RtcReadWriteAlarmTimeTest(&tm); if (ret == 0) { - HDF_LOGE("RtcReadWriteMaxAlarmTime read fail"); + HDF_LOGE("RtcReadWriteMaxAlarmTime read failed"); return -1; } @@ -273,7 +273,7 @@ static int32_t RtcReadWriteMinAlarmTime(void) time.weekday = weekday; ret = RtcReadWriteAlarmTimeTest(&time); if (ret == 0) { - HDF_LOGE("RtcReadWriteMinAlarmTime read fail"); + HDF_LOGE("RtcReadWriteMinAlarmTime read failed"); return -1; } @@ -299,12 +299,12 @@ static int32_t RtcAlarmEnable(void) tm.weekday = weekday; ret = RtcReadWriteAlarmTimeTest(&tm); if (ret != 0) { - HDF_LOGE("RtcReadWriteAlarmTime read fail"); + HDF_LOGE("RtcReadWriteAlarmTime read failed"); return -1; } ret = RtcAlarmInterruptEnable(g_rtcHandle, RTC_ALARM_INDEX_A, 1); if (ret != 0) { - HDF_LOGE("RtcAlarmInterruptEnable fail"); + HDF_LOGE("RtcAlarmInterruptEnable failed"); return -1; } return 0; @@ -323,17 +323,17 @@ static int32_t RtcAlarmIrqAttachConfig(void) ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, RtcAlarmACallback); if (ret != 0) { - HDF_LOGE("RtcRegisterAlarmCallback fail"); + HDF_LOGE("RtcRegisterAlarmCallback failed"); return -1; } ret = RtcSetFreq(g_rtcHandle, freq); if (ret != 0) { - HDF_LOGE("RtcSetFreq fail"); + HDF_LOGE("RtcSetFreq failed"); return -1; } ret = RtcAlarmInterruptEnable(g_rtcHandle, RTC_ALARM_INDEX_A, 1); if (ret != 0) { - HDF_LOGE("RtcAlarmInterruptEnable fail"); + HDF_LOGE("RtcAlarmInterruptEnable failed"); return -1; } return 0; @@ -361,24 +361,24 @@ static int32_t RtcAlarmIrq(void) time.weekday = weekday; ret = RtcAlarmIrqAttachConfig(); if (ret != 0) { - HDF_LOGE("RtcWriteTime fail"); + HDF_LOGE("RtcWriteTime failed"); return -1; } ret = RtcWriteTime(g_rtcHandle, &time); if (ret != 0) { - HDF_LOGE("RtcWriteTime fail"); + HDF_LOGE("RtcWriteTime failed"); return -1; } /* set alarm time 2020-08-08 Saturday 08:08:09 .000 */ time.second = RTC_TEST_TIME_SECOND + 1; ret = RtcWriteAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, &time); if (ret != 0) { - HDF_LOGE("RtcWriteAlarm fail"); + HDF_LOGE("RtcWriteAlarm failed"); return -1; } OsalSleep(RTC_TEST_WAIT_TIME_S); if (g_rtcIrqCallback == HDF_FAILURE) { - HDF_LOGE("RtcWriteAlarm fail"); + HDF_LOGE("RtcWriteAlarm failed"); return -1; } g_rtcIrqCallback = HDF_FAILURE; @@ -394,7 +394,7 @@ static int32_t RtcRegisterCallback(void) } ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, RtcAlarmACallback); if (ret != 0) { - HDF_LOGE("RtcRegisterCallback fail"); + HDF_LOGE("RtcRegisterCallback failed"); return -1; } return 0; @@ -410,7 +410,7 @@ static int32_t RtcRegisterNullCallback(void) ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, NULL); if (ret == 0) { - HDF_LOGE("RtcRegisterCallback fail"); + HDF_LOGE("RtcRegisterCallback failed"); return -1; } return 0; @@ -426,7 +426,7 @@ static int32_t RtcSetNormalFreq(void) ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ); if (ret != 0) { - HDF_LOGE("RtcSetNormalFreq fail"); + HDF_LOGE("RtcSetNormalFreq failed"); return -1; } return 0; @@ -442,7 +442,7 @@ static int32_t RtcSetMaxFreq(void) ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ * RTC_TIME_UNIT); if (ret == 0) { - HDF_LOGE("RtcSetMaxFreq fail"); + HDF_LOGE("RtcSetMaxFreq failed"); return -1; } return 0; @@ -458,7 +458,7 @@ static int32_t RtcSetMinFreq(void) ret = RtcSetFreq(g_rtcHandle, 0); if (ret == 0) { - HDF_LOGE("RtcSetMinFreq fail"); + HDF_LOGE("RtcSetMinFreq failed"); return -1; } ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ); @@ -476,12 +476,12 @@ static int32_t RtcReadWriteUserReg(void) ret = RtcWriteReg(g_rtcHandle, 0, value); if (ret != 0) { - HDF_LOGE("RtcReadWriteUserReg write fail"); + HDF_LOGE("RtcReadWriteUserReg write failed"); return -1; } ret = RtcReadReg(g_rtcHandle, 0, &value); if (ret != 0) { - HDF_LOGE("RtcSetMinFreq read fail"); + HDF_LOGE("RtcSetMinFreq read failed"); return -1; } if (value != RTC_TEST_USER_VALUE) { @@ -501,12 +501,12 @@ static int32_t RtcReadWriteMaxUserIndex(void) ret = RtcWriteReg(g_rtcHandle, RTC_TEST_USER_MAX_INDEX, value); if (ret == 0) { - HDF_LOGE("RtcReadWriteUserReg write fail"); + HDF_LOGE("RtcReadWriteUserReg write failed"); return -1; } ret = RtcReadReg(g_rtcHandle, RTC_TEST_USER_MAX_INDEX, &value); if (ret == 0) { - HDF_LOGE("RtcSetMinFreq read fail"); + HDF_LOGE("RtcSetMinFreq read failed"); return -1; } return 0; diff --git a/test/unittest/platform/hdf_rtc_entry_test.h b/test/unittest/platform/hdf_rtc_entry_test.h index 98df0ef6..3f3997e1 100644 --- a/test/unittest/platform/hdf_rtc_entry_test.h +++ b/test/unittest/platform/hdf_rtc_entry_test.h @@ -34,4 +34,4 @@ typedef enum { } HdfRtcTestCaseCmd; int32_t HdfRtcEntry(HdfTestMsg *msg); -#endif // HDF_RTC_ENTRY_TEST_H \ No newline at end of file +#endif /* HDF_RTC_ENTRY_TEST_H */ diff --git a/test/unittest/sensor/hdf_sensor_test.c b/test/unittest/sensor/hdf_sensor_test.c index 45526d45..09f5485d 100644 --- a/test/unittest/sensor/hdf_sensor_test.c +++ b/test/unittest/sensor/hdf_sensor_test.c @@ -177,7 +177,7 @@ int32_t InitSensorDriverTest(struct HdfDeviceObject *device) struct SensorDeviceInfo deviceInfo = { .sensorInfo = { .sensorName = "sensor_test", - .vendorName = "huawei", + .vendorName = "default", .firmwareVersion = "1.0", .hardwareVersion = "1.0", .sensorTypeId = SENSOR_TAG_NONE, diff --git a/test/unittest/wifi/hdf_wifi_test.c b/test/unittest/wifi/hdf_wifi_test.c index 30f5053b..4132c8fa 100644 --- a/test/unittest/wifi/hdf_wifi_test.c +++ b/test/unittest/wifi/hdf_wifi_test.c @@ -54,10 +54,15 @@ int32_t HdfWifiEntry(HdfTestMsg *msg) { int32_t result, i; + if (msg == NULL) { + HDF_LOGE("%s is fail: HdfTestMsg is NULL!", __func__); + return HDF_SUCCESS; + } + for (i = 0; i < sizeof(g_hdfWiFiTestCaseList) / sizeof(g_hdfWiFiTestCaseList[0]); ++i) { if ((msg->subCmd == g_hdfWiFiTestCaseList[i].subCmd) && (g_hdfWiFiTestCaseList[i].testFunc != NULL)) { result = g_hdfWiFiTestCaseList[i].testFunc(); - HDF_LOGE("HdfTest:Wifi test result[%s-%d]", ((result == 0) ? "pass" : "fail"), msg->subCmd); + HDF_LOGE("HdfTest:Wifi test result[%s-%u]", ((result == 0) ? "pass" : "fail"), msg->subCmd); msg->result = (result == 0) ? HDF_SUCCESS : HDF_FAILURE; return HDF_SUCCESS; } diff --git a/test/unittest/wifi/hdf_wifi_test.h b/test/unittest/wifi/hdf_wifi_test.h index 3cf27f56..294ecec4 100644 --- a/test/unittest/wifi/hdf_wifi_test.h +++ b/test/unittest/wifi/hdf_wifi_test.h @@ -44,7 +44,6 @@ typedef enum { WIFI_MODULE_ADD_FEATURE, WIFI_MODULE_DELETE_FEATURE, WIFI_MODULE_END = 200, - /* message */ WIFI_MESSAGE_QUEUE_001 = WIFI_MODULE_END, WIFI_MESSAGE_QUEUE_002, diff --git a/tools/hc-gen/Makefile b/tools/hc-gen/Makefile index 3b75b8ee..9dcdfae0 100644 --- a/tools/hc-gen/Makefile +++ b/tools/hc-gen/Makefile @@ -16,7 +16,7 @@ BOUNDS_CHECK_LIB := $(abspath ../../../../third_party/bounds_checking_function/) INCLUDE_DIR := ./include $(BOUNDS_CHECK_LIB)/include OUT_DIR := build -TEST_CASE := $(abspath ../../../adapter/khdf/liteos/test/tools/hc-gen/test/unittest) +TEST_CASE := $(abspath ../../../adapter/lite/khdf/test/tools/hc-gen/test/unittest) ORIGIN_SOURCES := $(wildcard src/*) ORIGIN_SOURCES += $(wildcard $(BOUNDS_CHECK_LIB)/src/*) diff --git a/tools/hc-gen/README.md b/tools/hc-gen/README.md index 7a56a9e8..40a65171 100755 --- a/tools/hc-gen/README.md +++ b/tools/hc-gen/README.md @@ -1 +1 @@ -hc-gen compilation requires flex and bison, make sure that they are installed before compiling. +hc-gen compilation requires flex and bison, so make sure they are installed before you get start. \ No newline at end of file diff --git a/tools/hc-gen/bin/hc-gen b/tools/hc-gen/bin/hc-gen index 196de129..a759c477 100755 Binary files a/tools/hc-gen/bin/hc-gen and b/tools/hc-gen/bin/hc-gen differ diff --git a/tools/hc-gen/include/hcs_compiler.h b/tools/hc-gen/include/hcs_compiler.h index 3e6371cb..8ef1aa7d 100644 --- a/tools/hc-gen/include/hcs_compiler.h +++ b/tools/hc-gen/include/hcs_compiler.h @@ -18,7 +18,7 @@ #define HBC_MAGIC_NUM 0xA00AA00A #define HCS_COMPILER_VERSION_MAJOR 00 -#define HCS_COMPILER_VERSION_MINOR 65 +#define HCS_COMPILER_VERSION_MINOR 66 typedef struct HbcHeader { uint32_t magicNumber; @@ -31,8 +31,8 @@ typedef struct HbcHeader { /* Parse compiler options */ int32_t DoOption(int32_t argc, char *argv[]); -int32_t HcsDoCompile(); +int32_t HcsDoCompile(void); -int32_t HcsDoOptimize(); +int32_t HcsDoOptimize(void); #endif // HCS_COMPILER_H diff --git a/tools/hc-gen/include/hcs_decompiler.h b/tools/hc-gen/include/hcs_decompiler.h index 32bd8800..ae5cbd4b 100644 --- a/tools/hc-gen/include/hcs_decompiler.h +++ b/tools/hc-gen/include/hcs_decompiler.h @@ -11,8 +11,8 @@ #include "hcs_compiler.h" -int32_t HcsDoDecompile(); +int32_t HcsDoDecompile(void); -int32_t HcsDecompileOutput(); +int32_t HcsDecompileOutput(void); #endif // HCS_DECOMPILE_H diff --git a/tools/hc-gen/include/hcs_file.h b/tools/hc-gen/include/hcs_file.h index 7411dd6d..e891f832 100644 --- a/tools/hc-gen/include/hcs_file.h +++ b/tools/hc-gen/include/hcs_file.h @@ -34,7 +34,7 @@ struct HcsSourceName { struct HcsSourceName *next; }; -const char *HcsGetInputFileName(); +const char *HcsGetInputFileName(void); void HcsSetInputFileName(const char *name); @@ -46,9 +46,11 @@ int32_t HcsSetOutPutName(const char *name); int32_t HcsSetOutPutNameWithCurrentWorkPath(const char *name); -const char *HcsGetOutPutFileName(); +const char *HcsGetOutPutFilePath(void); -const char *HcsGetStripedOutputFileName(); +char *HcsGetOutputFileNameWithoutSuffix(void); + +const char *HcsGetOutputFileName(void); struct HcsFile *HcsOpenOutputFile(const char *suffix); @@ -56,6 +58,8 @@ void HcsCloseOutput(struct HcsFile *output); int32_t HcsOutputWrite(const void *buffer, uint32_t length); +int32_t HcsFormatOutputWrite(const char *format, ...); + int32_t HcsOutputWriteAlign(const void *buffer, uint32_t length); void HcsMockOutPut(bool dummyOutput); @@ -66,13 +70,13 @@ void HcsResetOutputCurrentCount(void); void HcsSourceQueuePush(struct HcsFile *sourceFile); -void HcsSourceQueuePop(); +void HcsSourceQueuePop(void); -struct HcsFile *HcsSourceQueueTop(); +struct HcsFile *HcsSourceQueueTop(void); -uint32_t HcsSourceQueueSize(); +uint32_t HcsSourceQueueSize(void); -const char *HcsGetCurrentSourceName(); +const char *HcsGetCurrentSourceName(void); int32_t HcsSourceNameSetPush(const char *name); diff --git a/tools/hc-gen/include/hcs_gener.h b/tools/hc-gen/include/hcs_gener.h index ae29334a..c3706da1 100644 --- a/tools/hc-gen/include/hcs_gener.h +++ b/tools/hc-gen/include/hcs_gener.h @@ -11,8 +11,8 @@ #include -int32_t HcsBytecodeOutput(); -int32_t HcsTextCodeOutput(); +int32_t HcsBytecodeOutput(void); +int32_t HcsTextCodeOutput(void); 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 index bc71064a..76b8ff80 100644 --- a/tools/hc-gen/include/hcs_log.h +++ b/tools/hc-gen/include/hcs_log.h @@ -39,7 +39,7 @@ #define HCS_OBJECT_PR(prefix, object, fmt, args...) \ do { \ - HCS_LOG_PRINT (prefix": %s:%u\n\t" fmt"\n", \ + HCS_LOG_PRINT(prefix": %s:%u\n\t" fmt"\n", \ object ? ((ParserObjectBase*)object)->src : "unknown", \ object ? ((ParserObjectBase*)object)->lineno : 0, \ ##args); \ @@ -52,12 +52,20 @@ #define PRINTF_CHECK_AND_RETURN(printRes) \ do { \ if ((printRes) < 0) { \ - HCS_ERROR("Error:%s(%d), sprintf_s fail", \ + HCS_ERROR("Error:%s(%d), sprintf_s failed", \ + __FUNCTION__, __LINE__); \ + return EOUTPUT; \ + } \ + } while (0) + +#define OUTPUT_CHECK_AND_RETURN(printRes) \ + do { \ + if ((printRes) < 0) { \ + HCS_ERROR("Error:%s(%d), output write failed", \ __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_opcode.h b/tools/hc-gen/include/hcs_opcode.h index 0c32eacb..1e8f1d65 100644 --- a/tools/hc-gen/include/hcs_opcode.h +++ b/tools/hc-gen/include/hcs_opcode.h @@ -27,7 +27,7 @@ typedef struct { const char *opStr; } OpCodeMapEntry; -const OpCodeMapEntry *HcsGetOpCodeMap(); +const OpCodeMapEntry *HcsGetOpCodeMap(void); const OpCodeMapEntry *HcsParserObjectTypeToByteCode(uint32_t objectType); diff --git a/tools/hc-gen/include/hcs_option.h b/tools/hc-gen/include/hcs_option.h index 034d940c..9ec430e7 100644 --- a/tools/hc-gen/include/hcs_option.h +++ b/tools/hc-gen/include/hcs_option.h @@ -10,20 +10,20 @@ #define HCS_COMPILER_OPTION_H #include -bool HcsOptShouldAlign(); +bool HcsOptShouldAlign(void); void HcsOptSetAlign(bool align); -bool HcsOptShouldGenTextConfig(); +bool HcsOptShouldGenTextConfig(void); -bool HcsOptShouldGenByteCodeConfig(); +bool HcsOptShouldGenByteCodeConfig(void); -bool HcsOptDecompile(); +bool HcsOptDecompile(void); -bool HcsOptShouldGenHexdump(); +bool HcsOptShouldGenHexdump(void); -const char *HcsOptGetSymbolNamePrefix(); +const char *HcsOptGetSymbolNamePrefix(void); -bool HcsVerbosePrint(); +bool HcsVerbosePrint(void); #endif // HCS_COMPILER_OPTION_H diff --git a/tools/hc-gen/src/hcs_ast.c b/tools/hc-gen/src/hcs_ast.c index 5b2365f4..4348483a 100644 --- a/tools/hc-gen/src/hcs_ast.c +++ b/tools/hc-gen/src/hcs_ast.c @@ -6,13 +6,13 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "hcs_ast.h" #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; @@ -24,14 +24,14 @@ bool HcsIsAnonymousObject(const ParserObject *obj) ParserObject *HcsAllocParserObject(void) { - ParserObject *new = (ParserObject *)HcsMemZalloc(sizeof(ParserObject)); - if (new == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + ParserObject *newObject = (ParserObject *)HcsMemZalloc(sizeof(ParserObject)); + if (newObject == NULL) { + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return NULL; } - new->objectBase.src = HcsGetCurrentSourceName(); - new->objectBase.lineno = HcsGetCurrentSourceLine(); - return new; + newObject->objectBase.src = HcsGetCurrentSourceName(); + newObject->objectBase.lineno = HcsGetCurrentSourceLine(); + return newObject; } void HcsAstFreeObject(ParserObject *object) @@ -77,7 +77,7 @@ void HcsDeleteParserObjectTree(ParserObject *object) if (object == NULL) { return; } - /* delete current and subtree */ + /* delete current tree and subtree */ HcsAstFreeObjectAndSubtree(object); } @@ -89,7 +89,7 @@ ParserObject *HcsGetParserRoot(void) HCS_DEBUG("instance root node"); char *rootNodeName = strdup("root"); if (rootNodeName == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return NULL; } g_parserRoot = HcsNewConfigNode(rootNodeName, CONFIG_NODE_NOREF, NULL); @@ -311,7 +311,7 @@ static ParserObject *HcsParserObjectClone(const ParserObject *object) } ParserObject *clone = HcsAllocParserObject(); if (clone == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return NULL; } @@ -384,7 +384,7 @@ int32_t HcsAstCopyArray(const ParserObject *src, ParserObject *dst) while (arrayElement != NULL) { ParserObject *copy = HcsParserObjectClone(arrayElement); if (copy == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return EOOM; } HcsAstAddChild(dst, copy); @@ -407,7 +407,7 @@ static int32_t HcsCopyObject(const ParserObject *src, ParserObject *dst) 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__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return EOOM; } } else if (src->objectBase.type == PARSEROP_ARRAY) { @@ -442,7 +442,6 @@ static int32_t HcsAstCopyTree(ParserObject *src, ParserObject *dstTree, uint32_t } } 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; } diff --git a/tools/hc-gen/src/hcs_bytecode_gen.c b/tools/hc-gen/src/hcs_bytecode_gen.c index 39512292..caf56b8b 100644 --- a/tools/hc-gen/src/hcs_bytecode_gen.c +++ b/tools/hc-gen/src/hcs_bytecode_gen.c @@ -83,9 +83,9 @@ static int32_t ByteCodeWriteWalk(ParserObject *current, int32_t walkDepth) } int32_t ret = NOERR; switch (current->objectBase.opCode) { - case HCS_BYTE_OP: - case HCS_WORD_OP: - case HCS_DWORD_OP: + case HCS_BYTE_OP: /* fall-through */ + case HCS_WORD_OP: /* fall-through */ + case HCS_DWORD_OP: /* fall-through */ case HCS_QWORD_OP: { const OpCodeMapEntry *byteCodeMap = HcsGetOpCodeMap(); ret = HcsOutputWriteAlign(¤t->objectBase.integerValue, byteCodeMap[current->objectBase.type].size); @@ -103,7 +103,6 @@ static int32_t ByteCodeWriteWalk(ParserObject *current, int32_t walkDepth) } 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)); @@ -122,20 +121,20 @@ static int32_t ByteCodeWriteWalk(ParserObject *current, int32_t walkDepth) return ret; } -int32_t HcsBytecodeOutput() +int32_t HcsBytecodeOutput(void) { ParserObject *astRoot = HcsGetParserRoot(); if (astRoot == NULL) { return EFAIL; } - /* generate OpCode for every object on AST and calculate size for each */ + /* generate OpCode for every object on AST and calculate size for each object */ int32_t ret = HcsWalkAst(astRoot, AST_WALK_BACKEND, NULL, ByteCodeConvert); if (ret) { return ret; } - /* ast data is ready, do binder output */ + /* ast data is ready, do bindary output */ struct HcsFile *outputFIle = HcsOpenOutputFile(HCS_OUTPUT_FILE_SUFFIX); HbcHeader header = { @@ -181,7 +180,7 @@ int32_t HcsBytecodeOutput() HcsCloseOutput(outputFIle); HCS_DEBUG("Total size: %u ", astRoot->objectBase.size); if (ret == NOERR && HcsOptShouldGenHexdump()) { - ret = HcsBinaryToHexdump(HcsGetOutPutFileName()); + ret = HcsBinaryToHexdump(HcsGetOutPutFilePath()); } return ret; } diff --git a/tools/hc-gen/src/hcs_decompile_gen.c b/tools/hc-gen/src/hcs_decompile_gen.c index 5959fc52..c253ff2b 100644 --- a/tools/hc-gen/src/hcs_decompile_gen.c +++ b/tools/hc-gen/src/hcs_decompile_gen.c @@ -30,7 +30,7 @@ static char *HcsAssembleNodeRefName(char *buff, uint32_t buffSize, const char *n } char *str = strdup(buff); if (str == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return NULL; } return str; @@ -83,65 +83,59 @@ static char *HcsGetNodeRefPath(uint64_t hash) return NULL; } -static int32_t HcsDecompilePrintBaseType(char *buffer, uint32_t bufferSize, const ParserObject *object); +static int32_t HcsDecompilePrintBaseType(const ParserObject *object); -static int32_t HcsDecompilePrintArrayType(char *buffer, uint32_t bufferSize, const ParserObject *object) +static int32_t HcsDecompilePrintArrayType(const ParserObject *object) { - int32_t res = sprintf_s(buffer, bufferSize, "["); - PRINTF_CHECK_AND_RETURN(res); + int32_t res; + PRINTF_CHECK_AND_RETURN(HcsFormatOutputWrite("[")); ParserObject *arrayElement = (ParserObject *)object->objectBase.child; while (arrayElement->objectBase.next) { - res = HcsDecompilePrintBaseType(buffer + strlen(buffer), bufferSize - strlen(buffer), arrayElement); + res = HcsDecompilePrintBaseType(arrayElement); if (res) { return EOUTPUT; } - res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ", "); - PRINTF_CHECK_AND_RETURN(res); + PRINTF_CHECK_AND_RETURN(HcsFormatOutputWrite(", ")); arrayElement = (ParserObject *)arrayElement->objectBase.next; } - res = HcsDecompilePrintBaseType(buffer + strlen(buffer), bufferSize - strlen(buffer), arrayElement); + res = HcsDecompilePrintBaseType(arrayElement); if (res) { return EOUTPUT; } - res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), "]"); - PRINTF_CHECK_AND_RETURN(res); - return NOERR; + return HcsFormatOutputWrite("]"); } -static int32_t HcsDecompilePrintBaseType(char *buffer, uint32_t bufferSize, const ParserObject *object) +static int32_t HcsDecompilePrintBaseType(const ParserObject *object) { - int32_t res; + int32_t res = NOERR; 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); + res = HcsFormatOutputWrite("0x%"PRIx64, object->objectBase.integerValue); break; case PARSEROP_STRING: - res = sprintf_s(buffer, bufferSize, "\"%s\"", object->objectBase.stringValue); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite("\"%s\"", object->objectBase.stringValue); break; case PARSEROP_NODEREF: { char *refPath = HcsGetNodeRefPath(object->objectBase.value); if (refPath == NULL) { return EOUTPUT; } - res = sprintf_s(buffer, bufferSize, "&%s", refPath); + res = HcsFormatOutputWrite("&%s", refPath); HcsMemFree(refPath); - PRINTF_CHECK_AND_RETURN(res); } break; case PARSEROP_ARRAY: - return HcsDecompilePrintArrayType(buffer, bufferSize, object); + return HcsDecompilePrintArrayType(object); default: HCS_ERROR("unknown OpCode %u", object->objectBase.type); return EFAIL; } - return NOERR; + return res; } static int32_t HcsDecompileOutputWalk(ParserObject *current, int32_t walkDepth) @@ -151,41 +145,31 @@ static int32_t HcsDecompileOutputWalk(ParserObject *current, int32_t walkDepth) } 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); + PRINTF_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c", tabSize, ' ')); } 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%s {\n", current->configNode.name)); if (current->objectBase.child == NULL) { - res = sprintf_s(writeBuffer + strlen(writeBuffer) - 1, - WRITE_BUFFER_LEN - strlen(writeBuffer) + 1, "}\n"); - PRINTF_CHECK_AND_RETURN(res); + return HcsFormatOutputWrite("%*c}\n", tabSize, ' '); } 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%s = ", current->configNode.name)); + res = HcsDecompilePrintBaseType( + (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; + return HcsFormatOutputWrite(";\n"); default: break; } - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return NOERR; } static int32_t HcsDecompileCloseBraceGen(ParserObject *current, int32_t walkDepth) @@ -193,22 +177,13 @@ static int32_t HcsDecompileCloseBraceGen(ParserObject *current, int32_t walkDept 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)); + return current != HcsGetParserRoot() ? HcsFormatOutputWrite("%*c}\n", tabSize, ' ') : + HcsFormatOutputWrite("}\n"); } -int32_t HcsDecompileOutput() +int32_t HcsDecompileOutput(void) { ParserObject *astRoot = HcsGetParserRoot(); if (astRoot == NULL) { @@ -221,8 +196,7 @@ int32_t HcsDecompileOutput() goto OUT; } - const char *fileHeader = HCS_DECOMPILE_FILE_HEADER; - if (HcsOutputWrite(fileHeader, strlen(fileHeader))) { + if (HcsFormatOutputWrite(HCS_DECOMPILE_FILE_HEADER) != EOK) { goto OUT; } diff --git a/tools/hc-gen/src/hcs_decompiler.c b/tools/hc-gen/src/hcs_decompiler.c index 2aac4443..f69414e1 100644 --- a/tools/hc-gen/src/hcs_decompiler.c +++ b/tools/hc-gen/src/hcs_decompiler.c @@ -6,14 +6,14 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include +#include "hcs_decompiler.h" +#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); @@ -42,7 +42,7 @@ static bool HcsVerifyHbcFile() } HCS_INFO("Build by hcs compile %u.%u", header.versionMajor, header.versionMinor); - HCS_INFO("hcb file total size: %u\n", header.totalSize); + HCS_INFO("hcb file total size: %d\n", header.totalSize); return true; } @@ -74,7 +74,7 @@ static char *ReadCString() } char *str = strdup(buff); if (str == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return NULL; } return str; @@ -348,7 +348,7 @@ static bool RebuildAst() return true; } -int32_t HcsDoDecompile() +int32_t HcsDoDecompile(void) { struct HcsFile *source = NULL; uint32_t ret = HcsOpenSourceFile(HcsGetInputFileName(), &source, "rb"); diff --git a/tools/hc-gen/src/hcs_file.c b/tools/hc-gen/src/hcs_file.c index 34b50002..e3cdedaa 100644 --- a/tools/hc-gen/src/hcs_file.c +++ b/tools/hc-gen/src/hcs_file.c @@ -6,6 +6,7 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "hcs_file.h" #include #include #include @@ -15,11 +16,10 @@ #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 char *g_outputFileName = NULL; +static FILE *g_outputFile = NULL; +static const char *g_inputFileName = NULL; static bool g_dummyOutput = false; static uint32_t g_outputWriteCount = 0; static struct HcsFileQueue g_inputSourceFileQueue = { 0 }; @@ -30,20 +30,17 @@ void HcsSetInputFileName(const char *name) g_inputFileName = name; } -const char *HcsGetInputFileName() +const char *HcsGetInputFileName(void) { 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__); + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return EOOM; } head->name = name; @@ -61,13 +58,13 @@ int32_t HcsSourceNameSetPush(const char *name) last = last->next; } - struct HcsSourceName *new = HcsMemZalloc(sizeof(struct HcsSourceName)); - if (new == NULL) { - HCS_ERROR("%s %d %s OOM", __FILE__, __LINE__, __func__); + struct HcsSourceName *newName = HcsMemZalloc(sizeof(struct HcsSourceName)); + if (newName == NULL) { + HCS_ERROR("%s:%d OOM", __func__, __LINE__); return EOOM; } - new->name = name; - pre->next = new; + newName->name = name; + pre->next = newName; return NOERR; } @@ -101,6 +98,9 @@ void HcsSourceNameSetClean(void) static const char *GetFileName(const char *path) { + if (path == NULL) { + return NULL; + } int32_t length = (int32_t)strlen(path); int32_t i = length - 1; for (; i >= 0; --i) { @@ -147,7 +147,7 @@ static int32_t CopyAndSaveFileName(const char *filePath, char **savedFileName, c } /* if no specified output file name, use input name */ - if (HcsGetOutPutFileName() == NULL && HcsSetOutPutNameWithCurrentWorkPath(fileName)) { + if (HcsGetOutPutFilePath() == NULL && HcsSetOutPutNameWithCurrentWorkPath(fileName)) { HcsMemFree((void *)fileName); return EOOM; } @@ -172,26 +172,25 @@ int32_t HcsOpenSourceFile(const char *path, struct HcsFile **file, const char *f char *realPath = realpath(path, pathBuf); #endif if (realPath == NULL) { - HCS_ERROR("fail to open source file: %s", path); + HCS_ERROR("failed to open source file: %s", path); return EINVALF; } /* push to name set and check reopen */ - int32_t ret = HcsSourceNameSetFind(realPath); - if (ret == true) { + if (HcsSourceNameSetFind(realPath)) { 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); + HCS_ERROR("failed to open source file: %s", realPath); return EINVALF; } char *fileName = NULL; char *filePath = NULL; - ret = CopyAndSaveFileName(realPath, &fileName, &filePath); + int32_t ret = CopyAndSaveFileName(realPath, &fileName, &filePath); if (ret) { fclose(f); return EFAIL; @@ -200,6 +199,7 @@ int32_t HcsOpenSourceFile(const char *path, struct HcsFile **file, const char *f struct HcsFile *sourceFile = HcsMemZalloc(sizeof(struct HcsFile)); if (sourceFile == NULL) { HcsMemFree(fileName); + HcsMemFree(filePath); fclose(f); HCS_ERROR("oom"); return EOOM; @@ -272,17 +272,17 @@ int32_t HcsSetOutPutNameWithCurrentWorkPath(const char *name) int32_t HcsSetOutPutName(const char *name) { - if (g_outputFilename != NULL) { - HcsMemFree(g_outputFilename); + if (g_outputFileName != NULL) { + HcsMemFree(g_outputFileName); } - g_outputFilename = strdup(name); - if (g_outputFilename == NULL) { + g_outputFileName = strdup(name); + if (g_outputFileName == NULL) { HCS_ERROR("oom"); return EOOM; } #ifdef OS_WIN - char *temp = g_outputFilename; + char *temp = g_outputFileName; while (*temp != '\0') { if (*temp == UNIX_SEPARATOR) { *temp = WIN_SEPARATOR; @@ -296,13 +296,13 @@ int32_t HcsSetOutPutName(const char *name) bool HcsSetOutputFileSuffix(const char *suffix) { - const char *fileNameBefore = g_outputFilename; + const char *fileNameBefore = g_outputFileName; const char *fileNameWithoutSuffix = GetFileNameWithoutSuffix(fileNameBefore); if (fileNameWithoutSuffix == NULL) { return false; } - uint32_t newNameSize = strlen(g_outputFilename) + strlen(suffix) + 1; + uint32_t newNameSize = strlen(g_outputFileName) + strlen(suffix) + 1; char *newOutputFilename = HcsMemZalloc(newNameSize); if (newOutputFilename == NULL) { HcsMemFree((void *)fileNameWithoutSuffix); @@ -312,37 +312,58 @@ bool HcsSetOutputFileSuffix(const char *suffix) int32_t ret = strcpy_s(newOutputFilename, newNameSize, fileNameWithoutSuffix); HcsMemFree((void *)fileNameWithoutSuffix); if (ret) { - HCS_ERROR("string copy fail"); + HCS_ERROR("failed to copy string"); HcsMemFree(newOutputFilename); return false; } ret = strcat_s(newOutputFilename, newNameSize, suffix); if (ret) { - HCS_ERROR("string copy fail"); + HCS_ERROR("failed to copy string"); HcsMemFree(newOutputFilename); return false; } HcsMemFree((void *)fileNameBefore); - g_outputFilename = newOutputFilename; + g_outputFileName = newOutputFilename; return true; } // return output file name only -const char *HcsGetStripedOutputFileName() +const char *HcsGetOutputFileName(void) { - return GetFileName(g_outputFilename); + return GetFileName(g_outputFileName); } -// return full path of output file -const char *HcsGetOutPutFileName() +char *HcsGetOutputFileNameWithoutSuffix(void) { - return g_outputFilename; + const char *fileName = HcsGetOutputFileName(); + if (fileName == NULL) { + return NULL; + } + + char *retName = strdup(fileName); + if (retName == NULL) { + HCS_ERROR("oom"); + return NULL; + } + + char *dot = strchr(retName, '.'); + if (dot != NULL) { + *dot = '\0'; + } + return retName; +} + + +// return full path of output file +const char *HcsGetOutPutFilePath(void) +{ + return g_outputFileName; } bool HcsOutputNameVerify() { - const char *fileName = g_outputFilename; + const char *fileName = g_outputFileName; char lastChar = fileName[strlen(fileName) - 1]; if (lastChar == OS_SEPARATOR) { HCS_ERROR("output name is DIR"); @@ -360,10 +381,10 @@ struct HcsFile *HcsOpenOutputFile(const char *suffix) 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); + const char *outputFileName = HcsGetOutPutFilePath(); + g_outputFile = fopen(outputFileName, "wb"); + if (g_outputFile == NULL) { + HCS_ERROR("failed to open output file: %s", outputFileName); return NULL; } @@ -371,12 +392,12 @@ struct HcsFile *HcsOpenOutputFile(const char *suffix) struct HcsFile *outputFile = HcsMemZalloc(sizeof(struct HcsFile)); if (outputFile == NULL) { HCS_ERROR("oom"); - fclose(g_outputFIle); - g_outputFIle = NULL; + fclose(g_outputFile); + g_outputFile = NULL; return NULL; } outputFile->name = outputFileName; - outputFile->file = g_outputFIle; + outputFile->file = g_outputFile; outputFile->pos = 0; outputFile->fullPath = outputFileName; g_outputWriteCount = 0; @@ -404,15 +425,38 @@ int32_t HcsOutputWrite(const void *buffer, uint32_t length) return NOERR; } - uint32_t writeLen = fwrite(buffer, 1, length, g_outputFIle); + uint32_t writeLen = fwrite(buffer, 1, length, g_outputFile); if (writeLen != length) { - HCS_ERROR("output file write fail"); + HCS_ERROR("failed to write output file"); return EOUTPUT; } return NOERR; } +#define WRITE_MAX_PER_TIME 2048 + +int32_t HcsFormatOutputWrite(const char *format, ...) +{ + if (format == NULL) { + return EINVALARG; + } + static char writeBuffer[WRITE_MAX_PER_TIME] = {'\0'}; + + va_list argList; + + va_start(argList, format); + int length = vsprintf_s(writeBuffer, WRITE_MAX_PER_TIME, format, argList); + va_end(argList); + (void)argList; + + if (length < 0) { + HCS_ERROR("Output too long in one time"); + return EOUTPUT; + } + return HcsOutputWrite(writeBuffer, length); +} + int32_t HcsOutputWriteAlign(const void *buffer, uint32_t length) { static const uint8_t alignData[ALIGN_SIZE] = {0}; @@ -460,7 +504,7 @@ void HcsSourceQueuePush(struct HcsFile *sourceFile) sourceQueue->count++; } -void HcsSourceQueuePop() +void HcsSourceQueuePop(void) { struct HcsFileQueue *sourceQueue = &g_inputSourceFileQueue; if (sourceQueue->head == NULL) { @@ -470,17 +514,17 @@ void HcsSourceQueuePop() sourceQueue->count--; } -struct HcsFile *HcsSourceQueueTop() +struct HcsFile *HcsSourceQueueTop(void) { return g_inputSourceFileQueue.head; } -uint32_t HcsSourceQueueSize() +uint32_t HcsSourceQueueSize(void) { return g_inputSourceFileQueue.count; } -const char *HcsGetCurrentSourceName() +const char *HcsGetCurrentSourceName(void) { struct HcsFile *source = HcsSourceQueueTop(); return source ? source->fullPath : ""; @@ -488,19 +532,12 @@ const char *HcsGetCurrentSourceName() 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) { + const char *c = strrchr(fullPath, OS_SEPARATOR); + if (c == NULL) { HCS_ERROR("%s: path '%s' not include dir", __func__, fullPath); return false; } - + int32_t len = (int32_t)(c - fullPath) + 1; int32_t ret = strncpy_s(dst, dstBufferSize, fullPath, len); if (ret) { HCS_ERROR("%s:string copy fail", __func__); diff --git a/tools/hc-gen/src/hcs_hexdump.c b/tools/hc-gen/src/hcs_hexdump.c index 59d634a5..6ac7f981 100644 --- a/tools/hc-gen/src/hcs_hexdump.c +++ b/tools/hc-gen/src/hcs_hexdump.c @@ -61,13 +61,14 @@ int32_t HcsBinaryToHexdump(const char *inputFileName) struct HcsFile *out = HcsOpenOutputFile(HCS_HEXDUMP_FILE_SUFFIX); if (out == NULL) { - HCS_ERROR("can not open %s", HcsGetOutPutFileName()); + HCS_ERROR("can not open %s", HcsGetOutPutFilePath()); + HcsCloseFile(source); return EINVALF; } int32_t ret = HcsHexdumpOutput(source->file, out->file); if (ret) { - HCS_ERROR("fail to gen bytecode hexdump in C style"); + HCS_ERROR("failed to gen bytecode hexdump in C style"); } HcsCloseFile(source); HcsCloseFile(out); diff --git a/tools/hc-gen/src/hcs_mem.c b/tools/hc-gen/src/hcs_mem.c index 410c66a2..e5ec7cb8 100644 --- a/tools/hc-gen/src/hcs_mem.c +++ b/tools/hc-gen/src/hcs_mem.c @@ -6,11 +6,11 @@ * See the LICENSE file in the root of this repository for complete details. */ +#include "hcs_mem.h" #include #include #include -#include "hcs_mem.h" -#define MEM_MAX (1024*1024) +#define MEM_MAX (1024 * 1024) void *HcsMemAlloc(uint32_t size) { @@ -18,8 +18,7 @@ void *HcsMemAlloc(uint32_t size) return NULL; } - void *newMem = malloc(size); - return newMem; + return malloc(size); } void *HcsMemZalloc(uint32_t size) diff --git a/tools/hc-gen/src/hcs_middle.c b/tools/hc-gen/src/hcs_middle.c index 35301f84..b281764d 100644 --- a/tools/hc-gen/src/hcs_middle.c +++ b/tools/hc-gen/src/hcs_middle.c @@ -38,17 +38,14 @@ static ParserObject *HcsLookupAstObject(const ParserObject *current, const char ParserObject *object = HcsGetParserRoot(); while (nodeName != NULL) { object = HcsAstLookupObjectInChildren(object, nodeName); - if (object == NULL) + if (object == NULL) { break; + } nodeName = strtok(NULL, "."); } HcsMemFree(splitPath); - if (object != NULL) { - return object; - } - - return NULL; + return object; } static int32_t HcsExpandNodeRef(ParserObject *object) @@ -105,7 +102,7 @@ static int32_t HcsExpandNodeCopy(ParserObject *object) 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", + HCS_OBJECT_ERROR(object, "Not allow copy node has child node when output text config, at %s:%u", copyChild->src, copyChild->lineno); return EINVALARG; } @@ -340,12 +337,12 @@ static bool HcsApplyDelete(ParserObject *dst, ParserObject *src) 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); + HCS_OBJECT_ERROR(src, "merge different node to %s:%u", 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); + HCS_OBJECT_ERROR(src, "conflict type with %s:%u", dst->objectBase.src, dst->objectBase.lineno); return EINVALARG; } @@ -373,7 +370,7 @@ static int32_t HcsMergeTree(ParserObject *dst, ParserObject *src) 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, + HCS_OBJECT_ERROR(childSrc, "overwrite with different type at %s:%u", childDst->objectBase.src, childDst->objectBase.lineno); return EINVALARG; } @@ -435,7 +432,7 @@ static int32_t HcsMiddleMerge(ParserObject **mergedRoot) return NOERR; } -int32_t HcsDoOptimize() +int32_t HcsDoOptimize(void) { ParserObject *root = HcsGetParserRoot(); if (root == NULL) { diff --git a/tools/hc-gen/src/hcs_opcode.c b/tools/hc-gen/src/hcs_opcode.c index 3bfac2df..22adaa65 100644 --- a/tools/hc-gen/src/hcs_opcode.c +++ b/tools/hc-gen/src/hcs_opcode.c @@ -6,8 +6,8 @@ * See the LICENSE file in the root of this repository for complete details. */ -#include #include "hcs_opcode.h" +#include OpCodeMapEntry g_byteCodeMap[PARSEROP_COUNT] = { @@ -22,7 +22,7 @@ OpCodeMapEntry g_byteCodeMap[PARSEROP_COUNT] = { [PARSEROP_NODEREF] = {HCS_NODEREF_OP, DWORD_SIZE, "NodeRef"}, /* RefHashCode - DWORD */ }; -const OpCodeMapEntry *HcsGetOpCodeMap() +const OpCodeMapEntry *HcsGetOpCodeMap(void) { return g_byteCodeMap; } diff --git a/tools/hc-gen/src/hcs_option.c b/tools/hc-gen/src/hcs_option.c index 3958660b..3442275e 100644 --- a/tools/hc-gen/src/hcs_option.c +++ b/tools/hc-gen/src/hcs_option.c @@ -14,15 +14,15 @@ #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; +static bool g_genTextConfigOutput = false; +static bool g_genByteCodeConfigOutput = true; +static bool g_genByteCodeHexdump = false; +static bool g_verbosePrint = false; +static bool g_decompile = false; +static bool g_shouldAlign = false; +static const char *g_symbolPrefix = NULL; -bool HcsOptShouldAlign() +bool HcsOptShouldAlign(void) { return g_shouldAlign; } @@ -32,26 +32,27 @@ void HcsOptSetAlign(bool align) g_shouldAlign = align; } - -bool HcsOptShouldGenTextConfig() +bool HcsOptShouldGenTextConfig(void) { return g_genTextConfigOutput; } -bool HcsOptShouldGenByteCodeConfig() + +bool HcsOptShouldGenByteCodeConfig(void) { return g_genByteCodeConfigOutput; } -bool HcsOptDecompile() + +bool HcsOptDecompile(void) { return g_decompile; } -const char *HcsOptGetSymbolNamePrefix() +const char *HcsOptGetSymbolNamePrefix(void) { return g_symbolPrefix; } -bool HcsOptShouldGenHexdump() +bool HcsOptShouldGenHexdump(void) { return g_genByteCodeHexdump; } @@ -151,7 +152,7 @@ int32_t DoOption(int32_t argc, char *argv[]) return 0; } -bool HcsVerbosePrint() +bool HcsVerbosePrint(void) { return g_verbosePrint; } diff --git a/tools/hc-gen/src/hcs_parser.c b/tools/hc-gen/src/hcs_parser.c index 7e595cef..40eb343f 100644 --- a/tools/hc-gen/src/hcs_parser.c +++ b/tools/hc-gen/src/hcs_parser.c @@ -125,7 +125,7 @@ int32_t HcsProcessInclude(char *includePath, uint32_t lineNumber) return NOERR; } -int32_t HcsDoCompile() +int32_t HcsDoCompile(void) { struct HcsFile *source = NULL; char *forestName = strdup("ForestRoot"); diff --git a/tools/hc-gen/src/hcs_text_gen.c b/tools/hc-gen/src/hcs_text_gen.c index 00cce070..9513c372 100644 --- a/tools/hc-gen/src/hcs_text_gen.c +++ b/tools/hc-gen/src/hcs_text_gen.c @@ -18,20 +18,16 @@ #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 ELEMENT_PER_LINE 16 #define HCS_CONFIG_FILE_HEADER "/*\n" \ - " * It's HDF config auto-gen file, do not modify it manually\n" \ + " * This is an automatically generated HDF config 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" \ @@ -96,7 +92,7 @@ static int32_t InitConfigVariableNames() return EOOM; } if (strcpy_s(g_bigHumpModuleName, strlen(moduleName) + 1, moduleName) != EOK) { - HCS_ERROR("string copy fail"); + HCS_ERROR("failed to copy string"); return EFAIL; } ToUpperCamelString(g_bigHumpModuleName, strlen(g_bigHumpModuleName)); @@ -309,14 +305,16 @@ const char *g_typeMap[PARSEROP_COUNT] = { 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); + if (strcpy_s(nameBuffer, OBJECT_NAME_MAX_LEN, HcsGetModuleName()) != EOK) { + return EOUTPUT; + } ToUpperCamelString(nameBuffer, strlen(nameBuffer)); - res = sprintf_s(name, nameBuffLen, "%s%s", g_namePrefix, nameBuffer); + int32_t 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); + if (strcpy_s(nameBuffer, OBJECT_NAME_MAX_LEN, node->configNode.name) != EOK) { + return EOUTPUT; + } ToUpperCamelString(nameBuffer, strlen(nameBuffer)); res = sprintf_s(name + strlen(name), nameBuffLen - strlen(name), "%s", nameBuffer); PRINTF_CHECK_AND_RETURN(res); @@ -329,7 +327,7 @@ static int32_t GenConfigArrayName(ParserObject *array, char *name, uint32_t name char buffer[OBJECT_NAME_MAX_LEN] = {'\0'}; if (strcpy_s(buffer, sizeof(buffer), array->objectBase.name) != EOK) { - HCS_ERROR("%s: string copy fail", __func__); + HCS_ERROR("%s: failed to copy string", __func__); return EOUTPUT; } ToUpperCamelString(buffer, strlen(buffer)); @@ -376,32 +374,27 @@ static int32_t GetArraySize(const ParserObject *array) return size; } -static int32_t HcsPrintTermDefinition(char *buffer, uint32_t bufferSize, const ParserObject *object) +static int32_t HcsPrintTermDefinition(const ParserObject *object) { ParserObject *termContext = (ParserObject *)object->objectBase.child; - int32_t res; + int32_t res = NOERR; 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); + res = HcsFormatOutputWrite("const %s *%s;\n", GetArrayType(termContext), object->configTerm.name); + OUTPUT_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite("%*cuint32_t %sSize;\n", TAB_SIZE, ' ', object->configTerm.name); } else { - res = sprintf_s(buffer, bufferSize, "%s %s[%d];\n", GetArrayType(termContext), object->configTerm.name, + res = HcsFormatOutputWrite("%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); + res = HcsFormatOutputWrite("%s %s;\n", g_typeMap[termContext->objectBase.type], object->configTerm.name); break; case PARSEROP_NODEREF: { char refType[OBJECT_NAME_MAX_LEN] = {'\0'}; @@ -409,15 +402,13 @@ static int32_t HcsPrintTermDefinition(char *buffer, uint32_t bufferSize, const P 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); + res = HcsFormatOutputWrite("const struct %s* %s;\n", refType, object->configTerm.name); } break; default: break; } - return NOERR; + return res; } static int32_t HcsObjectDefinitionGen(const ParserObject *current) @@ -426,9 +417,8 @@ static int32_t HcsObjectDefinitionGen(const ParserObject *current) 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); + int res = NOERR; + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c", TAB_SIZE, ' ')); switch (current->objectBase.type) { case PARSEROP_CONFNODE: { char structName[OBJECT_NAME_MAX_LEN] = {'\0'}; @@ -438,32 +428,27 @@ static int32_t HcsObjectDefinitionGen(const ParserObject *current) } if (current->configNode.nodeType == CONFIG_NODE_TEMPLATE) { char nodeName[OBJECT_NAME_MAX_LEN] = {0}; - if (strcpy_s(nodeName, sizeof(nodeName), current->configNode.name)) { + if (strcpy_s(nodeName, sizeof(nodeName), current->configNode.name) != EOK) { 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("const struct %s* %s;\n", structName, nodeName)); + res = HcsFormatOutputWrite("%*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); + res = HcsFormatOutputWrite("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); + res = HcsPrintTermDefinition(current); break; default: break; } - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return res; } static int32_t HcsDuplicateCheckWalkCallBack(ParserObject *current, int32_t walkDepth) @@ -479,7 +464,6 @@ static int32_t HcsDuplicateCheckWalkCallBack(ParserObject *current, int32_t walk 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) { @@ -491,11 +475,7 @@ static int32_t HcsGenNormalNodeDefinition(ParserObject *object, int32_t walkDept 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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("struct %s {\n", structName)); ParserObject *terms = (ParserObject *)object->objectBase.child; while (terms != NULL) { @@ -506,10 +486,7 @@ static int32_t HcsGenNormalNodeDefinition(ParserObject *object, int32_t walkDept 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)); + return HcsFormatOutputWrite("};\n\n"); } static int32_t HcsGenNodeTemplateDefinition(ParserObject *object, int32_t walkDepth) @@ -532,20 +509,18 @@ static int32_t HcsDefinitionGenWalkCallBack(ParserObject *current, int32_t walkD } } -static uint32_t HcsPrintTermValue(char *buffer, uint32_t buffSize, const ParserObject *object) +static uint32_t HcsPrintTermValue(const ParserObject *object) { - int32_t res = 0; + int32_t res = NOERR; 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); + res = HcsFormatOutputWrite("0x%" PRIx64, object->objectBase.integerValue); break; case PARSEROP_STRING: - res = sprintf_s(buffer, buffSize, "\"%s\"", object->objectBase.stringValue); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite("\"%s\"", object->objectBase.stringValue); break; default: break; @@ -603,19 +578,15 @@ static char *HcsBuildObjectPath(const ParserObject *refObject) return path; } -static int32_t HcsPrintArrayImplInSubClass(char *buffer, uint32_t bufferSize, ParserObject *object, uint8_t tabSize) +static int32_t HcsPrintArrayImplInSubClass(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)) { + char arrayName[VARIABLE_NAME_LEN] = {0}; + if (GenConfigArrayName(object, arrayName, VARIABLE_NAME_LEN)) { 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)); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(".%s = %s,\n", object->objectBase.name, arrayName)); + return HcsFormatOutputWrite("%*c.%sSize = %d,\n", tabSize, ' ', + object->configTerm.name, GetArraySize((ParserObject *)object->objectBase.child)); } static int32_t HcsPrintArrayContent(const ParserObject *object, int32_t tabSize) @@ -624,59 +595,44 @@ static int32_t HcsPrintArrayContent(const ParserObject *object, int32_t tabSize) return NOERR; } - char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; ParserObject *element = (ParserObject *)object->objectBase.child; - uint32_t writeSize = 0; + uint32_t elementCount = 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; + if (HcsPrintTermValue(element) != NOERR) { + return EOUTPUT; + } + if (elementCount++ >= ELEMENT_PER_LINE) { + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("\n%*c", tabSize, ' ')); } element = (ParserObject *)element->configTerm.next; + if (element != NULL) { + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(", ")); + } } - return writeSize ? HcsOutputWrite(writeBuffer, writeSize - GEN_ARRAY_SEP_SIZE) : NOERR; + return NOERR; } -static int32_t HcsPrintArrayImplement(char *buffer, uint32_t bufferSize, ParserObject *object, uint8_t tabSize) +static int32_t HcsPrintArrayImplement(ParserObject *object, uint8_t tabSize) { if (HcsIsInSubClassNode(object)) { - return HcsPrintArrayImplInSubClass(buffer, bufferSize, object, tabSize); + return HcsPrintArrayImplInSubClass(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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(".%s = { ", object->configTerm.name)); + 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; + return HcsFormatOutputWrite(" },\n"); } -static int32_t HcsPrintTermImplement(char *buffer, uint32_t bufferSize, ParserObject *object, int32_t tabSize) +static int32_t HcsPrintTermImplement(ParserObject *object, int32_t tabSize) { - int32_t res; - sprintf_s(buffer, bufferSize, "%*c", tabSize, ' '); + int32_t res = NOERR; + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c", tabSize, ' ')); ParserObject *termContext = (ParserObject *)object->objectBase.child; switch (termContext->objectBase.type) { case PARSEROP_UINT8: @@ -686,52 +642,43 @@ static int32_t HcsPrintTermImplement(char *buffer, uint32_t bufferSize, ParserOb 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)) { + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(".%s = ", object->configTerm.name)); + if (HcsPrintTermValue(termContext) != NOERR) { return EOUTPUT; } - res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ",\n"); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite(",\n"); 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)) { + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(".%s = ", object->configTerm.name)); + if (HcsPrintTermValue(termContext) != NOERR) { return EOUTPUT; } - res = sprintf_s(buffer + strlen(buffer), bufferSize - strlen(buffer), ",\n"); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite(",\n"); break; case PARSEROP_ARRAY: - if (HcsPrintArrayImplement(buffer + strlen(buffer), bufferSize - strlen(buffer), object, tabSize)) { - return EOUTPUT; - } - buffer[0] = '\0'; + res = HcsPrintArrayImplement(object, tabSize); 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); + res = HcsFormatOutputWrite(".%s = &%s,\n", object->configTerm.name, refPath); HcsMemFree(refPath); - PRINTF_CHECK_AND_RETURN(res); break; } default: break; } - return NOERR; + return res; } 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"); + if (strcpy_s(tempName, sizeof(tempName), object->objectBase.name) != EOK) { + HCS_ERROR("failed to copy string"); return EOUTPUT; } ToUpperCamelString(tempName, sizeof(tempName)); @@ -756,24 +703,22 @@ static int32_t HcsGenTemplateVariableName(ParserObject *object, char *nameBuff, 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__); + if (strcpy_s(nodeName, sizeof(nodeName), current->configNode.name) != EOK) { + HCS_ERROR("%s: failed to copy string", __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", + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c.%s = %s,\n", tabSize, ' ', nodeName, + current->configNode.inheritCount ? templateVariableName : "0")); + + return HcsFormatOutputWrite("%*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) @@ -787,33 +732,26 @@ static int32_t HcsInheritObjectImplGen(ParserObject *current, int32_t tabSize) static int32_t HcsObjectImplementGen(ParserObject *current, int32_t tabSize) { - char writeBuffer[WRITE_BUFFER_LEN] = {'\0'}; - int32_t res; + int32_t res = NOERR; switch (current->objectBase.type) { - case PARSEROP_CONFNODE: { + 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c.%s = {\n", tabSize, ' ', current->configNode.name)); if (current->objectBase.child == NULL) { - res = sprintf_s(writeBuffer + strlen(writeBuffer) - 1, WRITE_BUFFER_LEN - strlen(writeBuffer) + 1, - "},\n"); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite("%*c},\n", tabSize, ' '); } - } break; + break; case PARSEROP_CONFTERM: - res = HcsPrintTermImplement(writeBuffer, WRITE_BUFFER_LEN, current, tabSize); - if (res) { - return res; - } + res = HcsPrintTermImplement(current, tabSize); break; default: return NOERR; } - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return res; } static int32_t HcsImplementGenWalkCallBack(ParserObject *current, int32_t walkDepth) @@ -827,20 +765,17 @@ static int32_t HcsImplementGenWalkCallBack(ParserObject *current, int32_t walkDe } 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("static const struct %s %s = {\n", + structName, GetConfigRootVariableName())); if (current->objectBase.child == NULL) { - res = sprintf_s(writeBuffer + strlen(writeBuffer), WRITE_BUFFER_LEN - strlen(writeBuffer), "};\n"); - PRINTF_CHECK_AND_RETURN(res); + res = HcsFormatOutputWrite("};\n"); } - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return res; } return HcsObjectImplementGen(current, walkDepth * TAB_SIZE); } @@ -856,18 +791,12 @@ static int32_t HcsImplementCloseBraceGen(ParserObject *current, int32_t walkDept } 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); + return HcsFormatOutputWrite("%*c},\n", tabSize, ' '); } else { - res = sprintf_s(writeBuffer, WRITE_BUFFER_LEN, "};\n"); - PRINTF_CHECK_AND_RETURN(res); + return HcsFormatOutputWrite("};\n"); } - - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); } static void ToUpperString(char *str, uint32_t strLen) @@ -877,118 +806,71 @@ static void ToUpperString(char *str, uint32_t strLen) } } -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"); + char *fileName = HcsGetOutputFileNameWithoutSuffix(); + if (fileName == NULL) { return NULL; } - StripFileNameSuffix(headerMacro, strlen(headerMacro)); - ToUpperString(headerMacro, strlen(headerMacro)); + ToUpperString(fileName, strlen(fileName)); char *macro = HcsMemZalloc(sizeof(char) * HCS_HEADER_MACRO_MAX_LEN); if (macro == NULL) { HCS_ERROR("oom"); - HcsMemFree(headerMacro); + HcsMemFree(fileName); return NULL; } - int32_t res = sprintf_s(macro, HCS_HEADER_MACRO_MAX_LEN, "HCS_CONFIG_%s_HEADER_H", headerMacro); + int32_t res = sprintf_s(macro, HCS_HEADER_MACRO_MAX_LEN, "HCS_CONFIG_%s_HEADER_H", fileName); + HcsMemFree(fileName); 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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite(HCS_CONFIG_FILE_HEADER)); /* 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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("#ifndef %s\n#define %s\n\n", + headerProtectMacro, headerProtectMacro)); /* Write include header file */ - header = HCS_CONFIG_INCLUDE_HEADER; - if (HcsOutputWrite(header, strlen(header))) { - return EOUTPUT; - } - - return NOERR; + return HcsFormatOutputWrite(HCS_CONFIG_INCLUDE_HEADER); } 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); + int32_t ret = HcsFormatOutputWrite("\n\n#endif // %s", headerMacro); HcsMemFree(headerMacro); - if (ret <= 0) { - return EOUTPUT; - } - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return ret; } 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, + return HcsFormatOutputWrite("const struct %s%sRoot* HdfGet%sModuleConfigRoot(void);", 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, + return HcsFormatOutputWrite(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() @@ -1064,47 +946,33 @@ static int32_t HcsTemplateImplGenWalkCallBack(ParserObject *current, int32_t wal 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); + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("static const struct %s ", nameBuff)); 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 */ + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%s[] = {\n", nameBuff)); + /* 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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c[%d] = {\n", TAB_SIZE, ' ', + subClasses->nodeObject->inheritIndex)); + 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; - } + OUTPUT_CHECK_AND_RETURN(HcsFormatOutputWrite("%*c},\n", TAB_SIZE, ' ')); subClasses = subClasses->next; } - res = sprintf_s(writeBuffer, sizeof(writeBuffer), "};\n\n"); - PRINTF_CHECK_AND_RETURN(res); - return HcsOutputWrite(writeBuffer, strlen(writeBuffer)); + return HcsFormatOutputWrite("};\n\n"); } static int32_t HcsArrayVariablesDeclareGen(ParserObject *term) @@ -1113,26 +981,21 @@ static int32_t HcsArrayVariablesDeclareGen(ParserObject *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), + res = HcsFormatOutputWrite("\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; - } + OUTPUT_CHECK_AND_RETURN(res); + 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)); + return HcsFormatOutputWrite("\n};\n"); } static int32_t HcsTemplateVariablesDeclareGenWalk(ParserObject *current, int32_t walkDepth) @@ -1174,10 +1037,8 @@ static int32_t HcsTemplateVariablesDeclareGen(ParserObject *astRoot) /* 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)); + const char *lineEnd = "\n"; + return HcsOutputWrite(lineEnd, strlen(lineEnd)); } static int32_t HcsOutputTemplateImplement(ParserObject *astRoot) @@ -1206,32 +1067,24 @@ static int32_t HcsOutputCFile() return EINVALF; } - const char *header = HCS_CONFIG_FILE_HEADER; - if (HcsOutputWrite(header, strlen(header))) { + if (HcsFormatOutputWrite(HCS_CONFIG_FILE_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); + char *fileName = HcsGetOutputFileNameWithoutSuffix(); + if (fileName == NULL) { 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))) { + int32_t res = HcsFormatOutputWrite("#include \"%s.h\"\n\n", fileName); + HcsMemFree(fileName); + if (res != NOERR) { HcsCloseOutput(outputFIle); return EOUTPUT; } res = HcsOutputTemplateImplement(astRoot); - if (res) { + if (res != NOERR) { HcsCloseOutput(outputFIle); return EOUTPUT; } @@ -1248,7 +1101,7 @@ static int32_t HcsOutputCFile() return res; } -int32_t HcsTextCodeOutput() +int32_t HcsTextCodeOutput(void) { int32_t ret = HcsSymbolTableInit(); if (ret) { diff --git a/utils/include/hdf_map.h b/utils/include/hdf_map.h new file mode 100644 index 00000000..df6c690c --- /dev/null +++ b/utils/include/hdf_map.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_MAP_H +#define HDF_MAP_H + +#include "hdf_base.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct MapNode; + +typedef struct { + struct MapNode **nodes; /**< Map node bucket */ + uint32_t nodeSize; /**< Map node count */ + uint32_t bucketSize; /**< Map node bucket size */ +} Map; + +void MapInit(Map *map); + +void MapDelete(Map *map); + +int32_t MapSet(Map *map, const char *key, const void *value, uint32_t valueSize); + +void *MapGet(const Map *map, const char *key); + +int32_t MapErase(Map *map, const char *key); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_MAP_H */ diff --git a/utils/include/hdf_message_looper.h b/utils/include/hdf_message_looper.h new file mode 100644 index 00000000..d11d79a9 --- /dev/null +++ b/utils/include/hdf_message_looper.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_MESSAGE_LOOPER_H +#define HDF_MESSAGE_LOOPER_H + +#include "osal_msg_queue.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define MESSAGE_STOP_LOOP (-1) + +struct HdfMessageLooper { + struct HdfMessageQueue messageQueue; + void (*Start)(struct HdfMessageLooper *); + void (*Stop)(struct HdfMessageLooper *); +}; + +void HdfMessageLooperConstruct(struct HdfMessageLooper *looper); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_MESSAGE_LOOPER_H */ diff --git a/utils/include/hdf_message_task.h b/utils/include/hdf_message_task.h new file mode 100644 index 00000000..9719084f --- /dev/null +++ b/utils/include/hdf_message_task.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_MESSAGE_TASK_H +#define HDF_MESSAGE_TASK_H + +#include "hdf_message_looper.h" +#include "osal_msg_queue.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfMessageTask; + +struct IHdfMessageHandler { + int32_t (*Dispatch)(struct HdfMessageTask *task, struct HdfMessage *msg); +}; + +struct HdfMessageTask { + int32_t (*SendMessage)(struct HdfMessageTask *task, struct HdfMessage *msg, bool sync); + void (*RemoveMessage)(struct HdfMessageTask *task, struct HdfMessage *msg); + void (*SendMessageLater)(struct HdfMessageTask *task, struct HdfMessage *msg, long delay); + void (*DispatchMessage)(struct HdfMessageTask *task, struct HdfMessage *msg); + struct HdfMessageQueue *messageQueue; + struct IHdfMessageHandler *messageHandler; +}; + +void HdfMessageTaskConstruct(struct HdfMessageTask *inst, + struct HdfMessageLooper *looper, struct IHdfMessageHandler *handler); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_MESSAGE_TASK_H */ diff --git a/utils/include/hdf_slist.h b/utils/include/hdf_slist.h index 94ec646e..f6b47a52 100644 --- a/utils/include/hdf_slist.h +++ b/utils/include/hdf_slist.h @@ -31,14 +31,14 @@ struct HdfSListIterator { typedef void (*HdfSListDeleter)(struct HdfSListNode *); -typedef bool (*HdfSListSearchCompare)(struct HdfSListNode *, uint32_t); +typedef bool (*HdfSListSearchComparer)(struct HdfSListNode *, uint32_t); -typedef bool (*HdfSListAddCompare)(struct HdfSListNode *, struct HdfSListNode *); +typedef bool (*HdfSListAddComparer)(struct HdfSListNode *, struct HdfSListNode *); /* * @brief Init the list * - * @param[in] list :the operation list. + * @param[in] list the operation list. * * @return None */ @@ -48,13 +48,13 @@ 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. + * @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); +struct HdfSListNode *HdfSListSearch(struct HdfSList *list, uint32_t searchKey, HdfSListSearchComparer comparer); /* * @brief tests if list is empty @@ -77,8 +77,8 @@ 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. + * @param[in] list the operation list. + * @param[in] link the new element to add. * * @return None */ @@ -88,7 +88,7 @@ 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. + * @param[in] link the new element to add. * * @return None */ @@ -98,22 +98,19 @@ 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. + * @param[in] link the new element to add. + * @param[in] comparer comparer of list node. * * @return bool result of queue status. */ -bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddCompare compare); +bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddComparer comparer); /* * @brief remove item from list * - * @param[in] list :the operation list. - * @param[in] p_node :the element to remove. + * @param[in] list the operation list. + * @param[in] link 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); @@ -121,7 +118,7 @@ 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. + * @param[in] deleter the function of free memory. * * @return None */ @@ -130,7 +127,7 @@ void HdfSListFlush(struct HdfSList *list, HdfSListDeleter deleter); /* * @brief calculate the element count in the list. * - * @param[in] list :the list to count. + * @param[in] list the list to count. * * @return the count of list. */ @@ -146,9 +143,9 @@ int HdfSListCount(struct HdfSList *list); struct HdfSListNode *HdfSListPeek(struct HdfSList *list); /* - * @brief get next element of p_link; + * @brief get next element of link; * - * @param[in] p_link: the operation link. + * @param[in] link the operation link. * * @return the next element of the link pass in */ @@ -203,7 +200,8 @@ 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. + * @param[in] iterator the point of iterator. + * @param[in] link the point of operation list. * * @return None */ diff --git a/utils/include/hdf_sref.h b/utils/include/hdf_sref.h index bfc4b6c5..04c1a367 100644 --- a/utils/include/hdf_sref.h +++ b/utils/include/hdf_sref.h @@ -27,10 +27,12 @@ struct HdfSRef { struct IHdfSRefListener *listener; void (*Acquire)(struct HdfSRef *); void (*Release)(struct HdfSRef *); + int (*Count)(const struct HdfSRef *); }; void HdfSRefAcquire(struct HdfSRef *sref); void HdfSRefRelease(struct HdfSRef *sref); +int HdfSRefCount(const struct HdfSRef *sref); void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener); #ifdef __cplusplus diff --git a/utils/include/hdf_thread_ex.h b/utils/include/hdf_thread_ex.h new file mode 100644 index 00000000..fad57898 --- /dev/null +++ b/utils/include/hdf_thread_ex.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_THREAD_H +#define HDF_THREAD_H + +#include +#include "osal_thread.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfThread { + struct OsalThread adapter; + bool status; + void (*ThreadEntry)(void *); + bool (*IsRunning)(); + void (*Start)(struct HdfThread *thread); + void (*Stop)(struct HdfThread *thread); +}; + +void HdfThreadConstruct(struct HdfThread *thread); +void HdfThreadDestruct(struct HdfThread *thread); +struct HdfThread *HdfThreadNewInstance(void); +void HdfThreadFreeInstance(struct HdfThread *instance); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* HDF_THREAD_H */ + diff --git a/utils/include/osal_cdev.h b/utils/include/osal_cdev.h new file mode 100644 index 00000000..b6895493 --- /dev/null +++ b/utils/include/osal_cdev.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef OSAL_CDEV_H +#define OSAL_CDEV_H + +#include "osal_cdev_adapter.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef __user +#define __user +#endif + +struct OsalCdev; +struct file; + +struct OsalCdevOps { + int64_t (*seek)(struct file* filep, int64_t offset, int whence); + ssize_t (*read)(struct file* filep, char __user* buffer, size_t buflen, int64_t* offset); + ssize_t (*write)(struct file* filep, const char __user* buffer, size_t buflen, int64_t* offset); + unsigned int (*poll)(struct file* filep, poll_table* pollTable); + long (*ioctl)(struct file* filep, unsigned int cmd, unsigned long arg); + int (*open)(struct OsalCdev* cdev, struct file* filep); + int (*release)(struct OsalCdev* cdev, struct file* filep); +}; + +struct OsalCdev* OsalAllocCdev(const struct OsalCdevOps* fops); +int OsalRegisterCdev(struct OsalCdev* cdev, const char *name, unsigned int mode, void *priv); +void OsalUnregisterCdev(struct OsalCdev* cdev); +void OsalFreeCdev(struct OsalCdev* cdev); + +void* OsalGetCdevPriv(struct OsalCdev* cdev); + +void OsalSetFilePriv(struct file* filep, void *priv); +void* OsalGetFilePriv(struct file* filep); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_CDEV_H */ +/** @} */ diff --git a/utils/include/osal_message.h b/utils/include/osal_message.h new file mode 100644 index 00000000..f06959f4 --- /dev/null +++ b/utils/include/osal_message.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef OSAL_MESSAGE_H +#define OSAL_MESSAGE_H + +#include "hdf_slist.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfMessage { + struct HdfSListNode entry; + struct HdfMessageTask *target; + int16_t messageId; + uint64_t timeStamp; + void *data[1]; +}; + +struct HdfMessage *HdfMessageObtain(size_t extendSize); +void HdfMessageRecycle(struct HdfMessage *message); +void HdfMessageDelete(struct HdfSListNode *listEntry); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_MESSAGE_H */ diff --git a/utils/include/osal_msg_queue.h b/utils/include/osal_msg_queue.h new file mode 100644 index 00000000..38ed3141 --- /dev/null +++ b/utils/include/osal_msg_queue.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef OSAL_MSG_QUEUE_H +#define OSAL_MSG_QUEUE_H + +#include "hdf_slist.h" +#include "osal_message.h" +#include "osal_mutex.h" +#include "osal_sem.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct HdfMessageQueue { + struct OsalMutex mutex; + struct OsalSem semaphore; + struct HdfSList list; +}; + +void OsalMessageQueueInit(struct HdfMessageQueue *queue); +void OsalMessageQueueDestroy(struct HdfMessageQueue *queue); +void HdfMessageQueueEnqueue( + struct HdfMessageQueue *queue, struct HdfMessage *message, long delayed); + +struct HdfMessage *HdfMessageQueueNext(struct HdfMessageQueue *queue); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_MSG_QUEUE_H */ diff --git a/utils/include/osal_sysevent.h b/utils/include/osal_sysevent.h new file mode 100644 index 00000000..b10a74c4 --- /dev/null +++ b/utils/include/osal_sysevent.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ +#ifndef OSAL_SYSEVENT_H +#define OSAL_SYSEVENT_H + +#include "hdf_dlist.h" + +#define HDF_SYSEVENT 0xFADE + +/* hdf sys event class definition */ +#define HDF_SYSEVENT_CLASS_POWER 0x00000001 + +/* hdf power event definition */ +enum PowerKeventId { + KEVENT_POWER_SUSPEND, + KEVENT_POWER_DISPLAY_OFF, + KEVENT_POWER_RESUME, + KEVENT_POWER_DISPLAY_ON, + KEVENT_POWER_EVENT_MAX, +}; + +struct HdfSysEvent { + uint64_t eventClass; + uint32_t eventid; + const char *content; + uint64_t syncToken; +}; + +struct HdfSysEventNotifyNode; + +typedef int (*HdfSysEventNotifierFn)( + struct HdfSysEventNotifyNode *self, uint64_t eventClass, uint32_t event, const char *content); + +struct HdfSysEventNotifyNode { + HdfSysEventNotifierFn callback; + struct DListHead listNode; + uint64_t classFilter; +}; + +int HdfSysEventNotifyRegister(struct HdfSysEventNotifyNode *notifierNode, uint64_t classSet); +void HdfSysEventNotifyUnregister(struct HdfSysEventNotifyNode *notifierNode); +int HdfSysEventSend(uint64_t eventClass, uint32_t event, const char *content, bool sync); + +#endif // #ifndef OSAL_SYSEVENT_H \ No newline at end of file diff --git a/utils/src/hdf_map.c b/utils/src/hdf_map.c new file mode 100644 index 00000000..67e14f45 --- /dev/null +++ b/utils/src/hdf_map.c @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_map.h" +#if defined(__KERNEL__) +#include +#else +#include +#endif +#include "osal_mem.h" +#include "securec.h" + +struct MapNode { + uint32_t hash; + uint32_t valueSize; + void *key; + void *value; + struct MapNode *next; +}; + +#define HDF_MIN_MAP_SIZE 8 +#define HDF_ENLARGE_FACTOR 2 +#define HDF_MAP_KEY_MAX_SIZE 1000 +#define HDF_MAP_VALUE_MAX_SIZE 1000 + +const uint32_t HASH_SEED = 131; + +/* BKDR Hash */ +static uint32_t MapHash(const char *hashKey) +{ + uint32_t hashValue = 0; + + while (*hashKey) { + hashValue = hashValue * HASH_SEED + (*hashKey++); + } + + return (hashValue & 0x7FFFFFFF); +} + +static uint32_t MapHashIdx(const Map *map, uint32_t hash) +{ + return (hash & (map->bucketSize - 1)); +} + +static void MapAddNode(Map *map, struct MapNode *node) +{ + uint32_t idx = MapHashIdx(map, node->hash); + node->next = map->nodes[idx]; + map->nodes[idx] = node; +} + +static int32_t MapResize(Map *map, uint32_t size) +{ + uint32_t bucketSize; + struct MapNode **nodes = NULL; + struct MapNode **tmp = NULL; + uint32_t i; + + nodes = (struct MapNode **)OsalMemCalloc(size * sizeof(*nodes)); + if (nodes == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + tmp = map->nodes; + bucketSize = map->bucketSize; + map->nodes = nodes; + map->bucketSize = size; + + if (tmp != NULL) { + struct MapNode *node = NULL; + struct MapNode *next = NULL; + + /* remap node with new map size */ + for (i = 0; i < bucketSize; i++) { + node = tmp[i]; + while (node != NULL) { + next = node->next; + MapAddNode(map, node); + node = next; + } + } + + OsalMemFree(tmp); + } + + return HDF_SUCCESS; +} + +static struct MapNode *MapCreateNode(const char *key, uint32_t hash, + const void *value, uint32_t valueSize) +{ + uint32_t keySize = strlen(key) + 1; + struct MapNode *node = (struct MapNode *)OsalMemCalloc(sizeof(*node) + keySize + valueSize); + if (node == NULL) { + return NULL; + } + + node->hash = hash; + node->key = (uint8_t *)node + sizeof(*node); + node->value = (uint8_t *)node + sizeof(*node) + keySize; + node->valueSize = valueSize; + if (memcpy_s(node->key, keySize, key, keySize) != EOK) { + OsalMemFree(node); + return NULL; + } + if (memcpy_s(node->value, node->valueSize, value, valueSize) != EOK) { + OsalMemFree(node); + return NULL; + } + + return node; +} + +int32_t MapSet(Map *map, const char *key, const void *value, uint32_t valueSize) +{ + struct MapNode *node = NULL; + + if (map == NULL || key == NULL || value == NULL || valueSize == 0) { + return HDF_ERR_INVALID_PARAM; + } + if (valueSize > HDF_MAP_KEY_MAX_SIZE || strlen(key) > HDF_MAP_VALUE_MAX_SIZE) { + return HDF_ERR_INVALID_PARAM; + } + uint32_t hash = MapHash(key); + if (map->nodeSize > 0 && map->nodes != NULL) { + uint32_t idx = MapHashIdx(map, hash); + node = map->nodes[idx]; + while (node != NULL) { + if (node->hash != hash || node->key == NULL || strcmp(node->key, key) != 0) { + node = node->next; + continue; + } + + // size mismatch + if (node->value == NULL || node->valueSize != valueSize) { + return HDF_ERR_INVALID_OBJECT; + } + // update k-v node + if (memcpy_s(node->value, node->valueSize, value, valueSize) != EOK) { + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + } + // Increase the bucket size to decrease the possibility of map search conflict. + if (map->nodeSize >= map->bucketSize) { + uint32_t size = (map->bucketSize < HDF_MIN_MAP_SIZE) ? HDF_MIN_MAP_SIZE : \ + (map->bucketSize << HDF_ENLARGE_FACTOR); + MapResize(map, size); + } + + node = MapCreateNode(key, hash, value, valueSize); + if (node == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + MapAddNode(map, node); + map->nodeSize++; + + return HDF_SUCCESS; +} + +void* MapGet(const Map *map, const char *key) +{ + if (map == NULL || key == NULL || map->nodeSize == 0 || map->nodes == NULL) { + return NULL; + } + + uint32_t hash = MapHash(key); + uint32_t idx = MapHashIdx(map, hash); + struct MapNode *node = map->nodes[idx]; + + while (node != NULL) { + if (node->hash == hash && node->key != NULL && !strcmp(node->key, key)) { + return node->value; + } + + node = node->next; + } + + return NULL; +} + +int32_t MapErase(Map *map, const char *key) +{ + if (map == NULL || key == NULL || map->nodeSize == 0 || map->nodes == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + uint32_t hash = MapHash(key); + uint32_t idx = MapHashIdx(map, hash); + struct MapNode *node = map->nodes[idx]; + struct MapNode *prev = node; + + while (node != NULL) { + if (node->hash == hash && node->key != NULL && !strcmp(node->key, key)) { + if (map->nodes[idx] == node) { + map->nodes[idx] = node->next; + } else { + prev->next = node->next; + } + OsalMemFree(node); + map->nodeSize--; + return HDF_SUCCESS; + } + prev = node; + node = node->next; + } + + return HDF_FAILURE; +} + +void MapInit(Map *map) +{ + if (map == NULL) { + return; + } + + map->nodes = NULL; + map->nodeSize = 0; + map->bucketSize = 0; +} + +void MapDelete(Map *map) +{ + uint32_t i; + struct MapNode *node = NULL; + struct MapNode *next = NULL; + + if (map == NULL || map->nodes == NULL) { + return; + } + + for (i = 0; i < map->bucketSize; i++) { + node = map->nodes[i]; + while (node != NULL) { + next = node->next; + OsalMemFree(node); + node = next; + } + } + + OsalMemFree(map->nodes); + + map->nodes = NULL; + map->nodeSize = 0; + map->bucketSize = 0; +} + diff --git a/utils/src/hdf_message_looper.c b/utils/src/hdf_message_looper.c new file mode 100644 index 00000000..b9aa190e --- /dev/null +++ b/utils/src/hdf_message_looper.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_message_looper.h" +#include "hdf_message_task.h" +#include "osal_message.h" + +void HdfMessageLooperStart(struct HdfMessageLooper *looper) +{ + struct HdfMessage *message = NULL; + while (looper != NULL) { + message = HdfMessageQueueNext(&looper->messageQueue); + if (message != NULL) { + if (message->messageId == MESSAGE_STOP_LOOP) { + HdfMessageRecycle(message); + OsalMessageQueueDestroy(&looper->messageQueue); + break; + } else if (message->target != NULL) { + struct HdfMessageTask *task = message->target; + task->DispatchMessage(task, message); + } + HdfMessageRecycle(message); + } + } +} + +void HdfMessageLooperStop(struct HdfMessageLooper *looper) +{ + if (looper == NULL) { + return; + } + + struct HdfMessage *message = HdfMessageObtain(0); + if (message != NULL) { + message->messageId = MESSAGE_STOP_LOOP; + HdfMessageQueueEnqueue(&looper->messageQueue, message, 0); + } +} + +void HdfMessageLooperConstruct(struct HdfMessageLooper *looper) +{ + if (looper != NULL) { + OsalMessageQueueInit(&looper->messageQueue); + looper->Start = HdfMessageLooperStart; + looper->Stop = HdfMessageLooperStop; + } +} + diff --git a/utils/src/hdf_message_task.c b/utils/src/hdf_message_task.c new file mode 100644 index 00000000..f8c24c18 --- /dev/null +++ b/utils/src/hdf_message_task.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_message_task.h" +#include "hdf_message_looper.h" +#include "osal_mem.h" +#include "osal_message.h" + +int32_t HdfMessageTaskSendMessageLater( + struct HdfMessageTask *task, struct HdfMessage *msg, bool sync, long delay) +{ + if (msg != NULL) { + if (msg->target == NULL) { + msg->target = task; + } + if (sync) { + if (task->messageHandler != NULL && task->messageHandler->Dispatch != NULL) { + int ret = task->messageHandler->Dispatch(task, msg); + OsalMemFree(msg); + return ret; + } + } else { + HdfMessageQueueEnqueue(task->messageQueue, msg, delay); + return HDF_SUCCESS; + } + } + + return HDF_ERR_INVALID_PARAM; +} + +int32_t HdfMessageTaskSendMessage(struct HdfMessageTask *task, struct HdfMessage *msg, bool sync) +{ + return HdfMessageTaskSendMessageLater(task, msg, sync, 0); +} + +void HdfMessageTaskDispatchMessage(struct HdfMessageTask *task, struct HdfMessage *msg) +{ + struct IHdfMessageHandler *handler = task->messageHandler; + if ((handler != NULL) && (handler->Dispatch != NULL)) { + handler->Dispatch(task, msg); + } +} + +void HdfMessageTaskConstruct(struct HdfMessageTask *inst, + struct HdfMessageLooper *looper, struct IHdfMessageHandler *handler) +{ + if (inst != NULL && looper != NULL) { + inst->SendMessage = HdfMessageTaskSendMessage; + inst->messageHandler = handler; + inst->messageQueue = &looper->messageQueue; + inst->DispatchMessage = HdfMessageTaskDispatchMessage; + } +} + diff --git a/utils/src/hdf_slist.c b/utils/src/hdf_slist.c index fdd13671..1aeb396c 100644 --- a/utils/src/hdf_slist.c +++ b/utils/src/hdf_slist.c @@ -23,16 +23,16 @@ bool HdfSListIsEmpty(struct HdfSList *list) return ((list == NULL) || (list->root == NULL)); } -struct HdfSListNode *HdfSListSearch(struct HdfSList *list, uint32_t keyValue, HdfSListSearchCompare compare) +struct HdfSListNode *HdfSListSearch(struct HdfSList *list, uint32_t keyValue, HdfSListSearchComparer comparer) { struct HdfSListIterator it; - if (compare == NULL) { + if (comparer == NULL) { return NULL; } HdfSListIteratorInit(&it, list); while (HdfSListIteratorHasNext(&it)) { struct HdfSListNode *listNode = HdfSListIteratorNext(&it); - if (compare(listNode, keyValue)) { + if (comparer(listNode, keyValue)) { return listNode; } } @@ -47,27 +47,17 @@ struct HdfSListNode *HdfSListGetLast(struct HdfSList *list) return NULL; } - for (iterator = list->root; iterator; iterator = iterator->next) { - if (iterator != NULL) { - last = iterator; - } + for (iterator = list->root; iterator != NULL; iterator = iterator->next) { + 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; } @@ -89,10 +79,10 @@ void HdfSListAddTail(struct HdfSList *list, struct HdfSListNode *link) iterator->next = link; } -bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddCompare compare) +bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSListAddComparer comparer) { struct HdfSListNode *iterator = NULL; - if (list == NULL || link == NULL || compare == NULL) { + if (list == NULL || link == NULL || comparer == NULL) { HDF_LOGE("input is invalid"); return false; } @@ -102,13 +92,13 @@ bool HdfSListAddOrder(struct HdfSList *list, struct HdfSListNode *link, HdfSList return false; } } - if (compare(link, list->root)) { + if (comparer(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)) { + if (comparer(iterator, link) && comparer(link, iterator->next)) { link->next = iterator->next; iterator->next = link; return true; diff --git a/utils/src/hdf_sref.c b/utils/src/hdf_sref.c index 9ea9733a..0df652be 100644 --- a/utils/src/hdf_sref.c +++ b/utils/src/hdf_sref.c @@ -28,6 +28,16 @@ void HdfSRefAcquire(struct HdfSRef *sref) } } +int HdfSRefCount(const struct HdfSRef *sref) +{ + if (sref == NULL) { + HDF_LOGE("invalid sref"); + return 0; + } + + return OsalAtomicRead(&sref->refs); +} + void HdfSRefRelease(struct HdfSRef *sref) { int32_t lockRef; @@ -55,5 +65,6 @@ void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener) sref->listener = listener; sref->Acquire = HdfSRefAcquire; sref->Release = HdfSRefRelease; + sref->Count = HdfSRefCount; } diff --git a/utils/src/hdf_thread_ex.c b/utils/src/hdf_thread_ex.c new file mode 100644 index 00000000..c4e1edea --- /dev/null +++ b/utils/src/hdf_thread_ex.c @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_thread_ex.h" +#include "osal_mem.h" +#include "osal_thread.h" + +void HdfThreadStart(struct HdfThread *thread) +{ + if (thread == NULL) { + return; + } + struct OsalThreadParam param = { + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = 0, + }; + OsalThreadStart(&thread->adapter, ¶m); + thread->status = true; +} + +void HdfThreadStop(struct HdfThread *thread) +{ + if (thread == NULL) { + return; + } + OsalThreadDestroy(&thread->adapter); + thread->status = false; +} + +bool HdfThreadIsRunning(struct HdfThread *thread) +{ + if (thread == NULL) { + return false; + } + return thread->status; +} + +void HdfThreadMain(void *argv) +{ + struct HdfThread *thread = (struct HdfThread *)argv; + if (thread == NULL) { + return; + } + if (thread->ThreadEntry != NULL) { + thread->ThreadEntry(argv); + } else { + OsalThreadDestroy(&thread->adapter); + } +} + +void HdfThreadConstruct(struct HdfThread *thread) +{ + if (thread == NULL) { + return; + } + thread->Start = HdfThreadStart; + thread->Stop = HdfThreadStop; + thread->IsRunning = HdfThreadIsRunning; + thread->status = false; + OsalThreadCreate(&thread->adapter, (OsalThreadEntry)HdfThreadMain, thread); +} + +void HdfThreadDestruct(struct HdfThread *thread) +{ + if (thread != NULL && thread->IsRunning()) { + thread->Stop(thread); + } +} + +struct HdfThread *HdfThreadNewInstance() +{ + struct HdfThread *thread = + (struct HdfThread *)OsalMemCalloc(sizeof(struct HdfThread)); + if (thread != NULL) { + HdfThreadConstruct(thread); + } + return thread; +} + +void HdfThreadFreeInstance(struct HdfThread *thread) +{ + if (thread != NULL) { + HdfThreadDestruct(thread); + OsalMemFree(thread); + } +} + diff --git a/utils/src/osal_message.c b/utils/src/osal_message.c new file mode 100644 index 00000000..03b756c9 --- /dev/null +++ b/utils/src/osal_message.c @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "osal_message.h" +#include "osal_mem.h" + +struct HdfMessage *HdfMessageObtain(size_t extendSize) +{ + size_t newSize = sizeof(struct HdfMessage) + extendSize; + return (struct HdfMessage *)OsalMemCalloc(newSize); +} + +void HdfMessageRecycle(struct HdfMessage *message) +{ + OsalMemFree(message); +} + +void HdfMessageDelete(struct HdfSListNode *listEntry) +{ + struct HdfMessage *message = (struct HdfMessage *)listEntry; + if (message != NULL) { + HdfMessageRecycle(message); + } +} + diff --git a/utils/src/osal_msg_queue.c b/utils/src/osal_msg_queue.c new file mode 100644 index 00000000..46445455 --- /dev/null +++ b/utils/src/osal_msg_queue.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "osal_msg_queue.h" +#include "osal_message.h" +#include "osal_time.h" + +void OsalMessageQueueInit(struct HdfMessageQueue *queue) +{ + if (queue != NULL) { + OsalMutexInit(&queue->mutex); + OsalSemInit(&queue->semaphore, 0); + HdfSListInit(&queue->list); + } +} + +void OsalMessageQueueDestroy(struct HdfMessageQueue *queue) +{ + if (queue != NULL) { + OsalMutexDestroy(&queue->mutex); + OsalSemDestroy(&queue->semaphore); + HdfSListFlush(&queue->list, HdfMessageDelete); + } +} + +void HdfMessageQueueEnqueue( + struct HdfMessageQueue *queue, struct HdfMessage *message, long delayed) +{ + if (queue == NULL || message == NULL) { + return; + } + + struct HdfSListIterator it; + (void)delayed; + message->timeStamp += OsalGetSysTimeMs(); + OsalMutexLock(&queue->mutex); + HdfSListIteratorInit(&it, &queue->list); + while (HdfSListIteratorHasNext(&it)) { + struct HdfMessage *next = (struct HdfMessage *)HdfSListIteratorNext(&it); + if (next->timeStamp > message->timeStamp) { + HdfSListIteratorInsert(&it, &message->entry); + goto complete; + } + } + + HdfSListAddTail(&queue->list, &message->entry); +complete: + OsalMutexUnlock(&queue->mutex); + OsalSemPost(&queue->semaphore); +} + +struct HdfMessage* HdfMessageQueueNext(struct HdfMessageQueue *queue) +{ + struct HdfSListIterator it; + struct HdfMessage *message = NULL; + uint64_t currentTime = OsalGetSysTimeMs(); + long miniTimeoutMs = OSAL_WAIT_FOREVER; + OsalMutexLock(&queue->mutex); + HdfSListIteratorInit(&it, &queue->list); + while (HdfSListIteratorHasNext(&it)) { + message = (struct HdfMessage *)HdfSListIteratorNext(&it); + if (message->timeStamp <= currentTime) { + HdfSListIteratorRemove(&it); + OsalMutexUnlock(&queue->mutex); + return message; + } + } + + OsalMutexUnlock(&queue->mutex); + OsalSemWait(&queue->semaphore, miniTimeoutMs); + return NULL; +} + +void HdfMessageQueueFlush(struct HdfMessageQueue *queue) +{ + struct HdfSListIterator it; + OsalMutexLock(&queue->mutex); + HdfSListIteratorInit(&it, &queue->list); + while (HdfSListIteratorHasNext(&it)) { + struct HdfMessage *msgNode = (struct HdfMessage *)HdfSListIteratorNext(&it); + HdfSListIteratorRemove(&it); + HdfMessageRecycle(msgNode); + } + OsalMutexUnlock(&queue->mutex); +} +