diff --git a/.gitee/ISSUE_TEMPLATE.zh-CN.md b/.gitee/ISSUE_TEMPLATE.zh-CN.md deleted file mode 100755 index f09d98dd..00000000 --- a/.gitee/ISSUE_TEMPLATE.zh-CN.md +++ /dev/null @@ -1,13 +0,0 @@ -### 该问题是怎么引起的? - - - -### 重现步骤 - - - -### 报错信息 - - - - diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md deleted file mode 100755 index 33948fdc..00000000 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ /dev/null @@ -1,15 +0,0 @@ -### 相关的Issue - - -### 原因(目的、解决的问题等) - - -### 描述(做了什么,变更了什么) - - -### 测试用例(新增、改动、可能影响的功能) - - - - - diff --git a/LICENSE b/LICENSE index 61fa69e3..f60fb811 100644 --- a/LICENSE +++ b/LICENSE @@ -1,28 +1,51 @@ -Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. -Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of - conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list - of conditions and the following disclaimer in the documentation and/or other materials - provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +HDF - Hardware Driver Foundation +Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + +HDF is dual licensed: you can use it either under the terms of +the GPL V2, or the BSD3 license, at your option. +a) GNU General Public License version 2, (https://opensource.org/licenses/GPL-2.0) +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public +License along with this library; if not, write to the Free +Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +MA 02110-1301 USA + +Alternatively, +b) The BSD3 License, (https://opensource.org/licenses/BSD-3-Clause) +Redistribution and use in source and binary forms, with or +without modification, are permitted provided that the following +conditions are met: + +1. Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. +2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..b18541f3 --- /dev/null +++ b/README.md @@ -0,0 +1,164 @@ +# HDF + +- [Introduction](#section11660541593) +- [Directory Structure](#section161941989596) +- [Usage](#section1312121216216) + - [HDF](#section129654513264) + - [Sensor](#section188637474417) + - [Display](#section161502341317) + - [Input](#section12629164020115) + - [WLAN](#section11408103183114) + +- [Repositories Involved](#section1371113476307) + +## Introduction + +This repository stores the core source code information of the OpenHarmony driver subsystem, including the driver framework, configuration management, configuration parsing, universal framework model, and unified hardware driver interfaces. It is designed to provide a more precise and efficient development environment, where you can perform one-time development for multi-system deployment. + +**Figure 1** Architecture of the HDF +![](figures/architecture-of-the-hdf.png) + +## Directory Structure + +``` +/drivers/framework +├── ability # Capabilities for the driver development, such as the message model libraries +│ ├── config # Parsing code of the configuration +│ └── sbuf # Data serialization code +├── core # Core code for implementing the HDF +│ ├── adapter # Kernel adaptation layer +│ ├── common # Common basic code +│ ├── host # Driver host environment module +│ ├── manager # Management module +│ └── shared # Code shared by the host and manager modules +├── include # Header files for the HDF to provide capabilities externally +│ ├── config # Header files declaring capabilities for parsing configuration +│ ├── core # Header files exposed externally +│ ├── net # Header files related to network operations +│ ├── osal # Header files of the OS adaptation layer +│ ├── platform # Header files declaring platform APIs +│ ├── utils # Header files declaring common capabilities +│ └── wifi # Header files for the WLAN module to provide capabilities externally +├── model # Universal framework module for drivers +│ ├── display # Display framework module +│ ├── input # Input framework module +│ ├── network # WLAN framework module +│ └── sensor # Sensor driver module +├── support # Basic capabilities +│ └── platform # Platform driver framework and APIs, including GPIO, I2C, and SPI +├── tools # Source code related to the tools of the HDF +│ └── hc-gen # Source code of the configuration management tool +└── utils # Basic data structures and algorithms +``` + +## Usage + +### HDF + +To develop a driver based on the HDF, you only need to register and configure required APIs. The driver framework will load and initialize the driver based on the parsing content. + +Driver development based on the HDF consists of the following three parts: + +- Driver: Develop the functions. + +- Information configuration: Present the loading information of the driver. + +- Resource configuration: Configure the hardware information of the driver. + +You need to complete the logic code for the functions of a driver by the following APIs. + +The first part that catches your eyes is the driver entry, which is described through **DriverEntry**. + +Three APIs are available, namely **Bind**, **Init**, and **Release**. + +``` +struct HdfDriverEntry g_deviceSample = { + .moduleVersion = 1, + .moduleName = "sample_driver", + .Bind = SampleDriverBind, + .Init = SampleDriverInit, + .Release = SampleDriverRelease, +}; +``` + +**Bind**: This API is used to bind driver devices and its functions. + +``` +int32_t SampleDriverBind(struct HdfDeviceObject *deviceObject) +{ + // TODO: Bind device service to device object. + // And you can also initialize device resources here. + return HDF_SUCCESS; +} +``` + +**Init**: When devices are successfully bound, the HDF calls **Init** to initialize the driver. After initialization is complete, the HDF will determine whether to create external service interfaces based on the configuration file. If the driver fails to be initialized, the driver framework will automatically release the created device interface. + +``` +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + // TODO: Init hardware or other resources here. + return HDF_S UCCESS; +} +``` + +**Release**: When you need to uninstall a driver, the HDF calls this function to release the driver resources. Then, other internal resources will be released. + +``` +void SampleDriverRelease(struct HdfDeviceObject *deviceObject) +{ + // Release all resources. + return; +} +``` + +For details, see [HDF Overview](en-us_topic_0000001051611604.md). + +### Sensor + +The sensor driver module is developed based on the HDF and supports functions such as cross-OS migration and differentiated device configuration. + +- APIs for implementing sensor driver module capabilities: Implement the capabilities of registering, loading, and deregistering sensor drivers as well as detecting sensor device depending on the HDF, normalize APIs for sensor devices of the same type, and offer APIs for parsing register configurations, abstract APIs for bus access, and abstract platform APIs. +- APIs to be implemented by developers: Based on the HDF Configuration Source \(HCS\), implement differentiated configuration for sensors of the same type and serialized configuration of sensor device parameters, and offer APIs for some sensor device operations to simplify the sensor driver development. + +For details, see [Sensor Driver Overview](en-us_topic_0000001078401780.md). + +### Display + +The display driver model that is developed based on the HDF shields the differences among chip platforms, achieving cross-platform migration of the OS. It also abstracts the common service logic of peripherals and configures differentiated adaptation APIs so that a driver model can be compatible with different peripheral. In this way, third-party vendors can efficiently access the OpenHarmony driver ecosystem. + +- APIs for implementing display driver module capabilities: Implement the Hardware Driver Interfaces \(HDIs\) and their adaptation with the chip platform. In addition, the kernel-mode driver abstracts the common services of the panel driver and provides capabilities of initializing the panel, obtaining the panel configuration, powering on/off the panel, and implementing the backlight control. +- APIs to be implemented by developers: Complete the board-level HCS configuration and private data configuration of the panel, or offer differentiated APIs for some components to ensure efficient development of the display driver. + +For details, see [LCD Overview](en-us_topic_0000001052857284.md). + +### Input + +The input driver model is developed based on the HDF, provides unified driver APIs for upper-layer input services, and is decoupled from the chip platform. In addition, it abstracts several types of common platform drivers based on different input devices and is compatible with those input devices through configuration and differentiated peripheral APIs. + +- APIs for implementing input driver module capabilities: Implement the HDIs and provide capabilities of managing devices, controlling services, and reporting data. Besides, the input driver model provides a unified driver for different input devices and the capabilities of registering/unregistering an input device, reporting event data, parsing configuration, and loading a common driver. +- APIs to be implemented by developers: Based on the provided platform driver, add the device descriptions as well as private configuration of the input device and implement differentiated APIs to greatly shorten the time required for developing input drivers. + +For details, see [Touchscreen Overview](en-us_topic_0000001052857350.md). + +### WLAN + +The WLAN module is developed based on the HDF and supports cross-OS migration, component adaptation, and modular assembly and compilation. Based on the unified APIs provided by the WLAN module, driver developers of WLAN vendors can adapt their driver code and developers of the HarmonyOS Driver Interfaces \(HDIs\) are capable of creating, disabling, scanning, and connecting to WLAN hotspots. + +- APIs for implementing WLAN driver module capabilities: Implement the APIs of the WLAN HDI layer and provide capabilities of setting/obtaining the MAC address, obtaining the feature type, and setting the transmit power for upper-layer input services, as well as the capabilities of creating/releasing a **WifiModule**, connecting to/disconnecting from a WLAN hotspot, and applying for/releasing a **NetBuf** for developers. +- APIs to be implemented by developers: Based on the provided platform driver, complete the board-level HCS configuration as well as the differentiated WLAN configuration, and offer APIs for initializing, deregistering, enabling, and disabling a network device. + +For details, see [WLAN Overview](en-us_topic_0000001051643558.md). + +## Repositories Involved + +Driver subsystem + +hmf/drivers/framework + +hmf/drivers/adapter\_uhdf + +hmf/drivers/adapter\_khdf\_linux + +hmf/drivers/adapter\_khdf\_liteos + diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 00000000..901f5eca --- /dev/null +++ b/README_zh.md @@ -0,0 +1,168 @@ +# Hdf Framework + +- [简介](#section11660541593) +- [目录](#section161941989596) +- [说明](#section1312121216216) + - [驱动框架使用说明](#section129654513264) + - [Sensor框架模型说明](#section188637474417) + - [Display框架模型说明](#section161502341317) + - [Input框架模型说明](#section12629164020115) + - [WLAN框架模型说明](#section11408103183114) + +- [相关仓](#section1371113476307) + +## 简介 + +该仓主要存放OpenHarmony驱动子系统核心源码信息(包括驱动框架、配置管理、配置解析、驱动通用框架模型、硬件通用平台能力接口等),旨在为开发者提供更精准、更高效的开发环境,力求做到一次开发,多系统部署。 + +**图 1** 驱动框架的架构图 +![](figures/architecture-of-the-hdf.png) + +## 目录 + +``` +/drivers/framework +├── ability #提供驱动开发的能力支持,如消息模型库等 +│ ├── config #配置解析代码 +│ └── sbuf #数据序列化代码 +├── core #实现驱动框架的核心代码 +│ ├── adapter #实现对内核操作接口适配,提供抽象化的接口供开发者使用 +│ ├── common #驱动框架公共基础代码 +│ ├── host #驱动宿主环境模块 +│ ├── manager #驱动框架管理模块 +│ └── shared #host和manager共享模块代码 +├── include #驱动框架对外提供能力的头文件 +│ ├── config #提供配置解析能力的头文件 +│ ├── core #驱动框架对外提供的头文件 +│ ├── net #网络数据操作相关的头文件 +│ ├── osal #系统适配相关接口的头文件 +│ ├── platform #平台设备相关接口的头文件 +│ ├── utils #驱动框架公共能力的头文件 +│ └── wifi #WLAN对外提供能力的头文件 +├── model #提供驱动通用框架模型 +│ ├── display #显示框架模型 +│ ├── input #输入框架模型 +│ ├── network #WLAN框架模型 +│ └── sensor #Sensor驱动模型 +├── support #提系统的基础能力 +│ └── platform #平台设备驱动框架及访问接口,范围包括GPIO、I2C、SPI等 +├── tools #hdf框架工具相关的源码 +│ └── hc-gen #配置管理工具源码 +└── utils #提供基础数据结构和算法等 +``` + +## 说明 + +### 驱动框架使用说明 + +基于HDF(驱动框架)开发驱动,用户只需注册自己所需的接口和配置,然后驱动框架就会解析配置的内容,完成驱动加载和初始化动作。 + +开发者基于HDF驱动框架开发的驱动主要包含三大部分: + +1、驱动程序部分----完成驱动的功能逻辑。 + +2、驱动配置信息----指示驱动的加载信息内容。 + +3、驱动资源配置----配置驱动的硬件配置信息。 + +驱动程序主要是完成驱动功能的逻辑代码: + +对于开发者首先看到的是驱动入口部分,驱动入口部分通过DriverEntry进行描述。 + +其中主要包含Bind, Init 和Release三个接口。 + +``` +struct HdfDriverEntry g_deviceSample = { + .moduleVersion = 1, + .moduleName = "sample_driver", + .Bind = SampleDriverBind, + .Init = SampleDriverInit, + .Release = SampleDriverRelease, +}; +``` + +Bind接口描述:该接口的作用主要是完成驱动设备和设备服务接口的bind动作。 + +``` +int32_t SampleDriverBind(struct HdfDeviceObject *deviceObject) +{ + // TODO: Bind device service to device object. + // And you can also initialize device resources here. + return HDF_SUCCESS; +} +``` + +Init接口描述:当框架完成设备绑定动作后,就开始调用驱动初始化接口,当初始化成功后,驱动框架根据配置文件决定是否对外创建设备服务接口,还是只是对当前服务接口可见。如果Init初始化失败的话,驱动框架就会主动释放创建的设备接口等信息。 + +``` +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + // TODO: Init hardware or other resources here. + return HDF_S UCCESS; +} +``` + +Release接口描述:当用户需要卸载驱动时,驱动框架先通过该接口通知驱动程序释放资源。然后在执行其他内部资源释放。 + +``` +void SampleDriverRelease(struct HdfDeviceObject *deviceObject) +{ + // Release all resources. + return; +} +``` + +HDF驱动框架详细开发请参考[驱动开发指南](zh-cn_topic_0000001051611604.md)。 + +### Sensor框架模型说明 + +基于HDF(**H**ardware **D**river **F**oundation)驱动框架开发的Sensor驱动模型,实现跨操作系统迁移,器件差异配置等功能,具体包括下面两部分: + +- Sensor驱动模型基础能力部分:依赖HDF驱动框架实现Sensor器件驱动的注册,加载,去注册,器件探测等能力,提供同一类型Sensor器件驱动归一接口, 寄存器配置解析操作接口,总线访问抽象接口,平台抽象接口。 +- 开发者实现的部分:依赖HDF驱动框架的HCS\(**H**DF **C**onfiguration **S**ource\)配置管理,根据同类型Sensor差异化配置,实现Sensor器件参数序列化配置和器件部分操作接口,简化Sensor器件驱动开发。 + +基于Sensor驱动模型开发Sensor器件驱动请参考[Sensor驱动开发指南](zh-cn_topic_0000001078401780.md)。 + +### Display框架模型说明 + +基于OpenHarmony驱动框架的Display驱动模型,对上屏蔽了芯片平台差异,方便操作系统跨平台迁移;向下抽象外设驱动公共业务逻辑,通过配置或差异化适配接口,实现一套驱动模型可兼容不同的外设器件,使得三方厂商可以高效、便捷的切入鸿蒙驱动生态。 + +- Display驱动模型基础能力部分:包括HDI(**H**ardware **D**river **I**nterfaces)接口的定义及其实现框架,以及芯片平台对HDI接口的适配实现;内核驱动部分抽象了Panel驱动的公共业务,提供基础的Panel初始化、器件配置信息获取、上下电、背光设置等公共流程。 +- 驱动开发者实现的部分:需要完成板级的HCS配置及Panel私有数据配置,或者实现部分器件差异化接口,保证显示屏驱动开发高效便捷。 + +基于Display驱动模型开发LCD器件驱动请参考[LCD驱动开发指南](zh-cn_topic_0000001052857284.md)。 + +### Input框架模型说明 + +基于OpenHarmony驱动框架的Input驱动模型,不依赖于芯片平台,对上层输入服务提供统一的驱动接口;在具体的驱动模型实现中,针对不同类别的输入设备,抽象出几类公共的平台驱动,通过配置及差异化的适配接口,使得驱动模型可兼容不同的输入设备。 + +- Input驱动模型基础能力部分:包括Input HDI层的接口定义及公共实现,对上层输入服务提供设备管理、业务控制、数据上报等驱动能力接口;而Input驱动模型提供不同类型Input设备的归一化驱动, 包括输入设备的注册和注销、event数据的上报通道、配置信息的解析、公共驱动的加载等能力。 +- 开发者实现的部分:根据驱动模型提供的平台驱动,需要完成设备描述配置及器件私有配置,以及实现预留的器件差异化接口,借由此驱动模型,可大幅缩减Input设备驱动的开发周期。 + +基于Input驱动模型开发Touchscreen器件驱动请参考[Touchscreen驱动开发指南](zh-cn_topic_0000001052857350.md)。 + +### WLAN框架模型说明 + +基于OpenHarmony驱动框架的WLAN驱动模型,可实现跨操作系统迁移,自适应器件差异,模块化拼装编译等功能。各WLAN厂商驱动开发人员可根据WLAN模块提供的向下统一接口适配各自的驱动代码,HDI层开发人员可根据WLAN模块提供的向上统一接口获取如下能力:建立/关闭WLAN热点、扫描、关联WLAN热点等。 + +- WLAN驱动模型基础能力部分:包括WLAN HDI层的接口定义及公共实现,对上层输入服务提供如设置MAC地址,获取设备的MAC地址,获取特性的类型,设置发射功率等能力;对驱动开发者提供创建/释放WifiModule,关联/取消关联,申请/释放NetBuf等能力。 +- 驱动开发者实现的部分:根据驱动模型提供的平台驱动,需要完成板级的HCS配置及WLAN芯片的私有配置,以及实现预留的初始化/注销网络设备、打开/关闭网络设备等相关接口。 + +基于WLAN驱动模型开发WLAN器件驱动请参考[WLAN驱动开发指南](zh-cn_topic_0000001051643558.md)。 + +## 相关仓 + +驱动子系统 + +hmf/drivers/framework + +hmf/drivers/adapter\_uhdf + +hmf/drivers/adapter\_khdf\_linux + +hmf/drivers/adapter\_khdf\_liteos + + + +
+ diff --git a/ability/config/device_resource_if.c b/ability/config/device_resource_if.c old mode 100755 new mode 100644 index 16863d67..6bea6afd --- a/ability/config/device_resource_if.c +++ b/ability/config/device_resource_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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" diff --git a/ability/config/hcs_parser/include/hcs_blob_if.h b/ability/config/hcs_parser/include/hcs_blob_if.h old mode 100755 new mode 100644 index c1f8547b..b50c8f35 --- a/ability/config/hcs_parser/include/hcs_blob_if.h +++ b/ability/config/hcs_parser/include/hcs_blob_if.h @@ -1,38 +1,14 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_BLOB_IF_H #define HCS_BLOB_IF_H -#include #include "hdf_base.h" #define CONFIG_NODE 0x1 diff --git a/ability/config/hcs_parser/include/hcs_generate_tree.h b/ability/config/hcs_parser/include/hcs_generate_tree.h old mode 100755 new mode 100644 index 59bfc3d8..2aa2c63e --- a/ability/config/hcs_parser/include/hcs_generate_tree.h +++ b/ability/config/hcs_parser/include/hcs_generate_tree.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_GENERATE_TREE_H diff --git a/ability/config/hcs_parser/include/hcs_parser.h b/ability/config/hcs_parser/include/hcs_parser.h old mode 100755 new mode 100644 index a58c60bc..216eecc3 --- a/ability/config/hcs_parser/include/hcs_parser.h +++ b/ability/config/hcs_parser/include/hcs_parser.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_PARSER_H diff --git a/ability/config/hcs_parser/include/hcs_tree_if.h b/ability/config/hcs_parser/include/hcs_tree_if.h old mode 100755 new mode 100644 index f4d9e096..b02bc332 --- a/ability/config/hcs_parser/include/hcs_tree_if.h +++ b/ability/config/hcs_parser/include/hcs_tree_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_TREE_IF_H diff --git a/ability/config/hcs_parser/src/hcs_blob_if.c b/ability/config/hcs_parser/src/hcs_blob_if.c old mode 100755 new mode 100644 index 22db6fca..1f007c6f --- a/ability/config/hcs_parser/src/hcs_blob_if.c +++ b/ability/config/hcs_parser/src/hcs_blob_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_blob_if.h" @@ -72,8 +49,12 @@ static int32_t HcsGetArrayLength(const char *start) { int32_t arrayLen = HCS_PREFIX_LENGTH + HCS_WORD_LENGTH; uint16_t count; - (void)HcsSwapToUint16(&count, start + HCS_PREFIX_LENGTH, CONFIG_WORD); - for (uint16_t i = 0; i < count; i++) { + uint16_t i; + if (!HcsSwapToUint16(&count, start + HCS_PREFIX_LENGTH, CONFIG_WORD)) { + HDF_LOGE("%s failed", __func__); + return HDF_FAILURE; + } + for (i = 0; i < count; i++) { int32_t lenData = HcsGetDataTypeOffset(start + arrayLen); if (lenData < 0) { return HDF_FAILURE; @@ -189,7 +170,7 @@ bool HcsSwapToUint64(uint64_t *value, const char *realValue, uint32_t type) return false; } -static bool CheckHcsBlobLength(const char *start, uint32_t length, struct HbcHeader *header) +static bool CheckHcsBlobLength(uint32_t length, struct HbcHeader *header) { uint32_t rootNodeLen = HCS_STRING_LENGTH(HBC_ROOT_NAME) + HCS_PREFIX_LENGTH + HCS_DWORD_LENGTH; uint32_t minLength = rootNodeLen + HBC_HEADER_LENGTH; @@ -223,7 +204,7 @@ bool HcsCheckBlobFormat(const char *start, uint32_t length) HDF_LOGE("%s failed, the magic of HBC is %x", __func__, header->magicNumber); return false; } - if (!CheckHcsBlobLength(start, length, header)) { + if (!CheckHcsBlobLength(length, header)) { return false; } return true; diff --git a/ability/config/hcs_parser/src/hcs_generate_tree.c b/ability/config/hcs_parser/src/hcs_generate_tree.c old mode 100755 new mode 100644 index 94083057..cd638683 --- a/ability/config/hcs_parser/src/hcs_generate_tree.c +++ b/ability/config/hcs_parser/src/hcs_generate_tree.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_generate_tree.h" diff --git a/ability/config/hcs_parser/src/hcs_parser.c b/ability/config/hcs_parser/src/hcs_parser.c old mode 100755 new mode 100644 index 65cbe951..50ef7643 --- a/ability/config/hcs_parser/src/hcs_parser.c +++ b/ability/config/hcs_parser/src/hcs_parser.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_parser.h" diff --git a/ability/config/hcs_parser/src/hcs_tree_if.c b/ability/config/hcs_parser/src/hcs_tree_if.c old mode 100755 new mode 100644 index dd0079f8..d4aba7c6 --- a/ability/config/hcs_parser/src/hcs_tree_if.c +++ b/ability/config/hcs_parser/src/hcs_tree_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_tree_if.h" @@ -51,13 +28,13 @@ static struct DeviceResourceAttr *GetAttrInNode(const struct DeviceResourceNode bool HcsGetBool(const struct DeviceResourceNode *node, const char *attrName) { + uint8_t value; struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); if ((attr == NULL) || (attr->value == NULL)) { HDF_LOGE("%s failed, the node or attrName is NULL", __func__); return false; } - uint8_t value; if (!HcsSwapToUint8(&value, attr->value + HCS_PREFIX_LENGTH, HcsGetPrefix(attr->value))) { HDF_LOGE("%s failed, Incorrect prefix code", __func__); return false; @@ -132,6 +109,7 @@ static const char *GetArrayElem(const struct DeviceResourceAttr *attr, uint32_t { int32_t offset = HCS_WORD_LENGTH + HCS_PREFIX_LENGTH; uint16_t count; + uint32_t i; if ((HcsGetPrefix(attr->value) != CONFIG_ARRAY) || !HcsSwapToUint16(&count, attr->value + HCS_PREFIX_LENGTH, CONFIG_WORD)) { HDF_LOGE("%s failed, the attr of %s is not array", __func__, attr->name); @@ -141,7 +119,7 @@ static const char *GetArrayElem(const struct DeviceResourceAttr *attr, uint32_t HDF_LOGE("%s failed, the index: %u >= count: %u", __func__, index, count); return NULL; } - for (uint32_t i = 0; i < index; i++) { + for (i = 0; i < index; i++) { int32_t result = HcsGetDataTypeOffset(attr->value + offset); if (result < 0) { return NULL; @@ -245,13 +223,14 @@ int32_t HcsGetUint64ArrayElem(const struct DeviceResourceNode *node, const char int32_t HcsGetUint8Array(const struct DeviceResourceNode *node, const char *attrName, uint8_t *value, uint32_t len, uint8_t def) { + int32_t ret = HDF_SUCCESS; + uint32_t i; if ((value == NULL) || (len == 0)) { HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); return HDF_FAILURE; } - int32_t ret = HDF_SUCCESS; - for (uint32_t i = 0; i < len; i++) { + for (i = 0; i < len; i++) { int32_t result = HcsGetUint8ArrayElem(node, attrName, i, value + i, def); // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); @@ -262,13 +241,14 @@ int32_t HcsGetUint8Array(const struct DeviceResourceNode *node, const char *attr int32_t HcsGetUint16Array(const struct DeviceResourceNode *node, const char *attrName, uint16_t *value, uint32_t len, uint16_t def) { + int32_t ret = HDF_SUCCESS; + uint32_t i; if ((value == NULL) || (len == 0)) { HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); return HDF_FAILURE; } - int32_t ret = HDF_SUCCESS; - for (uint32_t i = 0; i < len; i++) { + for (i = 0; i < len; i++) { int32_t result = HcsGetUint16ArrayElem(node, attrName, i, value + i, def); // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); @@ -279,13 +259,14 @@ int32_t HcsGetUint16Array(const struct DeviceResourceNode *node, const char *att int32_t HcsGetUint32Array(const struct DeviceResourceNode *node, const char *attrName, uint32_t *value, uint32_t len, uint32_t def) { + int32_t ret = HDF_SUCCESS; + uint32_t i; if ((value == NULL) || (len == 0)) { HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); return HDF_FAILURE; } - int32_t ret = HDF_SUCCESS; - for (uint32_t i = 0; i < len; i++) { + for (i = 0; i < len; i++) { int32_t result = HcsGetUint32ArrayElem(node, attrName, i, value + i, def); // If the error type is HDF_ERR_INVALID_OBJECT, the error is recorded and returned after the loop exits. CONTINUE_RETURN_DIFFERENT_ERRNO(ret, result); @@ -296,12 +277,13 @@ int32_t HcsGetUint32Array(const struct DeviceResourceNode *node, const char *att int32_t HcsGetUint64Array(const struct DeviceResourceNode *node, const char *attrName, uint64_t *value, uint32_t len, uint64_t def) { + uint32_t i; if ((value == NULL) || (len == 0)) { HDF_LOGE("%s failed, parameter error, len: %u", __func__, len); return HDF_FAILURE; } - for (uint32_t i = 0; i < len; i++) { + for (i = 0; i < len; i++) { int32_t result = HcsGetUint64ArrayElem(node, attrName, i, value + i, def); if (result != HDF_SUCCESS) { HDF_LOGE("%s failed, the ret is %d", __func__, result); @@ -314,10 +296,11 @@ int32_t HcsGetUint64Array(const struct DeviceResourceNode *node, const char *att int32_t HcsGetStringArrayElem(const struct DeviceResourceNode *node, const char *attrName, uint32_t index, const char **value, const char *def) { + const char *realValue = NULL; struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); RETURN_DEFAULT_VALUE(attr, attrName, value, def); - const char *realValue = GetArrayElem(attr, index); + realValue = GetArrayElem(attr, index); if ((realValue == NULL) || (HcsGetPrefix(realValue) != CONFIG_STRING)) { *value = def; HDF_LOGE("%s failed, %s attr is default value", __func__, attrName); @@ -342,13 +325,13 @@ int32_t HcsGetString(const struct DeviceResourceNode *node, const char *attrName int32_t HcsGetElemNum(const struct DeviceResourceNode *node, const char *attrName) { + uint16_t num; struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); if ((attr == NULL) || (attr->value == NULL) || (HcsGetPrefix(attr->value) != CONFIG_ARRAY)) { HDF_LOGE("%s failed, %s attr error", __func__, (attrName == NULL) ? "error attrName" : attrName); return HDF_FAILURE; } - uint16_t num; (void)HcsSwapToUint16(&num, attr->value + HCS_PREFIX_LENGTH, CONFIG_WORD); return num; } @@ -380,12 +363,13 @@ static const struct DeviceResourceNode *TraverseTreeNode(const struct DeviceReso const struct DeviceResourceNode *HcsGetNodeByMatchAttr(const struct DeviceResourceNode *node, const char *attrValue) { + 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__); return NULL; } - const struct DeviceResourceNode *curNode = (node != NULL) ? node : instance->GetRootNode(); + curNode = (node != NULL) ? node : instance->GetRootNode(); while (curNode != NULL) { if (GetAttrValueInNode(curNode, attrValue) != NULL) { break; @@ -397,12 +381,12 @@ const struct DeviceResourceNode *HcsGetNodeByMatchAttr(const struct DeviceResour const struct DeviceResourceNode *HcsGetChildNode(const struct DeviceResourceNode *node, const char *nodeName) { + struct DeviceResourceNode *child = NULL; if ((node == NULL) || (nodeName == NULL)) { HDF_LOGE("%s failed, the node or nodeName is NULL", __func__); return NULL; } - struct DeviceResourceNode *child = NULL; for (child = node->child; child != NULL; child = child->sibling) { if ((child->name != NULL) && (strcmp(nodeName, child->name) == 0)) { break; @@ -413,20 +397,22 @@ const struct DeviceResourceNode *HcsGetChildNode(const struct DeviceResourceNode const struct DeviceResourceNode *HcsGetNodeByRefAttr(const struct DeviceResourceNode *node, const char *attrName) { + uint32_t attrValue; + struct DeviceResourceIface *instance = NULL; + const struct DeviceResourceNode *curNode = NULL; struct DeviceResourceAttr *attr = GetAttrInNode(node, attrName); if ((attr == NULL) || (attr->value == NULL) || (HcsGetPrefix(attr->value) != CONFIG_REFERENCE)) { HDF_LOGE("%s failed, %s attr error", __func__, (attrName == NULL) ? "error attrName" : attrName); return NULL; } - uint32_t attrValue; (void)HcsSwapToUint32(&attrValue, attr->value + HCS_PREFIX_LENGTH, CONFIG_DWORD); - struct DeviceResourceIface *instance = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + instance = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); if ((instance == NULL) || (instance->GetRootNode == NULL)) { HDF_LOGE("%s failed, DeviceResourceGetIfaceInstance error", __func__); return NULL; } - const struct DeviceResourceNode *curNode = instance->GetRootNode(); + curNode = instance->GetRootNode(); while (curNode != NULL) { if (curNode->hashValue == attrValue) { break; diff --git a/ability/config/test/unittest/common/hdf_config_test.cpp b/ability/config/test/unittest/common/hdf_config_test.cpp new file mode 100644 index 00000000..2f4f9c32 --- /dev/null +++ b/ability/config/test/unittest/common/hdf_config_test.cpp @@ -0,0 +1,592 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +namespace ConfigTest { +const int8_t HDF_MSG_RESUL_DEFALUT = 3; + +// hcs config test case number +enum HdfTestCaseCmd { + HDF_CREATE_DM_HSL_TO_TREE_001, + HDF_GET_NODE_BY_ATTR_VALUE_001, + HDF_GET_NODE_BY_ATTR_VALUE_002, + HDF_GET_BOOL_ATTR_VALUE_001, + HDF_GET_BOOL_ATTR_VALUE_002, + HDF_GET_UINT8_ATTR_VALUE_001, + HDF_GET_UINT8_ATTR_VALUE_002, + HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT16_ATTR_VALUE_001, + HDF_GET_UINT16_ATTR_VALUE_002, + HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT32_ATTR_VALUE_001, + HDF_GET_UINT32_ATTR_VALUE_002, + HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT64_ATTR_VALUE_001, + HDF_GET_UINT64_ATTR_VALUE_002, + HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, + HDF_GET_ELEM_NUM_VALUE_001, + HDF_GET_ELEM_NUM_VALUE_002, + HDF_GET_CHILD_NODE_001, + HDF_GET_CHILD_NODE_002, + HDF_TRAVERSE_ATTR_IN_NODE_001, + HDF_TRAVERSE_ATTR_IN_NODE_002, + HDF_GET_STRING_ATTR_VALUE_001, + HDF_GET_STRING_ATTR_VALUE_002, + HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_NODE_BY_ATTR_REF_001, + HDF_GET_NODE_BY_ATTR_REF_002, +}; + +class HdfConfigTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfConfigTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfConfigTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfConfigTest::SetUp() +{ +} + +void HdfConfigTest::TearDown() +{ +} + +/** + * @tc.name: HslTestCreateDMHslToTree001 + * @tc.desc: Create a config tree, enter config test + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestCreateDMHslToTree001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_CREATE_DM_HSL_TO_TREE_001, HDF_MSG_RESUL_DEFALUT}; + printf("HdfConfigTest enter\n\r"); + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetNodeByMatchAttrSuccess001 + * @tc.desc: Obtains the root node of the configuration tree + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetNodeByMatchAttrFail001 + * @tc.desc: Failed to obtain the root node of the configuration tree + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetNodeByMatchAttrFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetBoolAttrValueSuccess001 + * @tc.desc: Obtains the value of a BOOL attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetBoolAttrValueFail001 + * @tc.desc: Failed to obtain the value of a BOOL attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetBoolAttrValueFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_BOOL_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8AttrValueSuccess001 + * @tc.desc: Obtains the value of a Uint8 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8AttrValueFail001 + * @tc.desc: Failed to obtain the value of a Uint8 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8AttrValueFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8ArrayElemSuccess001 + * @tc.desc: Obtains the value of a Unit8 array attribute numbered of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8ArrayElemFail001 + * @tc.desc: Failed to obtain the value of a Unit8 array attribute numbered of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayElemFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8ArraySuccess001 + * @tc.desc: Obtains the values of a Uint8 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8ArraySuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint8ArrayFail001 + * @tc.desc: Failed to obtain the values of a Uint8 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint8ArrayFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16AttrValueSuccess001 + * @tc.desc: Obtains the value of a Uint16 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16AttrValueFail001 + * @tc.desc: Failed to obtain the value of a Uint16 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16AttrValueFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16ArrayElemSuccess001 + * @tc.desc: Obtains the value of a Uint16 array attribute numbered index of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16ArrayElemFail001 + * @tc.desc: Failed to obtain the value of a Uint16 array attribute numbered index of a + * configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayElemFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16ArraySuccess001 + * @tc.desc: Obtains the values of a Uint16 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16ArraySuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint16ArrayFail001 + * @tc.desc: Failed to obtain the values of a Uint16 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint16ArrayFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32AttrValueSuccess001 + * @tc.desc: Obtains the value of a Uint32 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32AttrValueFail001 + * @tc.desc: Failed to obtain the value of a Uint32 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32AttrValueFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32ArrayElemSuccess001 + * @tc.desc: Obtains the value of a Uint32 array attribute numbered index of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32ArrayElemFail001 + * @tc.desc: Failed to obtain the value of a Uint32 array attribute numbered index of a + * configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayElemFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32ArraySuccess001 + * @tc.desc: Obtains the values of a Uint32 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32ArraySuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint32ArrayFail001 + * @tc.desc: Failed to obtain the values of a Uint32 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint32ArrayFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64AttrValueSuccess001 + * @tc.desc: Obtains the value of a Uint64 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64AttrValueFail001 + * @tc.desc: Failed to obtain the value of a Uint64 attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64AttrValueFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64ArrayElemSuccess001 + * @tc.desc: Obtains the value of a Uint64 array attribute numbered index of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64ArrayElemFail001 + * @tc.desc: Failed to obtain the value of a Uint64 array attribute numbered index of a + * configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayElemFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64ArraySuccess001 + * @tc.desc: Obtains the values of a Uint64 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64ArraySuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetUint64ArrayFail001 + * @tc.desc: Failed to obtain the values of a Uint64 array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetUint64ArrayFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetElemNumSuccess001 + * @tc.desc: Obtains the number of values for an array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetElemNumSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetElemNumFail001 + * @tc.desc: Failed to obtain the number of values for an array attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetElemNumFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_ELEM_NUM_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetChildNodeSuccess001 + * @tc.desc: Obtains the child node with a specified node name from a parent node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetChildNodeSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetChildNodeFail001 + * @tc.desc: Failed to obtain the child node with a specified node name from a parent node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetChildNodeFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_CHILD_NODE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestTraverseAttrInNodeSuccess001 + * @tc.desc: Traverses the attributes of the current configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestTraverseAttrInNodeFail001 + * @tc.desc: Failed to traverse the attributes of the current configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestTraverseAttrInNodeFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_TRAVERSE_ATTR_IN_NODE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetStringSuccess001 + * @tc.desc: Obtains the value of a String attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetStringSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetStringFail001 + * @tc.desc: Failed to obtain the value of a String attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetStringFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetStringArrayElemSuccess001 + * @tc.desc: Obtains the value of a String array attribute numbered index of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetStringArrayElemFail001 + * @tc.desc: Failed to obtain the value of a String array attribute numbered index of a + * configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetStringArrayElemFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetNodeAttrRefSuccess001 + * @tc.desc: Obtains the node that is specified by a node-type attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefSuccess001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_001, HDF_MSG_RESUL_DEFALUT}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HslTestGetNodeAttrRefFail001 + * @tc.desc: Failed to obtain the node that is specified by a node-type attribute of a configuration tree node + * @tc.type: FUNC + * @tc.require: AR000DQ0TB + */ +HWTEST_F(HdfConfigTest, HslTestGetNodeAttrRefFail001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_CONFIG_TYPE, HDF_GET_NODE_BY_ATTR_REF_002, HDF_MSG_RESUL_DEFALUT}; + 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 old mode 100755 new mode 100644 index 80a56909..6fd3bd6c --- a/ability/sbuf/include/hdf_sbuf.h +++ b/ability/sbuf/include/hdf_sbuf.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup Core @@ -52,9 +29,7 @@ #ifndef HDF_SBUF_H #define HDF_SBUF_H -#include -#include -#include "hdf_cstring.h" +#include "hdf_base.h" #ifdef __cplusplus extern "C" { diff --git a/ability/sbuf/src/hdf_sbuf.c b/ability/sbuf/src/hdf_sbuf.c old mode 100755 new mode 100644 index 0c2e1c50..57b4944a --- a/ability/sbuf/src/hdf_sbuf.c +++ b/ability/sbuf/src/hdf_sbuf.c @@ -1,35 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "securec.h" #include "osal_mem.h" #include "hdf_log.h" #include "hdf_sbuf.h" @@ -38,6 +15,14 @@ #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 + static inline size_t HdfSbufGetAlignSize(size_t size) { return (size + HDF_SBUF_ALIGN - 1) & (~(HDF_SBUF_ALIGN - 1)); @@ -125,12 +110,14 @@ static bool HdfSbufGrow(struct HdfSBuf *sbuf, uint32_t growSize) return false; } - if (memcpy_s(newData, newSize, sbuf->data, sbuf->writePos) != EOK) { - OsalMemFree(newData); - return false; + if (sbuf->data != NULL) { + if (memcpy_s(newData, newSize, sbuf->data, sbuf->writePos) != EOK) { + OsalMemFree(newData); + return false; + } + OsalMemFree(sbuf->data); } - OsalMemFree(sbuf->data); sbuf->data = newData; sbuf->capacity = newSize; @@ -139,7 +126,7 @@ static bool HdfSbufGrow(struct HdfSBuf *sbuf, uint32_t growSize) static bool HdfSbufWrite(struct HdfSBuf *sbuf, const uint8_t *data, uint32_t size) { - if (sbuf == NULL || data == NULL) { + if (sbuf == NULL || sbuf->data == NULL || data == NULL) { return false; } @@ -174,7 +161,7 @@ static bool HdfSbufWrite(struct HdfSBuf *sbuf, const uint8_t *data, uint32_t siz static bool HdfSbufRead(struct HdfSBuf *sbuf, uint8_t *data, uint32_t readSize) { - if (sbuf == NULL || data == NULL) { + if (sbuf == NULL || sbuf->data == NULL || data == NULL) { return false; } @@ -216,10 +203,9 @@ bool HdfSbufWriteBuffer(struct HdfSBuf *sbuf, const void *data, uint32_t writeSi return true; } -/* return actual read size */ bool HdfSbufReadBuffer(struct HdfSBuf *sbuf, const void **data, uint32_t *readSize) { - if (sbuf == NULL || data == NULL || readSize == NULL) { + if (sbuf == NULL || sbuf->data == NULL || data == NULL || readSize == NULL) { HDF_LOGE("%s:input invalid", __func__); return false; } @@ -339,7 +325,7 @@ bool HdfSbufReadInt8(struct HdfSBuf *sbuf, int8_t *value) const char *HdfSbufReadString(struct HdfSBuf *sbuf) { - if (sbuf == NULL) { + if (sbuf == NULL || sbuf->data == NULL) { HDF_LOGE("%s:input null", __func__); return NULL; } @@ -393,6 +379,9 @@ struct HdfSBuf *HdfSBufObtain(size_t capacity) 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"); @@ -435,7 +424,7 @@ struct HdfSBuf *HdfSBufCopy(const struct HdfSBuf *sbuf) struct HdfSBuf *HdfSBufMove(struct HdfSBuf *sbuf) { - if (sbuf == NULL) { + if (sbuf == NULL || sbuf->isBind) { return NULL; } @@ -463,6 +452,7 @@ void HdfSbufTransDataOwnership(struct HdfSBuf *sbuf) sbuf->isBind = false; } + void HdfSBufRecycle(struct HdfSBuf *sbuf) { if (sbuf != NULL) { diff --git a/core/adapter/syscall/include/hdf_syscall_adapter.h b/core/adapter/syscall/include/hdf_syscall_adapter.h new file mode 100644 index 00000000..60de08bd --- /dev/null +++ b/core/adapter/syscall/include/hdf_syscall_adapter.h @@ -0,0 +1,60 @@ +/* + * 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_SYSCALL_ADAPTER_H +#define HDF_SYSCALL_ADAPTER_H + +#include +#include +#include +#include +#include +#include "hdf_io_service.h" + +struct HdfSyscallAdapter; + +enum HdfDevListenerThreadStatus { + LISTENER_UNINITED = 0, + LISTENER_INITED, + LISTENER_EXITED, + LISTENER_RUNNING, + LISTENER_WAITING, +}; + +struct HdfDevListenerThread { + struct OsalMutex mutex; + struct OsalThread thread; + struct DListHead *adapterListPtr; + struct HdfSyscallAdapter *adapter; + struct pollfd *pfds; + uint16_t pfdSize; + bool pollChanged; + struct DListHead *listenerListPtr; + bool shouldStop; + uint8_t status; +}; + +struct HdfSyscallAdapter { + struct HdfIoService super; + struct OsalMutex mutex; + struct DListHead listenerList; + int fd; + struct DListHead listNode; + struct HdfDevListenerThread *thread; + struct HdfSyscallAdapterGroup *group; +}; + +struct HdfSyscallAdapterGroup { + struct HdfIoServiceGroup serviceGroup; + struct OsalMutex mutex; + struct DListHead adapterList; + struct HdfDevListenerThread *thread; + struct DListHead listenerList; +}; + +#endif /* HDF_SYSCALL_ADAPTER_H */ diff --git a/core/adapter/syscall/src/hdf_devmgr_adapter.c b/core/adapter/syscall/src/hdf_devmgr_adapter.c new file mode 100644 index 00000000..1d9b37cf --- /dev/null +++ b/core/adapter/syscall/src/hdf_devmgr_adapter.c @@ -0,0 +1,80 @@ +/* + * 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_base.h" +#include "hdf_io_service.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" + +int32_t HdfLoadDriverByServiceName(const char *serviceName) +{ + int32_t ret = HDF_FAILURE; + struct HdfSBuf *data = NULL; + if (serviceName == NULL || strcmp(serviceName, DEV_MGR_NODE) == 0) { + return ret; + } + struct HdfIoService *ioService = HdfIoServiceBind(DEV_MGR_NODE); + if (ioService == NULL) { + HDF_LOGE("Fail to get %s service", DEV_MGR_NODE); + return ret; + } + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("fail to obtain sbuf data"); + ret = HDF_DEV_ERR_NO_MEMORY; + goto out; + } + if (!HdfSbufWriteString(data, serviceName)) { + HDF_LOGE("fail 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"); + } +out: + HdfIoServiceRecycle(ioService); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfGetServiceNameByDeviceClass(DeviceClass deviceClass, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + struct HdfSBuf *data = NULL; + if (reply == NULL) { + HDF_LOGE("%s input reply is null", __func__); + return ret; + } + struct HdfIoService *ioService = HdfIoServiceBind(DEV_MGR_NODE); + if (ioService == NULL) { + HDF_LOGE("Fail to get %s service", DEV_MGR_NODE); + return ret; + } + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("fail to obtain sbuf data"); + ret = HDF_DEV_ERR_NO_MEMORY; + goto out; + } + if (!HdfSbufWriteInt32(data, deviceClass)) { + HDF_LOGE("fail 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"); + } +out: + HdfIoServiceRecycle(ioService); + HdfSBufRecycle(data); + return ret; +} + diff --git a/core/adapter/syscall/src/hdf_syscall_adapter.c b/core/adapter/syscall/src/hdf_syscall_adapter.c new file mode 100644 index 00000000..cefcaa3e --- /dev/null +++ b/core/adapter/syscall/src/hdf_syscall_adapter.c @@ -0,0 +1,1102 @@ +/* + * 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_syscall_adapter.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG hdf_syscall_adapter +#define EPOLL_MAX_EVENT_SIZE 4 +#define HDF_DEFAULT_BWR_READ_SIZE 1024 +#define EVENT_READ_BUFF_GROWTH_RATE 2 +#define EVENT_READ_BUFF_MAX (20 * 1024) // 20k +#define SYSCALL_INVALID_FD (-1) +#define HDF_PFD_GROW_SIZE 4 + +static bool HaveOnlyOneElement(const struct DListHead *head) +{ + if (head->next != head && head->next->next == head) { + return true; + } + + return false; +} + +static int32_t HdfDevEventGrowReadBuffer(struct HdfWriteReadBuf *buffer) +{ + size_t newSize = buffer->readSize; + + if (newSize > EVENT_READ_BUFF_MAX) { + HDF_LOGE("%s: report event size out of max limit", __func__); + return HDF_DEV_ERR_NORANGE; + } + + void *newBuff = OsalMemAlloc(newSize); + if (newBuff == NULL) { + HDF_LOGE("%s:oom,%d", __func__, (int)newSize); + return HDF_DEV_ERR_NO_MEMORY; + } + + OsalMemFree((void*)buffer->readBuffer); + buffer->readBuffer = (uintptr_t)newBuff; + return HDF_SUCCESS; +} + +static struct HdfSyscallAdapter *HdfFdToAdapterLocked(const struct HdfDevListenerThread *thread, int32_t fd) +{ + if (thread->adapter != NULL && thread->adapter->fd == fd) { + return thread->adapter; + } + + if (thread->adapterListPtr == NULL) { + return NULL; + } + + struct HdfSyscallAdapter *adapter = NULL; + DLIST_FOR_EACH_ENTRY(adapter, thread->adapterListPtr, struct HdfSyscallAdapter, listNode) { + if (adapter->fd == fd) { + return adapter; + } + } + + return NULL; +} + +static int32_t HdfDevEventDispatchLocked(const struct HdfDevListenerThread *thread, struct HdfSyscallAdapter *adapter, + const struct HdfWriteReadBuf *bwr) +{ + struct HdfDevEventlistener *listener = NULL; + struct HdfSBuf *sbuf = NULL; + + if (bwr->readConsumed > 0) { + sbuf = HdfSBufBind(bwr->readBuffer, bwr->readConsumed); + } else { + sbuf = HdfSBufObtain(sizeof(int)); + } + + if (sbuf == NULL) { + HDF_LOGE("%s:sbuf oom", __func__); + return HDF_DEV_ERR_NO_MEMORY; + } + + /* dispatch event to SERVICE GROUP listener */ + if (thread->listenerListPtr != NULL) { + DLIST_FOR_EACH_ENTRY(listener, thread->listenerListPtr, 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; + } + } + + OsalMutexLock(&adapter->mutex); + /* dispatch event to 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; + } + OsalMutexUnlock(&adapter->mutex); + + HdfSBufRecycle(sbuf); + return HDF_SUCCESS; +} + +static int32_t HdfDevEventReadAndDispatch(struct HdfDevListenerThread *thread, int32_t fd) +{ + struct HdfWriteReadBuf bwr = { 0 }; + 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; + } + + OsalMutexLock(&thread->mutex); + + struct HdfSyscallAdapter *adapter = HdfFdToAdapterLocked(thread, fd); + if (adapter == NULL) { + HDF_LOGI("%s:adapter invalid\n", __func__); + OsalMSleep(1); + goto finish; + } + + while (true) { + ret = ioctl(adapter->fd, HDF_READ_DEV_EVENT, &bwr); + if (ret == 0) { + break; + } + 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 */ + } + } + if (ret == -HDF_DEV_ERR_NODATA) { + ret = HDF_SUCCESS; + } else { + HDF_LOGE("%s:ioctl failed, errno=%d\n", __func__, ret); + } + + goto finish; + } + + ret = HdfDevEventDispatchLocked(thread, adapter, &bwr); + +finish: + OsalMemFree((void*)bwr.readBuffer); + OsalMutexUnlock(&thread->mutex); + return ret; +} + +static int32_t AssignPfds(struct HdfDevListenerThread *thread, struct pollfd **pfds, uint16_t *pfdSize) +{ + struct pollfd *pfdPtr = *pfds; + uint16_t pfdCount = 0; + + OsalMutexLock(&thread->mutex); + if (*pfdSize < thread->pfdSize) { + pfdPtr = OsalMemAlloc(sizeof(struct pollfd) * thread->pfdSize); + if (pfdPtr == NULL) { + HDF_LOGE("%s: oom", __func__); + OsalMutexUnlock(&thread->mutex); + return HDF_ERR_MALLOC_FAIL; + } + + *pfdSize = thread->pfdSize; + OsalMemFree(*pfds); + *pfds = pfdPtr; + } + + for (uint32_t i = 0; i < thread->pfdSize; i++) { + if (thread->pfds[i].fd != SYSCALL_INVALID_FD) { + pfdPtr[pfdCount].fd = thread->pfds[i].fd; + pfdPtr[pfdCount].events = thread->pfds[i].events; + pfdPtr[pfdCount].revents = 0; + pfdCount++; + } + } + + thread->pollChanged = false; + OsalMutexUnlock(&thread->mutex); + return pfdCount; +} + +#define POLL_WAIT_TIME_MS 100 +static int32_t HdfDevEventListenTask(void *para) +{ + struct HdfDevListenerThread *thread = (struct HdfDevListenerThread *)para; + struct pollfd *pfds = NULL; + uint16_t pfdSize = 0; + int32_t pollCount = 0; + + while (!thread->shouldStop) { + if (thread->pollChanged) { + pollCount = AssignPfds(thread, &pfds, &pfdSize); + } + if (pollCount <= 0) { + goto exit; + } + int32_t pollSize = poll(pfds, pollCount, -1); + if (pollSize <= 0) { + HDF_LOGE("%s: poll fail (%d)%s", __func__, errno, strerror(errno)); + OsalMSleep(POLL_WAIT_TIME_MS); + continue; + } + for (uint32_t i = 0; i < (uint32_t)pollCount; i++) { + if (pfds[i].fd == SYSCALL_INVALID_FD) { + continue; + } + if ((((uint32_t)pfds[i].revents) & POLLIN) && + HdfDevEventReadAndDispatch(thread, pfds[i].fd) != HDF_SUCCESS) { + goto exit; + } else if (((uint32_t)pfds[i].revents) & POLLHUP) { + HDF_LOGI("event listener task received exit event"); + thread->shouldStop = true; + goto exit; + } else if (((uint32_t)pfds[i].revents) & POLLNVAL) { + OsalMSleep(1); // polled closed fd, yield to sync + } + } + } + +exit: + HDF_LOGI("event listener task exit"); + + thread->status = LISTENER_EXITED; + OsalMemFree(pfds); + + if (thread->shouldStop) { + /* exit due to async exit call, should free thread struct */ + OsalMutexDestroy(&thread->mutex); + OsalThreadDestroy(&thread->thread); + OsalMemFree(thread->pfds); + OsalMemFree(thread); + } + + return HDF_SUCCESS; +} + +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)); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +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)); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +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)); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +static int32_t HdfDevListenerThreadDoInit(struct HdfDevListenerThread *thread) +{ + if (OsalMutexInit(&thread->mutex) != HDF_SUCCESS) { + HDF_LOGE("%s: fail 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__); + thread->status = LISTENER_UNINITED; + OsalMutexDestroy(&thread->mutex); + return HDF_ERR_THREAD_CREATE_FAIL; + } + + thread->status = LISTENER_INITED; + thread->shouldStop = false; + thread->pollChanged = true; + + return HDF_SUCCESS; +} + +static int32_t HdfDevListenerThreadInit(struct HdfDevListenerThread *thread) +{ + switch (thread->status) { + case LISTENER_RUNNING: // fall-through + case LISTENER_INITED: // fall-through + case LISTENER_WAITING: + return HDF_SUCCESS; + case LISTENER_EXITED: + thread->status = LISTENER_INITED; + thread->shouldStop = false; + return HDF_SUCCESS; + case LISTENER_UNINITED: + return HdfDevListenerThreadDoInit(thread); + default: + break; + } + + return HDF_FAILURE; +} + +static int32_t GetValidPfdIndexLocked(struct HdfDevListenerThread *thread, struct HdfSyscallAdapter *adapter) +{ + uint32_t index = 0; + struct pollfd *pfds = thread->pfds; + for (; index < thread->pfdSize; index++) { + if (pfds[index].fd == SYSCALL_INVALID_FD) { + break; + } + + if (pfds[index].fd == adapter->fd) { + return index; + } + } + + if (index >= thread->pfdSize) { + uint32_t newSize = thread->pfdSize + HDF_PFD_GROW_SIZE; + struct pollfd *newPfds = OsalMemCalloc(sizeof(struct pollfd) * newSize); + if (newPfds == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + if (thread->pfdSize != 0) { + (void)memcpy_s(newPfds, sizeof(struct pollfd) * newSize, + thread->pfds, sizeof(struct pollfd) * thread->pfdSize); + } + + for (uint32_t i = index; i < newSize; i++) { + newPfds[i].fd = SYSCALL_INVALID_FD; + } + + OsalMemFree(thread->pfds); + thread->pfds = newPfds; + thread->pfdSize = newSize; + } + + return index; +} + +static int32_t HdfAddAdapterToPfds(struct HdfDevListenerThread *thread, struct HdfSyscallAdapter *adapter) +{ + int32_t index = GetValidPfdIndexLocked(thread, adapter); + if (index < 0) { + return HDF_ERR_MALLOC_FAIL; + } + + thread->pfds[index].fd = adapter->fd; + thread->pfds[index].events = POLLIN; + thread->pfds[index].revents = 0; + + return HDF_SUCCESS; +} + +static int32_t HdfListenThreadInitPollFds(struct HdfDevListenerThread *thread) +{ + struct HdfSyscallAdapter *adapter = NULL; + if (thread->adapterListPtr != NULL) { + DLIST_FOR_EACH_ENTRY(adapter, thread->adapterListPtr, struct HdfSyscallAdapter, listNode) { + if (HdfAddAdapterToPfds(thread, adapter) != HDF_SUCCESS) { + return HDF_ERR_MALLOC_FAIL; + } + } + } + + if (thread->adapter != NULL) { + return HdfAddAdapterToPfds(thread, thread->adapter); + } + + return HDF_SUCCESS; +} + +static int32_t HdfDevListenerThreadStart(struct HdfDevListenerThread *thread) +{ + if (thread->status == LISTENER_RUNNING) { + return HDF_SUCCESS; + } + + if (thread->status != LISTENER_INITED) { + return HDF_ERR_INVALID_PARAM; + } + + int32_t ret = HdfListenThreadInitPollFds(thread); + if (ret != HDF_SUCCESS || thread->pfdSize <= 0) { + HDF_LOGE("%s:invalid poll list", __func__); + return HDF_DEV_ERR_NO_DEVICE; + } + + do { + for (int i = 0; i < thread->pfdSize; i++) { + if (thread->pfds[i].fd == SYSCALL_INVALID_FD) { + continue; + } + if (HdfAdapterStartListenIoctl(thread->pfds[i].fd)) { + return HDF_ERR_IO; + } + } + + struct OsalThreadParam config = { + .name = "hdf_event_listener", + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = 0, + }; + + if (OsalThreadStart(&thread->thread, &config) != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadStart failed", __func__); + ret = HDF_FAILURE; + break; + } + thread->status = LISTENER_RUNNING; + return HDF_SUCCESS; + } while (0); + + return ret; +} + +static struct HdfDevListenerThread *HdfDevListenerThreadObtain(void) +{ + struct HdfDevListenerThread *thread = OsalMemCalloc(sizeof(struct HdfDevListenerThread)); + if (thread == NULL) { + return NULL; + } + thread->status = LISTENER_UNINITED; + if (HdfDevListenerThreadInit(thread) != HDF_SUCCESS) { + OsalMemFree(thread); + return NULL; + } + return thread; +} + +static int32_t HdfIoServiceGroupThreadInit(struct HdfSyscallAdapterGroup *group) +{ + if (group->thread == NULL) { + struct HdfDevListenerThread *listenerThread = HdfDevListenerThreadObtain(); + if (listenerThread == NULL) { + return HDF_ERR_THREAD_CREATE_FAIL; + } + group->thread = listenerThread; + } + group->thread->adapterListPtr = &group->adapterList; + group->thread->listenerListPtr = &group->listenerList; + return HdfDevListenerThreadInit(group->thread); +} + +static int32_t HdfIoServiceGroupThreadStart(struct HdfSyscallAdapterGroup *group) +{ + OsalMutexLock(&group->mutex); + if (HdfIoServiceGroupThreadInit(group) != HDF_SUCCESS) { + OsalMutexUnlock(&group->mutex); + return HDF_FAILURE; + } + int32_t ret = HdfDevListenerThreadStart(group->thread); + OsalMutexUnlock(&group->mutex); + return ret; +} + +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->adapterListPtr == NULL) { + return HDF_SUCCESS; + } + + OsalMutexLock(&thread->mutex); + struct HdfSyscallAdapter *headAdapter = DListIsEmpty(thread->adapterListPtr) ? + NULL : DLIST_FIRST_ENTRY(thread->adapterListPtr, struct HdfSyscallAdapter, listNode); + + DListInsertTail(&adapter->listNode, thread->adapterListPtr); + + if (thread->status != LISTENER_RUNNING) { + OsalMutexUnlock(&thread->mutex); + return HDF_SUCCESS; + } + + int32_t ret = HDF_SUCCESS; + do { + int32_t index = GetValidPfdIndexLocked(thread, adapter); + if (index < 0) { + ret = HDF_ERR_MALLOC_FAIL; + break; + } + + thread->pfds[index].fd = adapter->fd; + thread->pfds[index].events = POLLIN; + thread->pfds[index].revents = 0; + + 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)); + thread->pfds[index].fd = SYSCALL_INVALID_FD; + ret = HDF_ERR_IO; + break; + } + } + + if (HdfAdapterStartListenIoctl(adapter->fd) != HDF_SUCCESS) { + thread->pfds[index].fd = SYSCALL_INVALID_FD; + ret = HDF_DEV_ERR_OP; + break; + } + thread->pollChanged = true; + OsalMutexUnlock(&thread->mutex); + return ret; + } while (false); + + DListRemove(&adapter->listNode); + OsalMutexUnlock(&thread->mutex); + return ret; +} + +static void HdfListenThreadPollDel(struct HdfDevListenerThread *thread, struct HdfSyscallAdapter *adapter) +{ + if (thread == NULL) { + DListRemove(&adapter->listNode); + adapter->group = NULL; + return; + } + OsalMutexLock(&thread->mutex); + struct pollfd *pfds = thread->pfds; + for (uint32_t index = 0; index < thread->pfdSize; index++) { + if (pfds[index].fd == adapter->fd) { + pfds[index].fd = SYSCALL_INVALID_FD; + break; + } + } + + if (HdfAdapterStopListenIoctl(adapter->fd)) { + HDF_LOGE("%s: fail 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)); + } + DListRemove(&adapter->listNode); + adapter->group = NULL; + thread->pollChanged = true; + 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) { + return; + } + + switch (thread->status) { + case LISTENER_RUNNING: { + uint32_t stopCount = 0; + OsalMutexLock(&thread->mutex); + thread->adapter = NULL; + thread->adapterListPtr = NULL; + thread->listenerListPtr = NULL; + OsalMutexUnlock(&thread->mutex); + for (int i = 0; i < thread->pfdSize; i++) { + if (thread->pfds[i].fd == SYSCALL_INVALID_FD) { + continue; + } + if (HdfAdapterExitListenIoctl(thread->pfds[i].fd) == HDF_SUCCESS) { + stopCount++; + } + } + + if (stopCount == 0) { + thread->shouldStop = true; + HDF_LOGE("%s:failed to exit listener thread with ioctl, will go async way", __func__); + } + + return; + } + case LISTENER_EXITED: // fall-through + case LISTENER_INITED: + HdfDevListenerThreadFree(thread); + break; + default: + break; + } +} + +static int32_t HdfSyscallAdapterDispatch(struct HdfObject *object, int32_t code, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (object == NULL) { + HDF_LOGE("Input object is null"); + return HDF_FAILURE; + } + struct HdfSyscallAdapter *ioService = (struct HdfSyscallAdapter *)object; + struct HdfWriteReadBuf wrBuf; + if (reply != NULL) { + wrBuf.readBuffer = (uintptr_t)HdfSbufGetData(reply); + wrBuf.readSize = HdfSbufGetCapacity(reply); + } else { + wrBuf.readBuffer = 0; + wrBuf.readSize = 0; + } + if (data != NULL) { + wrBuf.writeBuffer = (uintptr_t)HdfSbufGetData(data); + wrBuf.writeSize = HdfSbufGetDataSize(data); + } else { + wrBuf.writeBuffer = 0; + wrBuf.writeSize = 0; + } + + wrBuf.readConsumed = 0; + wrBuf.writeConsumed = 0; + 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); + } + if (reply != NULL) { + reply->writePos = wrBuf.readConsumed; + } + return ret; +} + +struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName) +{ + struct HdfSyscallAdapter *adapter = NULL; + struct HdfIoService *ioService = NULL; + char devNodePath[PATH_MAX] = {0}; + char realPath[PATH_MAX] = {0}; + + const char *devPath = DEV_NODE_PATH; + if (access(DEV_NODE_PATH, F_OK) != 0) { + devPath = DEV_PATH; + } + + if (sprintf_s(devNodePath, PATH_MAX - 1, "%s%s", devPath, serviceName) < 0) { + HDF_LOGE("Get node path failed"); + return NULL; + } + + if (realpath(devNodePath, realPath) == NULL) { + if (HdfLoadDriverByServiceName(serviceName) != HDF_SUCCESS) { + HDF_LOGE("%s load %s driver failed", __func__, serviceName); + return NULL; + } + if (realpath(devNodePath, realPath) == NULL) { + HDF_LOGE("%s file name %s is invalid", __func__, devNodePath); + return NULL; + } + } + + adapter = (struct HdfSyscallAdapter *)OsalMemCalloc(sizeof(struct HdfSyscallAdapter)); + if (adapter == NULL) { + HDF_LOGE("Alloc syscall adapter failed"); + return NULL; + } + + DListHeadInit(&adapter->listenerList); + if (OsalMutexInit(&adapter->mutex)) { + HDF_LOGE("%s: create mutex fail", __func__); + OsalMemFree(adapter); + return NULL; + } + + adapter->fd = open(realPath, O_RDWR); + if (adapter->fd < 0) { + HDF_LOGE("Open file node %s failed, (%d)%s", realPath, errno, strerror(errno)); + OsalMutexDestroy(&adapter->mutex); + OsalMemFree(adapter); + return NULL; + } + ioService = &adapter->super; + static struct HdfIoDispatcher dispatch = { + .Dispatch = HdfSyscallAdapterDispatch, + }; + ioService->dispatcher = &dispatch; + return ioService; +} + +void HdfIoServiceAdapterRecycle(struct HdfIoService *service) +{ + struct HdfSyscallAdapter *adapter = (struct HdfSyscallAdapter *)service; + if (adapter != NULL) { + HdfDevListenerThreadDestroy(adapter->thread); + adapter->thread = NULL; + if (adapter->fd >= 0) { + close(adapter->fd); + adapter->fd = -1; + } + OsalMutexDestroy(&adapter->mutex); + OsalMemFree(adapter); + } +} + +static int32_t HdfIoServiceThreadBindLocked(struct HdfSyscallAdapter *adapter) +{ + if (adapter->thread == NULL) { + struct HdfDevListenerThread *listenerthread = HdfDevListenerThreadObtain(); + if (listenerthread == NULL) { + return HDF_ERR_THREAD_CREATE_FAIL; + } + adapter->thread = listenerthread; + } + adapter->thread->adapter = adapter; + return HdfDevListenerThreadInit(adapter->thread); +} + +static int32_t HdfIoServiceStartListen(struct HdfSyscallAdapter *adapter) +{ + if (HdfIoServiceThreadBindLocked(adapter) != HDF_SUCCESS) { + HDF_LOGE("%s:adapter bind thread fail", __func__); + return HDF_FAILURE; + } + + return HdfDevListenerThreadStart(adapter->thread); +} + +static bool AddListenerToAdapterLocked(struct HdfSyscallAdapter *adapter, struct HdfDevEventlistener *listener) +{ + struct HdfDevEventlistener *it = NULL; + DLIST_FOR_EACH_ENTRY(it, &adapter->listenerList, struct HdfDevEventlistener, listNode) { + if (it == listener) { + HDF_LOGE("add duplicate dev-event listener"); + return false; + } + } + DListInsertTail(&listener->listNode, &adapter->listenerList); + return true; +} + +int32_t HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener) +{ + if (target == NULL || listener == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (listener->callBack == NULL && listener->onReceive == NULL) { + HDF_LOGE("listenr onReceive func not implement"); + return HDF_ERR_INVALID_OBJECT; + } + + struct HdfSyscallAdapter *adapter = CONTAINER_OF(target, struct HdfSyscallAdapter, super); + int32_t ret = HDF_SUCCESS; + + OsalMutexLock(&adapter->mutex); + if (!AddListenerToAdapterLocked(adapter, listener)) { + OsalMutexUnlock(&adapter->mutex); + return HDF_ERR_INVALID_PARAM; + } + + if (adapter->group != NULL) { + /* service in group, should not bind to self hold thread and try to start group thread */ + ret = HdfIoServiceGroupThreadStart(adapter->group); + OsalMutexUnlock(&adapter->mutex); + return ret; + } + + if (HdfIoServiceStartListen(adapter) != HDF_SUCCESS) { + DListRemove(&listener->listNode); + ret = HDF_FAILURE; + } + + OsalMutexUnlock(&adapter->mutex); + return ret; +} + +int32_t HdfDeviceUnregisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener) +{ + if (target == NULL || listener == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (listener->listNode.next == NULL || listener->listNode.prev == NULL) { + HDF_LOGE("%s:broken listener, may double unregister", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + struct HdfSyscallAdapter *adapter = (struct HdfSyscallAdapter *)target; + OsalMutexLock(&adapter->mutex); + + DListRemove(&listener->listNode); + + if (DListIsEmpty(&adapter->listenerList)) { + HdfDevListenerThreadDestroy(adapter->thread); + adapter->thread = NULL; + } + OsalMutexUnlock(&adapter->mutex); + + return HDF_SUCCESS; +} + +struct HdfIoServiceGroup *HdfIoServiceGroupObtain(void) +{ + struct HdfSyscallAdapterGroup *adapterGroup = OsalMemCalloc(sizeof(struct HdfSyscallAdapterGroup)); + if (adapterGroup == NULL) { + return NULL; + } + + if (OsalMutexInit(&adapterGroup->mutex)) { + OsalMemFree(adapterGroup); + return NULL; + } + DListHeadInit(&adapterGroup->adapterList); + DListHeadInit(&adapterGroup->listenerList); + return &adapterGroup->serviceGroup; +} + +void HdfIoServiceGroupRecycle(struct HdfIoServiceGroup *group) +{ + if (group == NULL) { + return; + } + + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + OsalMutexLock(&adapterGroup->mutex); + + HdfDevListenerThreadDestroy(adapterGroup->thread); + adapterGroup->thread = NULL; + + struct HdfSyscallAdapter *adapter = NULL; + struct HdfSyscallAdapter *tmp = NULL; + DLIST_FOR_EACH_ENTRY_SAFE(adapter, tmp, &adapterGroup->adapterList, struct HdfSyscallAdapter, listNode) { + DListRemove(&adapter->listNode); + adapter->group = NULL; + } + + OsalMutexUnlock(&adapterGroup->mutex); + + OsalMutexDestroy(&adapterGroup->mutex); + OsalMemFree(adapterGroup); +} + +int32_t HdfIoServiceGroupRegisterListener(struct HdfIoServiceGroup *group, struct HdfDevEventlistener *listener) +{ + if (group == NULL || listener == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (listener->callBack == NULL && listener->onReceive == NULL) { + HDF_LOGE("listenr onReceive func not implement"); + return HDF_ERR_INVALID_OBJECT; + } + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + + OsalMutexLock(&adapterGroup->mutex); + if (HdfIoServiceGroupThreadInit(adapterGroup) != HDF_SUCCESS) { + HDF_LOGE("%s:failed to bind listener thread for service group", __func__); + OsalMutexUnlock(&adapterGroup->mutex); + return HDF_FAILURE; + } + + int32_t ret = HDF_SUCCESS; + struct HdfDevListenerThread *listenerThread = adapterGroup->thread; + + OsalMutexLock(&listenerThread->mutex); + 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; + goto finish; + } + } + DListInsertTail(&listener->listNode, &adapterGroup->listenerList); + if (!DListIsEmpty(&adapterGroup->adapterList) && listenerThread->status != LISTENER_RUNNING) { + ret = HdfDevListenerThreadStart(listenerThread); + if (ret != HDF_SUCCESS) { + DListRemove(&listener->listNode); + } + } + +finish: + OsalMutexUnlock(&listenerThread->mutex); + OsalMutexUnlock(&adapterGroup->mutex); + return ret; +} + +static int32_t GetListenerCount(struct HdfDevListenerThread *thread) +{ + struct HdfDevEventlistener *listener = NULL; + int32_t count = 0; + + OsalMutexLock(&thread->mutex); + if (thread->listenerListPtr != NULL) { + DLIST_FOR_EACH_ENTRY (listener, thread->listenerListPtr, struct HdfDevEventlistener, listNode) { + count++; + } + } + + struct HdfSyscallAdapter *adapter = NULL; + DLIST_FOR_EACH_ENTRY (adapter, thread->adapterListPtr, struct HdfSyscallAdapter, listNode) { + OsalMutexLock(&adapter->mutex); + DLIST_FOR_EACH_ENTRY (listener, &adapter->listenerList, struct HdfDevEventlistener, listNode) { + count++; + } + OsalMutexUnlock(&adapter->mutex); + } + OsalMutexUnlock(&thread->mutex); + + return count; +} + +int32_t HdfIoServiceGroupUnregisterListener(struct HdfIoServiceGroup *group, struct HdfDevEventlistener *listener) +{ + if (group == NULL || listener == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (listener->listNode.next == NULL || listener->listNode.prev == NULL) { + HDF_LOGE("%s:broken listener, may double unregister", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + + OsalMutexLock(&adapterGroup->mutex); + struct HdfDevListenerThread *listenerThread = adapterGroup->thread; + + DListRemove(&listener->listNode); + + if (listenerThread != NULL && GetListenerCount(listenerThread) == 0) { + HdfDevListenerThreadDestroy(listenerThread); + adapterGroup->thread = NULL; + } + OsalMutexUnlock(&adapterGroup->mutex); + + return HDF_SUCCESS; +} + +int32_t HdfIoServiceGroupAddService(struct HdfIoServiceGroup *group, struct HdfIoService *service) +{ + if (group == NULL || service == NULL) { + return HDF_ERR_INVALID_PARAM; + } + struct HdfSyscallAdapter *adapter = CONTAINER_OF(service, struct HdfSyscallAdapter, super); + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + + if (adapter->group != NULL) { + HDF_LOGE("service already in group"); + return HDF_ERR_DEVICE_BUSY; + } + + if (adapter->thread != NULL) { + HDF_LOGE("service already has independent thread"); + return HDF_ERR_DEVICE_BUSY; + } + + OsalMutexLock(&adapterGroup->mutex); + if (HdfIoServiceGroupThreadInit(adapterGroup) != HDF_SUCCESS) { + HDF_LOGE("%s:failed to bind listener thread for service group", __func__); + OsalMutexUnlock(&adapterGroup->mutex); + return HDF_FAILURE; + } + + struct HdfDevListenerThread *listenerThread = adapterGroup->thread; + int32_t ret = HdfListenThreadPollAdd(listenerThread, adapter); + if (ret != HDF_SUCCESS) { + OsalMutexUnlock(&adapterGroup->mutex); + return ret; + } + + adapter->group = adapterGroup; + + OsalMutexLock(&listenerThread->mutex); + if ((!DListIsEmpty(&adapterGroup->listenerList) || !DListIsEmpty(&adapter->listenerList)) && + listenerThread->status != LISTENER_RUNNING) { + ret = HdfDevListenerThreadStart(adapterGroup->thread); + if (ret != HDF_SUCCESS) { + HdfListenThreadPollDel(adapterGroup->thread, adapter); + } + } + OsalMutexUnlock(&listenerThread->mutex); + OsalMutexUnlock(&adapterGroup->mutex); + return ret; +} + +void HdfIoServiceGroupRemoveService(struct HdfIoServiceGroup *group, struct HdfIoService *service) +{ + if (group == NULL || service == NULL) { + return; + } + struct HdfSyscallAdapter *adapter = CONTAINER_OF(service, struct HdfSyscallAdapter, super); + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + if (adapterGroup->thread == NULL || adapter->group == NULL) { + return; + } + + OsalMutexLock(&adapterGroup->mutex); + if (HaveOnlyOneElement(&adapterGroup->adapterList)) { + HdfDevListenerThreadDestroy(adapterGroup->thread); + adapterGroup->thread = NULL; + DListRemove(&adapter->listNode); + adapter->group = NULL; + } else { + HdfListenThreadPollDel(adapterGroup->thread, adapter); + } + OsalMutexUnlock(&adapterGroup->mutex); + adapter->group = NULL; +} + +static int DlistGetCount(const struct DListHead *head) +{ + struct DListHead *next = head->next; + int count = 0; + while (next != head) { + next = next->next; + count++; + } + return count; +} + +int HdfIoserviceGetListenerCount(const struct HdfIoService *service) +{ + if (service == NULL) { + return 0; + } + + struct HdfSyscallAdapter *adapter = CONTAINER_OF(service, struct HdfSyscallAdapter, super); + + OsalMutexLock(&adapter->mutex); + int count = DlistGetCount(&adapter->listenerList); + OsalMutexUnlock(&adapter->mutex); + return count; +} + +int HdfIoserviceGroupGetListenerCount(const struct HdfIoServiceGroup *group) +{ + if (group == NULL) { + return 0; + } + + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + OsalMutexLock(&adapterGroup->mutex); + if (adapterGroup->thread == NULL) { + OsalMutexUnlock(&adapterGroup->mutex); + return 0; + } + int count = GetListenerCount(adapterGroup->thread); + OsalMutexUnlock(&adapterGroup->mutex); + return count; +} + +int HdfIoserviceGroupGetServiceCount(const struct HdfIoServiceGroup *group) +{ + if (group == NULL) { + return 0; + } + + struct HdfSyscallAdapterGroup *adapterGroup = CONTAINER_OF(group, struct HdfSyscallAdapterGroup, serviceGroup); + + OsalMutexLock(&adapterGroup->mutex); + if (adapterGroup->thread == NULL) { + OsalMutexUnlock(&adapterGroup->mutex); + return 0; + } + + OsalMutexLock(&adapterGroup->thread->mutex); + int count = DlistGetCount(&adapterGroup->adapterList); + OsalMutexUnlock(&adapterGroup->thread->mutex); + + OsalMutexUnlock(&adapterGroup->mutex); + + return count; +} diff --git a/core/adapter/vnode/include/hdf_vnode_adapter.h b/core/adapter/vnode/include/hdf_vnode_adapter.h new file mode 100644 index 00000000..96fcb9db --- /dev/null +++ b/core/adapter/vnode/include/hdf_vnode_adapter.h @@ -0,0 +1,33 @@ +/* + * 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_VNODE_ADAPTER_H +#define HDF_VNODE_ADAPTER_H +#include "hdf_dlist.h" +#include "osal_mutex.h" +#include "hdf_sbuf.h" +#include "hdf_io_service.h" + +struct OsalCdev; + +struct HdfVNodeAdapter { + struct HdfIoService ioService; + char *vNodePath; + struct OsalMutex mutex; + struct DListHead clientList; + struct OsalCdev *cdev; +}; + +struct HdfDevEvent { + uint32_t id; + struct HdfSBuf *data; + struct DListHead listNode; +}; + +#endif /* HDF_VNODE_ADAPTER_H */ + diff --git a/core/adapter/vnode/src/hdf_vnode_adapter.c b/core/adapter/vnode/src/hdf_vnode_adapter.c new file mode 100644 index 00000000..0d39bd60 --- /dev/null +++ b/core/adapter/vnode/src/hdf_vnode_adapter.c @@ -0,0 +1,662 @@ +/* + * 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_vnode_adapter.h" +#include +#include +#include +#include +#include +#include "devsvc_manager_clnt.h" +#include "hdf_device_node_ext.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" + +#define HDF_LOG_TAG hdf_vnode +#define VOID_DATA_SIZE 4 +#define EVENT_QUEUE_MAX 100 +#define MAX_RW_SIZE (1024*1204) // 1M + +enum HdfVNodeClientStatus { + VNODE_CLIENT_RUNNING, + VNODE_CLIENT_LISTENING, + VNODE_CLIENT_STOPPED, + VNODE_CLIENT_EXITED, +}; + +struct HdfVNodeAdapterClient { + struct HdfVNodeAdapter *adapter; + struct HdfDeviceIoClient ioServiceClient; + wait_queue_head_t pollWait; + struct HdfIoService *serv; + struct OsalMutex mutex; + struct DListHead eventQueue; + struct DListHead listNode; + int32_t eventQueueSize; + int32_t wakeup; + uint32_t status; +}; + +struct HdfIoServiceKClient { + struct HdfIoService ioService; + struct HdfDeviceIoClient client; +}; + +int HdfKIoServiceDispatch (struct HdfObject *service, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct HdfIoService *ioService = (struct HdfIoService*)service; + struct HdfIoServiceKClient *kClient = NULL; + + if (ioService == NULL || ioService->dispatcher == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + kClient = CONTAINER_OF(ioService, struct HdfIoServiceKClient, ioService); + if (kClient->client.device == NULL || kClient->client.device->service == NULL || + kClient->client.device->service->Dispatch == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + return kClient->client.device->service->Dispatch(&kClient->client, cmdId, data, reply); +} + +static struct HdfIoServiceKClient *HdfHdfIoServiceKClientInstance(struct HdfDeviceObject *deviceObject) +{ + static struct HdfIoDispatcher kDispatcher = { + .Dispatch = HdfKIoServiceDispatch, + }; + + struct HdfIoServiceKClient *client = OsalMemCalloc(sizeof(struct HdfIoServiceKClient)); + if (client == NULL) { + return NULL; + } + + client->client.device = deviceObject; + if (deviceObject->service != NULL && deviceObject->service->Open != NULL) { + if (deviceObject->service->Open(&client->client) != HDF_SUCCESS) { + OsalMemFree(client); + return NULL; + } + } + + client->ioService.dispatcher = &kDispatcher; + return client; +} + +struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName) +{ + struct DevSvcManagerClnt *svcMgr = NULL; + struct HdfDeviceObject *deviceObject = NULL; + struct HdfIoServiceKClient *kClient = NULL; + + if (serviceName == NULL) { + return NULL; + } + + svcMgr = DevSvcManagerClntGetInstance(); + if (svcMgr == NULL) { + return NULL; + } + deviceObject = svcMgr->devSvcMgrIf->GetObject(svcMgr->devSvcMgrIf, serviceName); + if (deviceObject == NULL) { + return NULL; + } + + kClient = HdfHdfIoServiceKClientInstance(deviceObject); + if (kClient == NULL) { + return NULL; + } + + return &kClient->ioService; +} + +void HdfIoServiceAdapterRecycle(struct HdfIoService *ioService) +{ + struct HdfIoServiceKClient *kClient = NULL; + + if (ioService == NULL) { + return; + } + + kClient = CONTAINER_OF(ioService, struct HdfIoServiceKClient, ioService); + if (kClient->client.device != NULL && kClient->client.device->service != NULL && + kClient->client.device->service->Release != NULL) { + kClient->client.device->service->Release(&kClient->client); + } + OsalMemFree(kClient); +} + +static struct HdfSBuf *HdfSbufCopyFromUser(uintptr_t data, size_t size) +{ + uint8_t *kData = NULL; + struct HdfSBuf *sbuf = NULL; + + if (size == 0) { + return HdfSBufObtain(VOID_DATA_SIZE); + } + + kData = OsalMemAlloc(size); + if (kData == NULL) { + HDF_LOGE("%s:oom", __func__); + return NULL; + } + if (CopyFromUser((void*)kData, (void*)data, size) != 0) { + HDF_LOGE("%s:copy from user fail", __func__); + OsalMemFree(kData); + return NULL; + } + + sbuf = HdfSBufBind((uintptr_t)kData, size); + if (sbuf == NULL) { + OsalMemFree(kData); + } + HdfSbufTransDataOwnership(sbuf); + + return sbuf; +} + +static int HdfSbufCopyToUser(const struct HdfSBuf *sbuf, void *dstUser, size_t dstUserSize) +{ + size_t sbufSize = HdfSbufGetDataSize(sbuf); + if (sbufSize == 0) { + return HDF_SUCCESS; + } + if (dstUserSize < sbufSize) { + HDF_LOGE("%s: readBuffer too small %u", __func__, sbufSize); + return HDF_DEV_ERR_NORANGE; + } + + if (CopyToUser(dstUser, HdfSbufGetData(sbuf), sbufSize) != 0) { + HDF_LOGE("%s: copy buff data fail", __func__); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +static void DevEventFree(struct HdfDevEvent *event) +{ + if (event == NULL) { + return; + } + if (event->data != NULL) { + HdfSBufRecycle(event->data); + event->data = NULL; + } + OsalMemFree(event); +} + +static int HdfVNodeAdapterServCall(const struct HdfVNodeAdapterClient *client, unsigned long arg) +{ + struct HdfWriteReadBuf bwr; + struct HdfWriteReadBuf *bwrUser = (struct HdfWriteReadBuf *)((uintptr_t)arg); + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + int ret; + + if (client->serv == NULL) { + return HDF_DEV_ERR_NO_DEVICE; + } + + if (bwrUser == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (CopyFromUser(&bwr, (void*)bwrUser, sizeof(bwr)) != 0) { + HDF_LOGE("Copy from user failed"); + return HDF_FAILURE; + } + if (bwr.writeSize > MAX_RW_SIZE || bwr.readSize > MAX_RW_SIZE) { + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufCopyFromUser(bwr.writeBuffer, bwr.writeSize); + if (data == NULL) { + HDF_LOGE("Vnode adapter bind data is null"); + return HDF_FAILURE; + } + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + HDF_LOGE("%s:oom", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + (void)HdfSbufWriteUint64(reply, (uintptr_t)&client->ioServiceClient); + ret = client->adapter->ioService.dispatcher->Dispatch(client->adapter->ioService.target, + bwr.cmdCode, data, reply); + if (bwr.readSize != 0 && HdfSbufCopyToUser(reply, (void*)bwr.readBuffer, bwr.readSize) != HDF_SUCCESS) { + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return HDF_ERR_IO; + } + bwr.readConsumed = HdfSbufGetDataSize(reply); + if (CopyToUser(bwrUser, &bwr, sizeof(struct HdfWriteReadBuf)) != 0) { + HDF_LOGE("%s: copy bwr fail", __func__); + ret = HDF_FAILURE; + } + + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return ret; +} + +static int HdfVNodeAdapterReadDevEvent(struct HdfVNodeAdapterClient *client, unsigned long arg) +{ + struct HdfWriteReadBuf bwr; + struct HdfWriteReadBuf *bwrUser = (struct HdfWriteReadBuf *)((uintptr_t)arg); + struct HdfDevEvent *event = NULL; + size_t eventSize; + + int ret = HDF_SUCCESS; + if (bwrUser == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (CopyFromUser(&bwr, (void*)bwrUser, sizeof(bwr)) != 0) { + HDF_LOGE("Copy from user failed"); + return HDF_FAILURE; + } + + if (bwr.readSize > MAX_RW_SIZE) { + return HDF_ERR_INVALID_PARAM; + } + OsalMutexLock(&client->mutex); + + if (DListIsEmpty(&client->eventQueue)) { + OsalMutexUnlock(&client->mutex); + return HDF_DEV_ERR_NODATA; + } + + event = CONTAINER_OF(client->eventQueue.next, struct HdfDevEvent, listNode); + eventSize = HdfSbufGetDataSize(event->data); + if (eventSize > bwr.readSize) { + bwr.readSize = eventSize; + ret = HDF_DEV_ERR_NORANGE; + } else { + if (HdfSbufCopyToUser(event->data, (void *)bwr.readBuffer, bwr.readSize) != HDF_SUCCESS) { + OsalMutexUnlock(&client->mutex); + return HDF_ERR_IO; + } + bwr.readConsumed = eventSize; + bwr.cmdCode = event->id; + } + + if (CopyToUser(bwrUser, &bwr, sizeof(struct HdfWriteReadBuf)) != 0) { + HDF_LOGE("%s: copy bwr fail", __func__); + ret = HDF_ERR_IO; + } + if (ret == HDF_SUCCESS) { + DListRemove(&event->listNode); + DevEventFree(event); + client->eventQueueSize--; + } + + OsalMutexUnlock(&client->mutex); + return ret; +} + +static void HdfVnodeAdapterDropOldEventLocked(struct HdfVNodeAdapterClient *client) +{ + struct HdfDevEvent *dropEvent = CONTAINER_OF(client->eventQueue.next, struct HdfDevEvent, listNode); + + HDF_LOGE("dev event queue full, drop old one"); + DListRemove(&dropEvent->listNode); + DevEventFree(dropEvent); + client->eventQueueSize--; +} + +static int VNodeAdapterSendDevEventToClient(struct HdfVNodeAdapterClient *vnodeClient, + uint32_t id, const struct HdfSBuf *data) +{ + struct HdfDevEvent *event = NULL; + + OsalMutexLock(&vnodeClient->mutex); + if (vnodeClient->status != VNODE_CLIENT_LISTENING) { + OsalMutexUnlock(&vnodeClient->mutex); + return HDF_SUCCESS; + } + if (vnodeClient->eventQueueSize >= EVENT_QUEUE_MAX) { + HdfVnodeAdapterDropOldEventLocked(vnodeClient); + } + event = OsalMemAlloc(sizeof(struct HdfDevEvent)); + if (event == NULL) { + OsalMutexUnlock(&vnodeClient->mutex); + return HDF_DEV_ERR_NO_MEMORY; + } + event->id = id; + event->data = HdfSBufCopy(data); + if (event->data == NULL) { + OsalMutexUnlock(&vnodeClient->mutex); + HDF_LOGE("%s: sbuf oom", __func__); + OsalMemFree(event); + return HDF_DEV_ERR_NO_MEMORY; + } + DListInsertTail(&event->listNode, &vnodeClient->eventQueue); + vnodeClient->eventQueueSize++; + wake_up_interruptible(&vnodeClient->pollWait); + OsalMutexUnlock(&vnodeClient->mutex); + + return HDF_SUCCESS; +} + +static int HdfVNodeAdapterSendDevEvent(struct HdfVNodeAdapter *adapter, struct HdfVNodeAdapterClient *vnodeClient, + uint32_t id, const struct HdfSBuf *data) +{ + struct HdfVNodeAdapterClient *client = NULL; + int ret = HDF_FAILURE; + + if (adapter == NULL || data == NULL || HdfSbufGetDataSize(data) == 0) { + return HDF_ERR_INVALID_PARAM; + } + OsalMutexLock(&adapter->mutex); + DLIST_FOR_EACH_ENTRY(client, &adapter->clientList, struct HdfVNodeAdapterClient, listNode) { + if (vnodeClient != NULL && client != vnodeClient) { + continue; + } + ret = VNodeAdapterSendDevEventToClient(client, id, data); + if (ret != HDF_SUCCESS) { + break; + } + } + OsalMutexUnlock(&adapter->mutex); + return ret; +} + +static void HdfVNodeAdapterClientStartListening(struct HdfVNodeAdapterClient *client) +{ + OsalMutexLock(&client->mutex); + client->status = VNODE_CLIENT_LISTENING; + OsalMutexUnlock(&client->mutex); +} + +static void HdfVnodeCleanEventQueue(struct HdfVNodeAdapterClient *client) +{ + struct HdfDevEvent *event = NULL; + struct HdfDevEvent *eventTemp = NULL; + DLIST_FOR_EACH_ENTRY_SAFE(event, eventTemp, &client->eventQueue, struct HdfDevEvent, listNode) { + DListRemove(&event->listNode); + DevEventFree(event); + } +} + +static void HdfVNodeAdapterClientStopListening(struct HdfVNodeAdapterClient *client) +{ + OsalMutexLock(&client->mutex); + client->status = VNODE_CLIENT_STOPPED; + HdfVnodeCleanEventQueue(client); + wake_up_interruptible(&client->pollWait); + OsalMutexUnlock(&client->mutex); +} + +static void HdfVNodeAdapterClientExitListening(struct HdfVNodeAdapterClient *client) +{ + OsalMutexLock(&client->mutex); + client->status = VNODE_CLIENT_EXITED; + HdfVnodeCleanEventQueue(client); + wake_up_interruptible(&client->pollWait); + OsalMutexUnlock(&client->mutex); +} + +static void HdfVNodeAdapterClientWakeup(struct HdfVNodeAdapterClient *client) +{ + OsalMutexLock(&client->mutex); + if (client->status != VNODE_CLIENT_LISTENING) { + OsalMutexUnlock(&client->mutex); + return; + } + client->wakeup++; + wake_up_interruptible(&client->pollWait); + OsalMutexUnlock(&client->mutex); +} + +static long HdfVNodeAdapterIoctl(struct file *filep, unsigned int cmd, unsigned long arg) +{ + struct HdfVNodeAdapterClient *client = (struct HdfVNodeAdapterClient *)OsalGetFilePriv(filep); + if (client == NULL) { + return HDF_DEV_ERR_NO_DEVICE; + } + switch (cmd) { + case HDF_WRITE_READ: + return HdfVNodeAdapterServCall(client, arg); + case HDF_READ_DEV_EVENT: + return HdfVNodeAdapterReadDevEvent(client, arg); + case HDF_LISTEN_EVENT_START: + HdfVNodeAdapterClientStartListening(client); + break; + case HDF_LISTEN_EVENT_STOP: + HdfVNodeAdapterClientStopListening(client); + break; + case HDF_LISTEN_EVENT_WAKEUP: + HdfVNodeAdapterClientWakeup(client); + break; + case HDF_LISTEN_EVENT_EXIT: + HdfVNodeAdapterClientExitListening(client); + break; + default: + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static struct HdfVNodeAdapterClient *HdfNewVNodeAdapterClient(struct HdfVNodeAdapter *adapter) +{ + struct HdfVNodeAdapterClient *client = OsalMemCalloc(sizeof(struct HdfVNodeAdapterClient)); + if (client == NULL) { + HDF_LOGE("%s: oom", __func__); + return NULL; + } + if (OsalMutexInit(&client->mutex) != HDF_SUCCESS) { + OsalMemFree(client); + HDF_LOGE("%s: no mutex", __func__); + return NULL; + } + + DListHeadInit(&client->eventQueue); + client->eventQueueSize = 0; + 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; + init_waitqueue_head(&client->pollWait); + OsalMutexLock(&adapter->mutex); + DListInsertTail(&client->listNode, &adapter->clientList); + OsalMutexUnlock(&adapter->mutex); + + return client; +} + +static void HdfDestoryVNodeAdapterClient(struct HdfVNodeAdapterClient *client) +{ + struct HdfDevEvent *event = NULL; + struct HdfDevEvent *eventTemp = NULL; + + client->status = VNODE_CLIENT_STOPPED; + + OsalMutexLock(&client->adapter->mutex); + DListRemove(&client->listNode); + OsalMutexUnlock(&client->adapter->mutex); + + OsalMutexLock(&client->mutex); + DLIST_FOR_EACH_ENTRY_SAFE(event, eventTemp, &client->eventQueue, struct HdfDevEvent, listNode) { + DListRemove(&event->listNode); + DevEventFree(event); + } + OsalMutexUnlock(&client->mutex); + OsalMutexDestroy(&client->mutex); + OsalMemFree(client); +} + +int HdfVNodeAdapterOpen(struct OsalCdev *cdev, struct file *filep) +{ + struct HdfVNodeAdapter *adapter = (struct HdfVNodeAdapter *)OsalGetCdevPriv(cdev); + struct HdfVNodeAdapterClient *client = NULL; + int32_t ret; + + if (adapter == NULL) { + HDF_LOGE("Vnode adapter dispatcher is null"); + return HDF_FAILURE; + } + client = HdfNewVNodeAdapterClient(adapter); + if (client == NULL) { + return ETXTBSY; + } + OsalSetFilePriv(filep, client); + if (client->ioServiceClient.device != NULL && client->ioServiceClient.device->service != NULL && + client->ioServiceClient.device->service->Open != NULL) { + ret = client->ioServiceClient.device->service->Open(&client->ioServiceClient); + if (ret != HDF_SUCCESS) { + HdfDestoryVNodeAdapterClient(client); + return ret; + } + } + + return HDF_SUCCESS; +} + +static unsigned int HdfVNodeAdapterPoll(struct file *filep, poll_table *wait) +{ + unsigned int mask = 0; + struct HdfVNodeAdapterClient *client = (struct HdfVNodeAdapterClient *)OsalGetFilePriv(filep); + + poll_wait(filep, &client->pollWait, wait); + OsalMutexLock(&client->mutex); + if (client->status == VNODE_CLIENT_EXITED) { + mask |= POLLHUP; + } else if (!DListIsEmpty(&client->eventQueue)) { + mask |= POLLIN; + } else if (client->wakeup > 0) { + mask |= POLLIN; + client->wakeup--; + } + OsalMutexUnlock(&client->mutex); + return mask; +} + +static int HdfVNodeAdapterClose(struct OsalCdev *cdev, struct file *filep) +{ + (void)cdev; + struct HdfVNodeAdapterClient *client = (struct HdfVNodeAdapterClient *)OsalGetFilePriv(filep); + if (client->ioServiceClient.device != NULL && client->ioServiceClient.device->service != NULL && + client->ioServiceClient.device->service->Release != NULL) { + client->ioServiceClient.device->service->Release(&client->ioServiceClient); + } + HdfDestoryVNodeAdapterClient(client); + return HDF_SUCCESS; +} + +struct HdfIoService *HdfIoServiceAdapterPublish(const char *serviceName, uint32_t mode) +{ + int nodePathLength; + struct HdfVNodeAdapter *vnodeAdapter = NULL; + int ret; + static const struct OsalCdevOps fileOps = { + .open = HdfVNodeAdapterOpen, + .release = HdfVNodeAdapterClose, + .ioctl = HdfVNodeAdapterIoctl, + .poll = HdfVNodeAdapterPoll, + }; + + if ((serviceName == NULL) || (mode > MAX_MODE_SIZE)) { + 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"); + 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"); + OsalMemFree(vnodeAdapter); + return NULL; + } + + if (sprintf_s(vnodeAdapter->vNodePath, nodePathLength, "%s%s", DEV_NODE_PATH, serviceName) < 0) { + HDF_LOGE("Get node path failed"); + OsalMemFree(vnodeAdapter->vNodePath); + OsalMemFree(vnodeAdapter); + return NULL; + } + DListHeadInit(&vnodeAdapter->clientList); + if (OsalMutexInit(&vnodeAdapter->mutex) != HDF_SUCCESS) { + HDF_LOGE("vnode adapter out of mutex"); + goto error; + } + vnodeAdapter->cdev = OsalAllocCdev(&fileOps); + if (vnodeAdapter->cdev == NULL) { + HDF_LOGE("fail to alloc osalcdev"); + OsalMutexDestroy(&vnodeAdapter->mutex); + goto error; + } + ret = OsalRegisterCdev(vnodeAdapter->cdev, vnodeAdapter->vNodePath, mode, vnodeAdapter); + if (ret != 0) { + HDF_LOGE("register dev node %s failed, ret is: %d", vnodeAdapter->vNodePath, ret); + OsalMutexDestroy(&vnodeAdapter->mutex); + goto error; + } + + return &vnodeAdapter->ioService; +error: + OsalMemFree(vnodeAdapter->vNodePath); + OsalMemFree(vnodeAdapter); + return NULL; +} + +void HdfIoServiceAdapterRemove(struct HdfIoService *service) +{ + if (service != NULL) { + struct HdfVNodeAdapter *vnodeAdapter = (struct HdfVNodeAdapter *)service; + if (vnodeAdapter->vNodePath != NULL) { + OsalUnregisterCdev(vnodeAdapter->cdev); + OsalFreeCdev(vnodeAdapter->cdev); + OsalMemFree(vnodeAdapter->vNodePath); + } + OsalMutexDestroy(&vnodeAdapter->mutex); + OsalMemFree(vnodeAdapter); + } +} + +int32_t HdfDeviceSendEvent(const struct HdfDeviceObject *deviceObject, uint32_t id, const struct HdfSBuf *data) +{ + struct HdfDeviceNode *deviceNode = NULL; + struct HdfVNodeAdapter *adapter = NULL; + + if (deviceObject == NULL || data == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + deviceNode = CONTAINER_OF(deviceObject, struct HdfDeviceNode, deviceObject); + if (deviceNode->deviceInfo->policy != SERVICE_POLICY_CAPACITY) { + return HDF_ERR_NOT_SUPPORT; + } + + adapter = (struct HdfVNodeAdapter *)(((struct DeviceNodeExt*)deviceNode)->ioService); + return HdfVNodeAdapterSendDevEvent(adapter, NULL, id, data); +} + +int32_t HdfDeviceSendEventToClient(const struct HdfDeviceIoClient *client, uint32_t id, const struct HdfSBuf *data) +{ + struct HdfVNodeAdapterClient *vnodeClient = NULL; + if (client == NULL || client->device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + vnodeClient = CONTAINER_OF(client, struct HdfVNodeAdapterClient, ioServiceClient); + if (vnodeClient->adapter == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + return HdfVNodeAdapterSendDevEvent(vnodeClient->adapter, vnodeClient, id, data); +} diff --git a/core/common/include/host/hdf_device_section.h b/core/common/include/host/hdf_device_section.h new file mode 100644 index 00000000..fea82a1c --- /dev/null +++ b/core/common/include/host/hdf_device_section.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 HDF_DEVICE_SECTION_H +#define HDF_DEVICE_SECTION_H + +#if !defined(NON_HDF_DRIVER_SECTION) +#define USED_ATTR __attribute__((used)) +#define HDF_SECTION __attribute__((section(".hdf.driver"))) +#define HDF_DRIVER_INIT(module) \ + const size_t USED_ATTR module##HdfEntry HDF_SECTION = (size_t)(&(module)) + +#if (defined(__GNUC__) || defined(__clang__)) +#define HDF_DRIVER_SEC_NAME(type, name) \ + ({ extern type name; \ + &name; \ + }) +#define HDF_DRIVER_BEGIN() HDF_DRIVER_SEC_NAME(size_t, _hdf_drivers_start) +#define HDF_DRIVER_END() HDF_DRIVER_SEC_NAME(size_t, _hdf_drivers_end) + +#elif defined(__ICCARM__) +#define HDF_DRIVER_BEGIN() __section_begin(".hdf.driver") +#define HDF_DRIVER_END() __section_end(".hdf.driver") +#pragma section = ".hdf.driver" +#else +#error "No support section begin and section end!" +#endif /* defined(__GNUC__) || defined(__clang__) */ +#endif /* NON_HDF_DRIVER_SECTION */ + +#endif /* HDF_DEVICE_SECTION_H */ + diff --git a/core/common/include/manager/devmgr_service_start.h b/core/common/include/manager/devmgr_service_start.h new file mode 100644 index 00000000..6a2d571e --- /dev/null +++ b/core/common/include/manager/devmgr_service_start.h @@ -0,0 +1,22 @@ +/* + * 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 DEVICE_SERVICE_START_H +#define DEVICE_SERVICE_START_H + +enum { + DEV_MGR_SLOW_LOAD = 0, + DEV_MGR_QUICK_LOAD, +}; + +int DeviceManagerStart(void); +int DeviceManagerStartStep2(void); +void DeviceManagerSetQuickLoad(int isQuickLoad); +int DeviceManagerIsQuickLoad(void); + +#endif /* DEVICE_SERVICE_START_H */ diff --git a/core/common/include/manager/hdf_device_node_ext.h b/core/common/include/manager/hdf_device_node_ext.h new file mode 100644 index 00000000..b0bb685c --- /dev/null +++ b/core/common/include/manager/hdf_device_node_ext.h @@ -0,0 +1,24 @@ +/* + * 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_DEVICE_NODE_EXT_H +#define HDF_DEVICE_NODE_EXT_H + +#include "hdf_io_service.h" +#include "hdf_device_node.h" + +struct DeviceNodeExt { + struct HdfDeviceNode super; + struct HdfIoService *ioService; +}; + +struct HdfObject *DeviceNodeExtCreate(void); +void DeviceNodeExtRelease(struct HdfObject *object); + +#endif /* HDF_DEVICE_NODE_EXT_H */ + diff --git a/core/common/src/devlite_object_config.c b/core/common/src/devlite_object_config.c new file mode 100644 index 00000000..bea66407 --- /dev/null +++ b/core/common/src/devlite_object_config.c @@ -0,0 +1,69 @@ +/* + * 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_object_manager.h" +#include "devhost_service.h" +#include "devmgr_service.h" +#include "devsvc_manager.h" +#include "hdf_device.h" +#include "hdf_device_node_ext.h" +#include "hdf_device_token.h" +#include "hdf_driver_installer.h" +#include "hdf_driver_loader.h" + +static const struct HdfObjectCreator g_liteObjectCreators[] = { + [HDF_OBJECT_ID_DEVMGR_SERVICE] = + { + .Create = DevmgrServiceCreate, + .Release = DevmgrServiceRelease, + }, + [HDF_OBJECT_ID_DEVSVC_MANAGER] = + { + .Create = DevSvcManagerCreate, + .Release = DevSvcManagerRelease, + }, + [HDF_OBJECT_ID_DEVHOST_SERVICE] = + { + .Create = DevHostServiceCreate, + .Release = DevHostServiceRelease, + }, + [HDF_OBJECT_ID_DRIVER_INSTALLER] = + { + .Create = DriverInstallerCreate, + .Release = NULL, + }, + [HDF_OBJECT_ID_DRIVER_LOADER] = + { + .Create = HdfDriverLoaderCreate, + .Release = NULL, + }, + [HDF_OBJECT_ID_DEVICE] = + { + .Create = HdfDeviceCreate, + .Release = HdfDeviceRelease, + }, + [HDF_OBJECT_ID_DEVICE_TOKEN] = + { + .Create = HdfDeviceTokenCreate, + .Release = HdfDeviceTokenRelease, + }, + [HDF_OBJECT_ID_DEVICE_SERVICE] = + { + .Create = DeviceNodeExtCreate, + .Release = DeviceNodeExtRelease, + } +}; + +const struct HdfObjectCreator *HdfObjectManagerGetCreators(int objectId) +{ + int numConfigs = sizeof(g_liteObjectCreators) / sizeof(g_liteObjectCreators[0]); + if ((objectId >= 0) && (objectId < numConfigs)) { + return &g_liteObjectCreators[objectId]; + } + return NULL; +} diff --git a/core/common/src/devmgr_service_start.c b/core/common/src/devmgr_service_start.c new file mode 100644 index 00000000..a1c78200 --- /dev/null +++ b/core/common/src/devmgr_service_start.c @@ -0,0 +1,141 @@ +/* + * 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 "devmgr_service_start.h" +#include "devhost_service_clnt.h" +#include "devmgr_service.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_device_node.h" +#include "hdf_io_service.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" + +#define DEV_MGR_NODE_PERM 0660 + +static int g_isQuickLoad = DEV_MGR_SLOW_LOAD; + +static void GetDeviceServiceNameByClass(DeviceClass deviceClass, struct HdfSBuf *reply) +{ + struct HdfSListIterator itHost; + struct HdfSListIterator itDeviceInfo; + struct HdfDeviceInfo *deviceInfo = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); + if (devMgrSvc == NULL) { + return; + } + + reply->readPos = 0; + reply->writePos = 0; + HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); + while (HdfSListIteratorHasNext(&itHost)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); + HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&itDeviceInfo)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); + if (deviceInfo->policy == SERVICE_POLICY_CAPACITY) { + struct HdfDeviceObject *deviceObject = DevSvcManagerClntGetDeviceObject(deviceInfo->svcName); + if (deviceObject == NULL || (deviceObject->deviceClass != deviceClass)) { + continue; + } + HdfSbufWriteString(reply, deviceInfo->svcName); + } + } + } + HdfSbufWriteString(reply, NULL); +} + +int DeviceManagerDispatch(struct HdfObject *stub, int code, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)reply; + int ret = HDF_FAILURE; + int32_t deviceClass = 0; + const char *svcName = NULL; + struct DevmgrService *devMgrSvc = (struct DevmgrService *)stub; + if (data == NULL || devMgrSvc == NULL) { + HDF_LOGE("%s: input param is invalid", __func__); + return ret; + } + OsalMutexLock(&devMgrSvc->devMgrMutex); + switch (code) { + case DEVMGR_LOAD_SERVICE: + svcName = HdfSbufReadString(data); + if (svcName == NULL) { + HDF_LOGE("%s: get svc name is null", __func__); + break; + } + static struct SubscriberCallback callback = { + .deviceObject = NULL, + .OnServiceConnected = NULL, + }; + ret = DevSvcManagerClntSubscribeService(svcName, callback); + break; + case DEVMGR_UNLOAD_SERVICE: + svcName = HdfSbufReadString(data); + if (svcName == NULL) { + HDF_LOGE("%s: get 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__); + 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); + break; + } + OsalMutexUnlock(&devMgrSvc->devMgrMutex); + return ret; +} + +void DeviceManagerSetQuickLoad(int loadFlag) +{ + g_isQuickLoad = loadFlag; +} + +int DeviceManagerIsQuickLoad() +{ + return g_isQuickLoad; +} + +int DeviceManagerStart() +{ + struct IDevmgrService *instance = DevmgrServiceGetInstance(); + + if (instance == NULL || instance->StartService == 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); + if (ioService != NULL) { + static struct HdfIoDispatcher dispatcher = { + .Dispatch = DeviceManagerDispatch, + }; + ioService->dispatcher = &dispatcher; + ioService->target = &instance->base; + } + return instance->StartService(instance); +} + +int DeviceManagerStartStep2() +{ + if (DeviceManagerIsQuickLoad() == DEV_MGR_SLOW_LOAD) { + HDF_LOGW("%s device manager is not set quick load!", __func__); + return HDF_SUCCESS; + } + struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); + return DevmgrServiceLoadLeftDriver(devMgrSvc); +} + diff --git a/core/common/src/hdf_attribute.c b/core/common/src/hdf_attribute.c new file mode 100644 index 00000000..71583265 --- /dev/null +++ b/core/common/src/hdf_attribute.c @@ -0,0 +1,369 @@ +/* + * 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_attribute_manager.h" +#include "devhost_service_clnt.h" +#include "devmgr_service.h" +#include "hcs_blob_if.h" +#include "hcs_parser.h" +#include "hcs_tree_if.h" +#include "hdf_base.h" +#include "hdf_device_info.h" +#include "hdf_host_info.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" + +#define ATTR_HOST_NAME "hostName" +#define ATTR_DEV_POLICY "policy" +#define ATTR_DEV_PRIORITY "priority" +#define ATTR_DEV_PRELOAD "preload" +#define ATTR_DEV_PERMISSION "permission" +#define ATTR_DEV_MODULENAME "moduleName" +#define ATTR_DEV_SVCNAME "serviceName" +#define ATTR_DEV_MATCHATTR "deviceMatchAttr" +#define MANAGER_NODE_MATCH_ATTR "hdf_manager" + +static struct DeviceResourceNode *g_hcsTreeRoot = NULL; + +void HdfGetBuildInConfigData(const unsigned char **data, unsigned int *size); +static bool CreateHcsToTree(void) +{ + uint32_t length; + const unsigned char *hcsBlob = NULL; + HdfGetBuildInConfigData(&hcsBlob, &length); + if (!HcsCheckBlobFormat((const char *)hcsBlob, length)) { + return false; + } + if (!HcsDecompile((const char *)hcsBlob, HBC_HEADER_LENGTH, &g_hcsTreeRoot)) { + return false; + } + return true; +} + +const struct DeviceResourceNode *HcsGetRootNode(void) +{ + if ((g_hcsTreeRoot == NULL) && !CreateHcsToTree()) { + HDF_LOGE("%s failed", __func__); + return NULL; + } + return g_hcsTreeRoot; +} + +const struct DeviceResourceNode *HdfGetRootNode(void) +{ + return HcsGetRootNode(); +} + +static bool HdfHostListCompare(struct HdfSListNode *listEntryFirst, struct HdfSListNode *listEntrySecond) +{ + if (listEntryFirst == NULL || listEntrySecond == NULL) { + return false; + } + struct HdfHostInfo *attrFirst = (struct HdfHostInfo *)listEntryFirst; + struct HdfHostInfo *attrSecond = (struct HdfHostInfo *)listEntrySecond; + return attrFirst->priority <= attrSecond->priority; +} + +static const struct DeviceResourceNode *GetHdfManagerNode(const struct DeviceResourceNode *node) +{ + return HcsGetNodeByMatchAttr(node, MANAGER_NODE_MATCH_ATTR); +} + +static bool GetHostInfo(const struct DeviceResourceNode *hostNode, struct HdfHostInfo *hostInfo) +{ + 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__); + 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); + return false; + } + hostInfo->priority = readNum; + return true; +} + +bool HdfAttributeManagerGetHostList(struct HdfSList *hostList) +{ + const struct DeviceResourceNode *hdfManagerNode = NULL; + const struct DeviceResourceNode *hostNode = NULL; + uint16_t hostId = 0; + if (hostList == NULL) { + return false; + } + + hdfManagerNode = GetHdfManagerNode(HcsGetRootNode()); + if (hdfManagerNode == NULL) { + HDF_LOGE("%s get hdf manager node is null", __func__); + return false; + } + + hostNode = hdfManagerNode->child; + while (hostNode != NULL) { + struct HdfHostInfo *hostInfo = HdfHostInfoNewInstance(); + if (hostInfo == NULL) { + HdfSListFlush(hostList, HdfHostInfoDelete); + 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; + } + hostId++; + hostNode = hostNode->sibling; + } + return true; +} + +static bool HdfDeviceListCompare(struct HdfSListNode *listEntryFirst, struct HdfSListNode *listEntrySecond) +{ + if (listEntryFirst == NULL || listEntrySecond == NULL) { + return false; + } + struct HdfDeviceInfo *attrFirst = (struct HdfDeviceInfo *)listEntryFirst; + struct HdfDeviceInfo *attrSecond = (struct HdfDeviceInfo *)listEntrySecond; + return attrFirst->priority <= attrSecond->priority; +} + +static const struct DeviceResourceNode *GetHostNode(const char *inHostName) +{ + const struct DeviceResourceNode *hdfManagerNode = NULL; + const struct DeviceResourceNode *hostNode = NULL; + const char *hostName = NULL; + + hdfManagerNode = GetHdfManagerNode(HcsGetRootNode()); + if (hdfManagerNode == NULL) { + return NULL; + } + hostNode = hdfManagerNode->child; + while (hostNode != NULL) { + if (HcsGetString(hostNode, ATTR_HOST_NAME, &hostName, NULL) != HDF_SUCCESS) { + hostNode = hostNode->sibling; + continue; + } + if (strcmp(hostName, inHostName) == 0) { + return hostNode; + } + hostNode = hostNode->sibling; + } + return NULL; +} + +static bool CheckDeviceInfo(const struct HdfDeviceInfo *deviceNodeInfo) +{ + if (deviceNodeInfo->policy > SERVICE_POLICY_PRIVATE) { + HDF_LOGE("%s policy is invalid", __func__); + return false; + } + + if (deviceNodeInfo->priority > MAX_PRIORITY_NUM) { + HDF_LOGE("%s priority is invalid", __func__); + return false; + } + + if (deviceNodeInfo->preload > DEVICE_PRELOAD_DISABLE) { + HDF_LOGE("%s preload is invalid", __func__); + return false; + } + + return (strcmp(deviceNodeInfo->moduleName, "") != 0); +} + +static bool GetDeviceNodeInfo(const struct DeviceResourceNode *deviceNode, struct HdfDeviceInfo *deviceNodeInfo) +{ + 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__); + return false; + } + deviceNodeInfo->policy = readNum; + + if (HcsGetUint16(deviceNode, ATTR_DEV_PRIORITY, &readNum, 0) != HDF_SUCCESS) { + HDF_LOGE("%s get priority failed", __func__); + return false; + } + deviceNodeInfo->priority = readNum; + + if (HcsGetUint16(deviceNode, ATTR_DEV_PRELOAD, &readNum, 0) != HDF_SUCCESS) { + HDF_LOGE("%s get preload failed", __func__); + return false; + } + deviceNodeInfo->preload = readNum; + + if (HcsGetUint16(deviceNode, ATTR_DEV_PERMISSION, &readNum, 0) != HDF_SUCCESS) { + HDF_LOGE("%s get permission failed", __func__); + return false; + } + deviceNodeInfo->permission = readNum; + + if (HcsGetString(deviceNode, ATTR_DEV_MODULENAME, &readString, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s get module name failed", __func__); + return false; + } + deviceNodeInfo->moduleName = readString; + + if (HcsGetString(deviceNode, ATTR_DEV_SVCNAME, &readString, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s get service name failed", __func__); + return false; + } + deviceNodeInfo->svcName = readString; + + if (HcsGetString(deviceNode, ATTR_DEV_MATCHATTR, &readString, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s get service name failed", __func__); + return false; + } + deviceNodeInfo->deviceMatchAttr = readString; + return CheckDeviceInfo(deviceNodeInfo); +} + +struct HdfSList *HdfAttributeManagerGetDeviceList(uint16_t hostId, const char *hostName) +{ + uint16_t deviceIdx = 0; + const struct DeviceResourceNode *hostNode = GetHostNode(hostName); + if (hostNode == NULL) { + return NULL; + } + struct HdfSList *deviceList = (struct HdfSList *)OsalMemCalloc(sizeof(struct HdfSList)); + if (deviceList == NULL) { + return NULL; + } + const struct DeviceResourceNode *device = hostNode->child; + while (device != NULL) { + const struct DeviceResourceNode *deviceNode = device->child; + while (deviceNode != NULL) { + struct HdfDeviceInfo *deviceNodeInfo = HdfDeviceInfoNewInstance(); + if (deviceNodeInfo == NULL) { + HdfSListFlush(deviceList, HdfDeviceInfoDelete); + OsalMemFree(deviceList); + return NULL; + } + deviceNodeInfo->hostId = hostId; + if (!GetDeviceNodeInfo(deviceNode, deviceNodeInfo)) { + HdfDeviceInfoFreeInstance(deviceNodeInfo); + HDF_LOGE("%s get device failed", __func__); + deviceNodeInfo = NULL; + deviceNode = deviceNode->sibling; + continue; + } + if (!HdfSListAddOrder(deviceList, &deviceNodeInfo->node, HdfDeviceListCompare)) { + HDF_LOGE("%s add device %s failed", __func__, deviceNodeInfo->svcName); + HdfDeviceInfoFreeInstance(deviceNodeInfo); + deviceNodeInfo = NULL; + deviceNode = deviceNode->sibling; + continue; + } + deviceNodeInfo->deviceId = deviceIdx; + deviceNode = deviceNode->sibling; + } + device = device->sibling; + deviceIdx++; + } + if (HdfSListCount(deviceList) == 0) { + OsalMemFree(deviceList); + return NULL; + } + return deviceList; +} + +bool HdfDeviceListAdd(const char *moduleName, const char *serviceName) +{ + struct HdfSListIterator itHost; + struct HdfSListIterator itDeviceInfo; + struct HdfDeviceInfo *deviceInfo = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); + if (devMgrSvc == NULL || moduleName == NULL || serviceName == NULL) { + return false; + } + + struct HdfDeviceInfo *deviceNodeInfo = HdfDeviceInfoNewInstance(); + if (deviceNodeInfo == NULL) { + return false; + } + HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); + while (HdfSListIteratorHasNext(&itHost)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); + HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&itDeviceInfo)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); + if (deviceInfo->moduleName == NULL) { + continue; + } + if (strcmp(deviceInfo->moduleName, moduleName) == 0) { + deviceInfo->isDynamic = true; + deviceNodeInfo->hostId = deviceInfo->hostId; + deviceNodeInfo->deviceId = hostClnt->devCount; + deviceNodeInfo->policy = deviceInfo->policy; + deviceNodeInfo->priority = deviceInfo->priority; + deviceNodeInfo->preload = DEVICE_PRELOAD_DISABLE; + deviceNodeInfo->permission = deviceInfo->permission; + deviceNodeInfo->deviceMatchAttr = deviceInfo->deviceMatchAttr; + deviceNodeInfo->moduleName = deviceInfo->moduleName; + char *svcName = OsalMemCalloc(strlen(serviceName) + 1); + if (svcName == NULL) { + break; + } + if (strcpy_s(svcName, strlen(serviceName) + 1, serviceName) != EOK) { + HDF_LOGE("%s: string copy fail", __func__); + OsalMemFree(svcName); + break; + } + deviceNodeInfo->svcName = svcName; + HdfSListAdd(hostClnt->deviceInfos, &deviceNodeInfo->node); + hostClnt->devCount++; + return true; + } + } + } + HdfDeviceInfoFreeInstance(deviceNodeInfo); + return false; +} + +void HdfDeviceListDel(const char *moduleName, const char *serviceName) +{ + struct HdfSListIterator itHost; + struct HdfSListIterator itDeviceInfo; + struct HdfDeviceInfo *deviceInfo = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); + if (devMgrSvc == NULL || moduleName == NULL || serviceName == NULL) { + return; + } + + HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); + while (HdfSListIteratorHasNext(&itHost)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); + HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&itDeviceInfo)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); + if ((strcmp(deviceInfo->moduleName, moduleName) == 0) && + (strcmp(deviceInfo->svcName, serviceName) == 0)) { + HdfSListRemove(hostClnt->deviceInfos, &deviceInfo->node); + HdfDeviceInfoFreeInstance(deviceInfo); + hostClnt->devCount--; + return; + } + } + } +} + diff --git a/core/common/src/hdf_device_node_ext.c b/core/common/src/hdf_device_node_ext.c new file mode 100644 index 00000000..493cd51e --- /dev/null +++ b/core/common/src/hdf_device_node_ext.c @@ -0,0 +1,125 @@ +/* + * 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_device_node_ext.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_io_service.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG device_node_ext + +static int DeviceNodeExtDispatch(struct HdfObject *stub, int code, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct IDeviceIoService *deviceMethod = NULL; + const struct HdfDeviceInfo *deviceInfo = NULL; + struct HdfDeviceNode *devNode = NULL; + + if (stub == NULL) { + HDF_LOGE("input ioService null"); + return HDF_FAILURE; + } + uint64_t ioClientPtr = 0; + if (!HdfSbufReadUint64(reply, &ioClientPtr) || ioClientPtr == 0) { + HDF_LOGE("input ioClient 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"); + return HDF_FAILURE; + } + deviceInfo = devNode->deviceInfo; + if (deviceInfo == NULL) { + HDF_LOGE("Device deviceInfo is null"); + return HDF_FAILURE; + } + if (deviceInfo->policy == SERVICE_POLICY_CAPACITY) { + if (deviceMethod->Dispatch == NULL) { + HDF_LOGE("Remote service dispatch is null"); + return HDF_FAILURE; + } + return deviceMethod->Dispatch((struct HdfDeviceIoClient *)((uintptr_t)ioClientPtr), code, data, reply); + } + return HDF_FAILURE; +} + +static int DeviceNodeExtPublishService(struct HdfDeviceNode *inst, const char *serviceName) +{ + const struct HdfDeviceInfo *deviceInfo = NULL; + struct HdfDeviceObject *deviceObject = NULL; + struct DeviceNodeExt *devNodeExt = (struct DeviceNodeExt *)inst; + if (devNodeExt == NULL) { + return HDF_FAILURE; + } + int ret = HdfDeviceNodePublishPublicService(inst, serviceName); + if (ret != HDF_SUCCESS) { + HDF_LOGE("Device publish service failed, ret is: %d", ret); + return HDF_FAILURE; + } + + deviceInfo = inst->deviceInfo; + deviceObject = &devNodeExt->super.deviceObject; + if ((deviceObject->service == NULL) || (deviceInfo == NULL)) { + HDF_LOGE("Device service interface or deviceInfo is null"); + return HDF_FAILURE; + } + if (deviceInfo->policy == SERVICE_POLICY_CAPACITY) { + devNodeExt->ioService = HdfIoServicePublish(serviceName, deviceInfo->permission); + if (devNodeExt->ioService != NULL) { + devNodeExt->ioService->target = (struct HdfObject*)(&inst->deviceObject); + static struct HdfIoDispatcher dispatcher = { + .Dispatch = DeviceNodeExtDispatch + }; + devNodeExt->ioService->dispatcher = &dispatcher; + } else { + HDF_LOGE("Device remote service bind failed"); + HdfDeviceNodeReclaimService(serviceName); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static void DeviceNodeExtConstruct(struct DeviceNodeExt *inst) +{ + struct IDeviceNode *nodeIf = (struct IDeviceNode *)inst; + if (nodeIf != NULL) { + HdfDeviceNodeConstruct(&inst->super); + nodeIf->PublishService = DeviceNodeExtPublishService; + } +} + +struct HdfObject *DeviceNodeExtCreate() +{ + struct DeviceNodeExt *instance = + (struct DeviceNodeExt *)OsalMemCalloc(sizeof(struct DeviceNodeExt)); + if (instance != NULL) { + DeviceNodeExtConstruct(instance); + instance->ioService = NULL; + } + return (struct HdfObject *)instance; +} + +void DeviceNodeExtRelease(struct HdfObject *object) +{ + struct DeviceNodeExt *instance = (struct DeviceNodeExt *)object; + if (instance != NULL) { + if (instance->ioService != NULL) { + HdfIoServiceRemove(instance->ioService); + } + HdfDeviceNodeDestruct(&instance->super); + OsalMemFree(instance); + } +} + diff --git a/core/common/src/load_driver_entry.c b/core/common/src/load_driver_entry.c new file mode 100644 index 00000000..39e420a4 --- /dev/null +++ b/core/common/src/load_driver_entry.c @@ -0,0 +1,67 @@ +/* + * 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_driver_loader.h" +#include "hdf_log.h" +#include "osal_mem.h" + +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__); + return NULL; + } + struct HdfDriverEntry *driverEntry = OsalMemCalloc(*driverCount * sizeof(struct HdfDriverEntry)); + if (driverEntry == NULL) { + HDF_LOGE("%s hdf alloc driver entry mem failed!", __func__); + *driverCount = 0; + return NULL; + } + size_t *addrBegin = (size_t *)(HDF_DRIVER_BEGIN()); + for (i = 0; i < *driverCount; i++) { + driverEntry[i] = *(struct HdfDriverEntry *)(*addrBegin); + addrBegin++; + } + return driverEntry; +} + +struct HdfDriverEntry *HdfDriverLoaderGetDriverEntry(const struct HdfDeviceInfo *deviceInfo) +{ + int i; + if ((deviceInfo == NULL) || (deviceInfo->moduleName == NULL) || (deviceInfo->svcName == NULL)) { + HDF_LOGE("%s hdf get device entry failed, input deviceInfo is NULL!", __func__); + return NULL; + } + static struct HdfDriverEntry *driverEntry = NULL; + static int32_t driverCount = 0; + if (driverEntry == NULL) { + driverEntry = HdfDriverEntryConstruct(&driverCount); + if (driverEntry == NULL) { + HDF_LOGE("%s driver entry construct failed!", __func__); + return NULL; + } + } + for (i = 0; i < driverCount; i++) { + if (driverEntry == NULL) { + 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; + } + if (strcmp(deviceInfo->moduleName, driverEntry[i].moduleName) == 0) { + return &driverEntry[i]; + } + } + HDF_LOGE("Hdf get %s device entry failed!", deviceInfo->svcName); + return NULL; +} + diff --git a/core/host/include/devhost_service.h b/core/host/include/devhost_service.h old mode 100755 new mode 100644 index 402e67ce..26d8972c --- a/core/host/include/devhost_service.h +++ b/core/host/include/devhost_service.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVICE_HOST_SERVICE_H @@ -45,6 +22,9 @@ struct DevHostService { struct HdfServiceObserver observer; }; +void DevHostServiceConstruct(struct DevHostService *service); +void DevHostServiceDestruct(struct DevHostService *service); +int DevHostServiceAddDevice(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/devmgr_service_clnt.h b/core/host/include/devmgr_service_clnt.h old mode 100755 new mode 100644 index 962cf208..87216668 --- a/core/host/include/devmgr_service_clnt.h +++ b/core/host/include/devmgr_service_clnt.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVMGR_SERVICE_CLIENT_H diff --git a/core/host/include/devsvc_manager_clnt.h b/core/host/include/devsvc_manager_clnt.h old mode 100755 new mode 100644 index 03be6eca..e164d8ae --- a/core/host/include/devsvc_manager_clnt.h +++ b/core/host/include/devsvc_manager_clnt.h @@ -1,39 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVSVC_MANAGER_CLNT_H #define DEVSVC_MANAGER_CLNT_H #include "devsvc_manager_if.h" -#include "devsvc_manager_stub.h" struct DevSvcManagerClnt { struct IDevSvcManager *devSvcMgrIf; @@ -43,5 +19,9 @@ struct DevSvcManagerClnt *DevSvcManagerClntGetInstance(void); struct HdfDeviceObject *DevSvcManagerClntGetDeviceObject(const char *svcName); int DevSvcManagerClntAddService(const char *svcName, struct HdfDeviceObject *service); void DevSvcManagerClntRemoveService(const char *svcName); +int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback); +int DevSvcManagerClntUnsubscribeService(const char *svcName); +struct HdfDeviceObject *HdfRegisterDevice(const char *moduleName, const char *serviceName); +void HdfUnregisterDevice(const char *moduleName, const char *serviceName); #endif /* DEVSVC_MANAGER_CLNT_H */ diff --git a/core/host/include/hdf_device.h b/core/host/include/hdf_device.h old mode 100755 new mode 100644 index 26b2189f..c14e9901 --- a/core/host/include/hdf_device.h +++ b/core/host/include/hdf_device.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DEVICE_H @@ -54,7 +31,8 @@ struct HdfDevice { uint16_t deviceId; uint16_t hostId; }; - +void HdfDeviceConstruct(struct HdfDevice *device); +void HdfDeviceDestruct(struct HdfDevice *device); struct HdfObject *HdfDeviceCreate(void); void HdfDeviceRelease(struct HdfObject *object); struct HdfDevice *HdfDeviceNewInstance(void); diff --git a/core/host/include/hdf_device_node.h b/core/host/include/hdf_device_node.h old mode 100755 new mode 100644 index 1af1982b..aee06dd2 --- a/core/host/include/hdf_device_node.h +++ b/core/host/include/hdf_device_node.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DEVICE_NODE_H diff --git a/core/host/include/hdf_device_object.h b/core/host/include/hdf_device_object.h old mode 100755 new mode 100644 index 62732f9c..ec194e46 --- a/core/host/include/hdf_device_object.h +++ b/core/host/include/hdf_device_object.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DEVICE_OBJECT_H diff --git a/core/host/include/hdf_device_token.h b/core/host/include/hdf_device_token.h old mode 100755 new mode 100644 index 851766e5..2f4f24c9 --- a/core/host/include/hdf_device_token.h +++ b/core/host/include/hdf_device_token.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DEVICE_TOKEN_H diff --git a/core/host/include/hdf_driver_loader.h b/core/host/include/hdf_driver_loader.h old mode 100755 new mode 100644 index 3551fed1..e6fbb413 --- a/core/host/include/hdf_driver_loader.h +++ b/core/host/include/hdf_driver_loader.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DRIVER_LOADER_H @@ -51,5 +28,7 @@ struct HdfObject *HdfDriverLoaderCreate(void); 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); #endif /* HDF_DRIVER_LOADER_H */ diff --git a/core/host/include/hdf_observer_record.h b/core/host/include/hdf_observer_record.h old mode 100755 new mode 100644 index 4dd7370d..a8bcbd93 --- a/core/host/include/hdf_observer_record.h +++ b/core/host/include/hdf_observer_record.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_OBSERVER_RECORD_H diff --git a/core/host/include/hdf_service_observer.h b/core/host/include/hdf_service_observer.h old mode 100755 new mode 100644 index 530a09c3..d9a23038 --- a/core/host/include/hdf_service_observer.h +++ b/core/host/include/hdf_service_observer.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_SERVICE_OBSERVER_H diff --git a/core/host/include/hdf_service_subscriber.h b/core/host/include/hdf_service_subscriber.h old mode 100755 new mode 100644 index 3ec9106b..2d2528b0 --- a/core/host/include/hdf_service_subscriber.h +++ b/core/host/include/hdf_service_subscriber.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_SERVICE_SUBSCRIBER_H diff --git a/core/host/include/power_state_token.h b/core/host/include/power_state_token.h old mode 100755 new mode 100644 index c75cdb19..eda268bf --- a/core/host/include/power_state_token.h +++ b/core/host/include/power_state_token.h @@ -1,50 +1,27 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef POWER_STATE_TOKEN_H -#define POWER_STATE_TOKEN_H - -#include "hdf_sref.h" -#include "power_state_token_if.h" - -struct PowerStateToken { - struct IPowerStateToken super; - struct IPowerEventListener *listener; - struct HdfDeviceObject *deviceObject; - struct HdfSRef wakeRef; - HdfPowerState state; -}; - -struct PowerStateToken *PowerStateTokenNewInstance( - struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener); -void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken); - +/* + * 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 POWER_STATE_TOKEN_H +#define POWER_STATE_TOKEN_H + +#include "hdf_sref.h" +#include "power_state_token_if.h" + +struct PowerStateToken { + struct IPowerStateToken super; + struct IPowerEventListener *listener; + struct HdfDeviceObject *deviceObject; + struct HdfSRef wakeRef; + HdfPowerState state; +}; + +struct PowerStateToken *PowerStateTokenNewInstance( + struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener); +void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken); + #endif /* POWER_STATE_TOKEN_H */ \ No newline at end of file diff --git a/core/host/src/devhost_service.c b/core/host/src/devhost_service.c old mode 100755 new mode 100644 index d5f91073..71f1ffd9 --- a/core/host/src/devhost_service.c +++ b/core/host/src/devhost_service.c @@ -1,39 +1,18 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devhost_service.h" #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" @@ -79,12 +58,13 @@ static struct HdfDevice *DevHostServiceGetDevice(struct DevHostService *inst, ui return NULL; } device->hostId = inst->hostId; + device->deviceId = deviceId; HdfSListAdd(&inst->devices, &device->node); } return device; } -static int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo) +int DevHostServiceAddDevice(struct IDevHostService *inst, const struct HdfDeviceInfo *deviceInfo) { int ret = HDF_FAILURE; struct HdfDevice *device = NULL; @@ -116,8 +96,8 @@ static int DevHostServiceAddDevice(struct IDevHostService *inst, const struct Hd return HDF_SUCCESS; error: - if (HdfSListIsEmpty(&hostService->devices)) { - DevHostServiceFreeDevice(hostService, hostService->hostId); + if (!HdfSListIsEmpty(&hostService->devices)) { + DevHostServiceFreeDevice(hostService, deviceInfo->deviceId); } return ret; } @@ -140,7 +120,21 @@ static int DevHostServiceDelDevice(struct IDevHostService *inst, const struct Hd } driverLoader->UnLoadNode(driverLoader, deviceInfo); - if (HdfSListIsEmpty(&hostService->devices)) { + 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); } DevSvcManagerClntRemoveService(deviceInfo->svcName); @@ -157,7 +151,7 @@ static int DevHostServiceStartService(struct IDevHostService *service) return DevmgrServiceClntAttachDeviceHost(hostService->hostId, service); } -static void DevHostServiceConstruct(struct DevHostService *service) +void DevHostServiceConstruct(struct DevHostService *service) { struct IDevHostService *hostServiceIf = &service->super; if (hostServiceIf != NULL) { @@ -169,7 +163,7 @@ static void DevHostServiceConstruct(struct DevHostService *service) } } -static void DevHostServiceDestruct(struct DevHostService *service) +void DevHostServiceDestruct(struct DevHostService *service) { HdfSListFlush(&service->devices, HdfDeviceDelete); HdfServiceObserverDestruct(&service->observer); diff --git a/core/host/src/devmgr_service_clnt.c b/core/host/src/devmgr_service_clnt.c old mode 100755 new mode 100644 index 4991e631..712e2098 --- a/core/host/src/devmgr_service_clnt.c +++ b/core/host/src/devmgr_service_clnt.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devmgr_service_clnt.h" diff --git a/core/host/src/devsvc_manager_clnt.c b/core/host/src/devsvc_manager_clnt.c old mode 100755 new mode 100644 index 8d5a61fd..e3ae2142 --- a/core/host/src/devsvc_manager_clnt.c +++ b/core/host/src/devsvc_manager_clnt.c @@ -1,36 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devsvc_manager_clnt.h" +#include "devmgr_service.h" #include "devsvc_manager.h" +#include "hdf_attribute_manager.h" #include "hdf_base.h" #include "hdf_log.h" #include "hdf_object_manager.h" @@ -46,7 +25,7 @@ int DevSvcManagerClntAddService(const char *svcName, struct HdfDeviceObject *ser } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->AddService == NULL) { + if (serviceManager == NULL || serviceManager->AddService == NULL) { HDF_LOGE("AddService function is not assigned"); return HDF_FAILURE; } @@ -62,7 +41,7 @@ const struct HdfObject *DevSvcManagerClntGetService(const char *svcName) } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->GetService == NULL) { + if (serviceManager == NULL || serviceManager->GetService == NULL) { HDF_LOGE("GetService function is not assigned"); return NULL; } @@ -78,13 +57,39 @@ struct HdfDeviceObject *DevSvcManagerClntGetDeviceObject(const char *svcName) } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->GetObject == NULL) { + if (serviceManager == NULL || serviceManager->GetObject == NULL) { HDF_LOGE("GetObject function is not assigned"); return NULL; } return serviceManager->GetObject(serviceManager, svcName); } +struct HdfDeviceObject *HdfRegisterDevice(const char *moduleName, const char *serviceName) +{ + int ret; + if (!HdfDeviceListAdd(moduleName, serviceName)) { + HDF_LOGE("%s device info add failed!", __func__); + return NULL; + } + ret = DevmgrServiceLoadDevice(serviceName); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s load device %s failed!", __func__, serviceName); + HdfDeviceListDel(moduleName, serviceName); + return NULL; + } + return DevSvcManagerClntGetDeviceObject(serviceName); +} + +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); + } + HdfDeviceListDel(moduleName, serviceName); +} + int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback) { struct DevSvcManagerClnt *devSvcMgrClnt = DevSvcManagerClntGetInstance(); @@ -94,7 +99,7 @@ int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCall } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->SubscribeService == NULL) { + if (serviceManager == NULL || serviceManager->SubscribeService == NULL) { HDF_LOGE("SubscribeService function is not assigned"); return HDF_FAILURE; } @@ -110,7 +115,7 @@ int DevSvcManagerClntUnsubscribeService(const char *svcName) } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->UnsubscribeService == NULL) { + if (serviceManager == NULL || serviceManager->UnsubscribeService == NULL) { HDF_LOGE("UnsubService function is not assigned"); return HDF_FAILURE; } @@ -126,7 +131,7 @@ void DevSvcManagerClntRemoveService(const char *svcName) } struct IDevSvcManager *serviceManager = devSvcMgrClnt->devSvcMgrIf; - if (serviceManager->RemoveService == NULL) { + if (serviceManager == NULL || serviceManager->RemoveService == NULL) { HDF_LOGE("Remove service function is not assigned"); return; } diff --git a/core/host/src/hdf_device.c b/core/host/src/hdf_device.c old mode 100755 new mode 100644 index 15660ddb..b4f27d19 --- a/core/host/src/hdf_device.c +++ b/core/host/src/hdf_device.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_device.h" @@ -53,13 +30,13 @@ static int HdfDeviceAttach(struct IHdfDevice *devInst, struct HdfDeviceNode *dev return nodeIf->LaunchNode(devNode, devInst); } -static void HdfDeviceConstruct(struct HdfDevice *device) +void HdfDeviceConstruct(struct HdfDevice *device) { device->super.Attach = HdfDeviceAttach; HdfSListInit(&device->services); } -static void HdfDeviceDestruct(struct HdfDevice *device) +void HdfDeviceDestruct(struct HdfDevice *device) { HdfSListFlush(&device->services, HdfDeviceNodeDelete); } diff --git a/core/host/src/hdf_device_node.c b/core/host/src/hdf_device_node.c old mode 100755 new mode 100644 index a518cc91..4ccd58a1 --- a/core/host/src/hdf_device_node.c +++ b/core/host/src/hdf_device_node.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_device_node.h" @@ -65,6 +42,7 @@ static int HdfDeviceNodePublishLocalService( static int HdfDeviceNodePublishService( struct HdfDeviceNode *devNode, const struct HdfDeviceInfo *deviceInfo, struct IHdfDevice *device) { + (void)device; int status = HDF_SUCCESS; if (deviceInfo->policy == SERVICE_POLICY_NONE) { HDF_LOGI("policy is %d", SERVICE_POLICY_NONE); @@ -139,7 +117,7 @@ int HdfDeviceNodeAddPowerStateListener( if (devNode->powerToken == NULL) { devNode->powerToken = PowerStateTokenNewInstance(&devNode->deviceObject, listener); } - return (devNode->powerToken == NULL) ? HDF_SUCCESS : HDF_FAILURE; + return (devNode->powerToken != NULL) ? HDF_SUCCESS : HDF_FAILURE; } int HdfDeviceNodePublishPublicService(struct HdfDeviceNode *devNode, const char *svcName) diff --git a/core/host/src/hdf_device_object.c b/core/host/src/hdf_device_object.c old mode 100755 new mode 100644 index 397f448f..2c109ac3 --- a/core/host/src/hdf_device_object.c +++ b/core/host/src/hdf_device_object.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_device_object.h" @@ -120,10 +97,21 @@ void HdfDeviceReleaseWakeLock(struct HdfDeviceObject *deviceObject) } } +bool HdfDeviceSetClass(struct HdfDeviceObject *deviceObject, DeviceClass deviceClass) +{ + if ((deviceObject == NULL) || (deviceClass >= DEVICE_CLASS_MAX) || + (deviceClass < DEVICE_CLASS_DEFAULT)) { + return false; + } + deviceObject->deviceClass = deviceClass; + return true; +} + void HdfDeviceObjectConstruct(struct HdfDeviceObject *deviceObject) { if (deviceObject != NULL) { deviceObject->property = NULL; deviceObject->service = NULL; + deviceObject->deviceClass = DEVICE_CLASS_DEFAULT; } } diff --git a/core/host/src/hdf_device_token.c b/core/host/src/hdf_device_token.c old mode 100755 new mode 100644 index fd8098dd..3d52d26f --- a/core/host/src/hdf_device_token.c +++ b/core/host/src/hdf_device_token.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_device_token.h" diff --git a/core/host/src/hdf_driver_loader.c b/core/host/src/hdf_driver_loader.c old mode 100755 new mode 100644 index f779c3ad..ec9f7801 --- a/core/host/src/hdf_driver_loader.c +++ b/core/host/src/hdf_driver_loader.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_driver_loader.h" @@ -36,10 +13,11 @@ #include "hdf_device_node.h" #include "hdf_log.h" #include "hdf_object_manager.h" +#include "hdf_attribute_manager.h" #define HDF_LOG_TAG driver_loader -static struct HdfDeviceNode *HdfDriverLoaderLoadNode( +struct HdfDeviceNode *HdfDriverLoaderLoadNode( struct IDriverLoader *loader, const struct HdfDeviceInfo *deviceInfo) { struct HdfDriverEntry *driverEntry = NULL; @@ -63,7 +41,7 @@ static struct HdfDeviceNode *HdfDriverLoaderLoadNode( devNode->driverEntry = driverEntry; devNode->deviceInfo = deviceInfo; - devNode->deviceObject.property = HcsGetNodeByMatchAttr(HcsGetRootNode(), deviceInfo->deviceMatchAttr); + devNode->deviceObject.property = HcsGetNodeByMatchAttr(HdfGetRootNode(), deviceInfo->deviceMatchAttr); if (devNode->deviceObject.property == NULL) { HDF_LOGW("Get property is null, match attr is: %s", deviceInfo->deviceMatchAttr); } diff --git a/core/host/src/hdf_observer_record.c b/core/host/src/hdf_observer_record.c old mode 100755 new mode 100644 index b0dc8847..d75f5c95 --- a/core/host/src/hdf_observer_record.c +++ b/core/host/src/hdf_observer_record.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_observer_record.h" diff --git a/core/host/src/hdf_service_observer.c b/core/host/src/hdf_service_observer.c old mode 100755 new mode 100644 index c68089a1..52bafee2 --- a/core/host/src/hdf_service_observer.c +++ b/core/host/src/hdf_service_observer.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_service_observer.h" diff --git a/core/host/src/hdf_service_subscriber.c b/core/host/src/hdf_service_subscriber.c old mode 100755 new mode 100644 index 14b31c86..6307977e --- a/core/host/src/hdf_service_subscriber.c +++ b/core/host/src/hdf_service_subscriber.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_mem.h" diff --git a/core/host/src/power_state_token.c b/core/host/src/power_state_token.c old mode 100755 new mode 100644 index 441b42a4..41702590 --- a/core/host/src/power_state_token.c +++ b/core/host/src/power_state_token.c @@ -1,159 +1,136 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "power_state_token.h" -#include "devmgr_service_clnt.h" -#include "hdf_device_desc.h" -#include "hdf_slist.h" -#include "osal_mem.h" - -static void PowerStateTokenAcqureWakeLock(struct IPowerStateToken *token) -{ - struct HdfSRef *sref = NULL; - struct PowerStateToken *stateToken = (struct PowerStateToken *)token; - if (stateToken == NULL) { - return; - } - sref = (struct HdfSRef *)&stateToken->wakeRef; - if ((sref != NULL) && (sref->Acquire != NULL)) { - sref->Acquire(sref); - } -} - -static void PowerStateTokenReleaseWakeLock(struct IPowerStateToken *token) -{ - struct HdfSRef *sref = NULL; - struct PowerStateToken *stateToken = (struct PowerStateToken *)token; - if (stateToken == NULL) { - return; - } - sref = (struct HdfSRef *)&stateToken->wakeRef; - if ((sref != NULL) && (sref->Release != NULL)) { - sref->Release(sref); - } -} - -static void PowerStateTokenOnFirstAcquire(struct HdfSRef *sref) -{ - if (sref == NULL) { - return; - } - struct PowerStateToken *stateToken = (struct PowerStateToken *)HDF_SLIST_CONTAINER_OF( - struct HdfSRef, sref, struct PowerStateToken, wakeRef); - if (stateToken->state != POWER_STATE_ACTIVE) { - struct IDevmgrService *devMgrSvcIf = NULL; - struct IPowerEventListener* listener = stateToken->listener; - struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); - if (inst == NULL) { - return; - } - devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; - if (devMgrSvcIf->AcquireWakeLock == NULL) { - return; - } - devMgrSvcIf->AcquireWakeLock(devMgrSvcIf, &stateToken->super); - if (stateToken->state == POWER_STATE_INACTIVE) { - if ((listener != NULL) && (listener->Resume != NULL)) { - listener->Resume(stateToken->deviceObject); - } - } - stateToken->state = POWER_STATE_ACTIVE; - } -} - -static void PowerStateTokenOnLastRelease(struct HdfSRef *sref) -{ - if (sref == NULL) { - return; - } - struct PowerStateToken *stateToken = (struct PowerStateToken *)HDF_SLIST_CONTAINER_OF( - struct HdfSRef, sref, struct PowerStateToken, wakeRef); - if (stateToken->state == POWER_STATE_ACTIVE) { - struct IDevmgrService *devMgrSvcIf = NULL; - struct IPowerEventListener *listener = stateToken->listener; - struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); - if (inst == NULL) { - return; - } - devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; - if ((devMgrSvcIf == NULL) || (devMgrSvcIf->AcquireWakeLock == NULL)) { - return; - } - devMgrSvcIf->ReleaseWakeLock(devMgrSvcIf, &stateToken->super); - if ((listener != NULL) && (listener->Suspend != NULL)) { - listener->Suspend(stateToken->deviceObject); - } - stateToken->state = POWER_STATE_INACTIVE; - } -} - -static void PowerStateTokenConstruct( - struct PowerStateToken *powerStateToken, struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) -{ - struct IPowerStateToken *tokenIf = (struct IPowerStateToken *)powerStateToken; - struct IHdfSRefListener *srefListener = (struct IHdfSRefListener *)OsalMemCalloc(sizeof(struct IHdfSRefListener)); - if (srefListener == NULL) { - return; - } - - tokenIf->AcquireWakeLock = PowerStateTokenAcqureWakeLock; - tokenIf->ReleaseWakeLock = PowerStateTokenReleaseWakeLock; - - srefListener->OnFirstAcquire = PowerStateTokenOnFirstAcquire; - srefListener->OnLastRelease = PowerStateTokenOnLastRelease; - - powerStateToken->state = POWER_STATE_IDLE; - powerStateToken->listener = listener; - powerStateToken->deviceObject = deviceObject; - HdfSRefConstruct(&powerStateToken->wakeRef, srefListener); -} - -struct PowerStateToken *PowerStateTokenNewInstance( - struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) -{ - struct PowerStateToken *stateToken = - (struct PowerStateToken *)OsalMemCalloc(sizeof(struct PowerStateToken)); - if (stateToken != NULL) { - PowerStateTokenConstruct(stateToken, deviceObject, listener); - } - return stateToken; -} - -void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken) -{ - if (stateToken != NULL) { - if (stateToken->wakeRef.listener != NULL) { - OsalMemFree(stateToken->wakeRef.listener); - stateToken->wakeRef.listener = NULL; - } - OsalMemFree(stateToken); - } -} +/* + * 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 "power_state_token.h" +#include "devmgr_service_clnt.h" +#include "hdf_device_desc.h" +#include "hdf_slist.h" +#include "osal_mem.h" + +static void PowerStateTokenAcqureWakeLock(struct IPowerStateToken *token) +{ + struct HdfSRef *sref = NULL; + struct PowerStateToken *stateToken = (struct PowerStateToken *)token; + if (stateToken == NULL) { + return; + } + sref = (struct HdfSRef *)&stateToken->wakeRef; + if ((sref != NULL) && (sref->Acquire != NULL)) { + sref->Acquire(sref); + } +} + +static void PowerStateTokenReleaseWakeLock(struct IPowerStateToken *token) +{ + struct HdfSRef *sref = NULL; + struct PowerStateToken *stateToken = (struct PowerStateToken *)token; + if (stateToken == NULL) { + return; + } + sref = (struct HdfSRef *)&stateToken->wakeRef; + if ((sref != NULL) && (sref->Release != NULL)) { + sref->Release(sref); + } +} + +static void PowerStateTokenOnFirstAcquire(struct HdfSRef *sref) +{ + if (sref == NULL) { + return; + } + struct PowerStateToken *stateToken = (struct PowerStateToken *)HDF_SLIST_CONTAINER_OF( + struct HdfSRef, sref, struct PowerStateToken, wakeRef); + if (stateToken->state != POWER_STATE_ACTIVE) { + struct IDevmgrService *devMgrSvcIf = NULL; + struct IPowerEventListener* listener = stateToken->listener; + struct DevmgrServiceClnt *inst = DevmgrServiceClntGetInstance(); + if (inst == NULL) { + return; + } + devMgrSvcIf = (struct IDevmgrService *)inst->devMgrSvcIf; + if (devMgrSvcIf == 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) +{ + struct IPowerStateToken *tokenIf = &powerStateToken->super; + struct IHdfSRefListener *srefListener = (struct IHdfSRefListener *)OsalMemCalloc(sizeof(struct IHdfSRefListener)); + if (srefListener == NULL) { + return; + } + + tokenIf->AcquireWakeLock = PowerStateTokenAcqureWakeLock; + tokenIf->ReleaseWakeLock = PowerStateTokenReleaseWakeLock; + + srefListener->OnFirstAcquire = PowerStateTokenOnFirstAcquire; + srefListener->OnLastRelease = PowerStateTokenOnLastRelease; + + powerStateToken->state = POWER_STATE_IDLE; + powerStateToken->listener = listener; + powerStateToken->deviceObject = deviceObject; + HdfSRefConstruct(&powerStateToken->wakeRef, srefListener); +} + +struct PowerStateToken *PowerStateTokenNewInstance( + struct HdfDeviceObject *deviceObject, struct IPowerEventListener *listener) +{ + struct PowerStateToken *stateToken = + (struct PowerStateToken *)OsalMemCalloc(sizeof(struct PowerStateToken)); + if (stateToken != NULL) { + PowerStateTokenConstruct(stateToken, deviceObject, listener); + } + return stateToken; +} + +void PowerStateTokenFreeInstance(struct PowerStateToken *stateToken) +{ + if (stateToken != NULL) { + if (stateToken->wakeRef.listener != NULL) { + OsalMemFree(stateToken->wakeRef.listener); + stateToken->wakeRef.listener = NULL; + } + OsalMemFree(stateToken); + } +} diff --git a/core/manager/include/devhost_service_clnt.h b/core/manager/include/devhost_service_clnt.h old mode 100755 new mode 100644 index d38c98b3..3a641297 --- a/core/manager/include/devhost_service_clnt.h +++ b/core/manager/include/devhost_service_clnt.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVHOST_SERVICE_CLNT_H @@ -40,6 +17,7 @@ struct DevHostServiceClnt { struct HdfSList devices; struct HdfSList *deviceInfos; struct IDevHostService *hostService; + uint16_t devCount; uint16_t hostId; int hostPid; const char *hostName; diff --git a/core/manager/include/device_token_clnt.h b/core/manager/include/device_token_clnt.h old mode 100755 new mode 100644 index 047ed729..818bba94 --- a/core/manager/include/device_token_clnt.h +++ b/core/manager/include/device_token_clnt.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVICE_TOKEN_CLNT_H diff --git a/core/manager/include/devmgr_service.h b/core/manager/include/devmgr_service.h old mode 100755 new mode 100644 index 2fd02601..1d255d18 --- a/core/manager/include/devmgr_service.h +++ b/core/manager/include/devmgr_service.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVICE_MANAGER_SERVICE_H @@ -43,11 +20,13 @@ struct DevmgrService { }; int DevmgrServiceStartService(struct IDevmgrService *inst); +bool DevmgrServiceConstruct(struct DevmgrService *inst); struct HdfObject *DevmgrServiceCreate(void); void DevmgrServiceRelease(struct HdfObject *object); struct IDevmgrService *DevmgrServiceGetInstance(void); int DevmgrServiceLoadDevice(const char *svcName); int DevmgrServiceUnLoadDevice(const char *svcName); +int32_t DevmgrServiceLoadLeftDriver(struct DevmgrService *devMgrSvc); void DevmgrServiceAcquireWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf); void DevmgrServiceReleaseWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf); diff --git a/core/manager/include/devsvc_manager.h b/core/manager/include/devsvc_manager.h old mode 100755 new mode 100644 index 65829a59..658fd49e --- a/core/manager/include/devsvc_manager.h +++ b/core/manager/include/devsvc_manager.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVICE_SERVICE_MANAGER_H @@ -45,6 +22,7 @@ struct DevSvcManager { }; struct HdfObject *DevSvcManagerCreate(void); +bool DevSvcManagerConstruct(struct DevSvcManager *inst); void DevSvcManagerRelease(struct HdfObject *object); struct IDevSvcManager *DevSvcManagerGetInstance(void); int DevSvcManagerAddService(struct IDevSvcManager *manager, const char *svcName, struct HdfDeviceObject *service); diff --git a/core/manager/include/devsvc_manager_stub.h b/core/manager/include/devsvc_manager_stub.h deleted file mode 100755 index ef8b7856..00000000 --- a/core/manager/include/devsvc_manager_stub.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef DEVSVC_MANAGER_STUB_H -#define DEVSVC_MANAGER_STUB_H - -#include "hdf_device_desc.h" - -int DevSvcManagerClntSubscribeService(const char *svcName, struct SubscriberCallback callback); -int DevSvcManagerClntUnsubscribeService(const char *svcName); - -#endif /* DEVSVC_MANAGER_STUB_H */ - diff --git a/core/manager/include/hdf_driver_installer.h b/core/manager/include/hdf_driver_installer.h old mode 100755 new mode 100644 index fed4dfb9..d21ab365 --- a/core/manager/include/hdf_driver_installer.h +++ b/core/manager/include/hdf_driver_installer.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DRIVER_INSTALLER_H diff --git a/core/manager/include/hdf_host_info.h b/core/manager/include/hdf_host_info.h old mode 100755 new mode 100644 index 6fe5e57d..a607e412 --- a/core/manager/include/hdf_host_info.h +++ b/core/manager/include/hdf_host_info.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_HOST_INFO_H diff --git a/core/manager/include/power_state_manager.h b/core/manager/include/power_state_manager.h old mode 100755 new mode 100644 index 186db047..0cf87de3 --- a/core/manager/include/power_state_manager.h +++ b/core/manager/include/power_state_manager.h @@ -1,48 +1,25 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef POWER_STATE_MANAGER_H -#define POWER_STATE_MANAGER_H - -#include "hdf_sref.h" -#include "hdf_slist.h" -#include "power_state_token_if.h" - -struct PowerStateManager { - struct HdfSRef wakeRef; - struct HdfSList tokens; - void (*AcquireWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); - void (*ReleaseWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); -}; - -struct PowerStateManager *PowerStateManagerGetInstance(void); - +/* + * 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 POWER_STATE_MANAGER_H +#define POWER_STATE_MANAGER_H + +#include "hdf_sref.h" +#include "hdf_slist.h" +#include "power_state_token_if.h" + +struct PowerStateManager { + struct HdfSRef wakeRef; + struct HdfSList tokens; + void (*AcquireWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); + void (*ReleaseWakeLock)(struct PowerStateManager *, struct IPowerStateToken *); +}; + +struct PowerStateManager *PowerStateManagerGetInstance(void); + #endif /* POWER_STATE_MANAGER_H */ \ No newline at end of file diff --git a/core/manager/include/power_state_token_clnt.h b/core/manager/include/power_state_token_clnt.h old mode 100755 new mode 100644 index cd963cbb..ba700d8b --- a/core/manager/include/power_state_token_clnt.h +++ b/core/manager/include/power_state_token_clnt.h @@ -1,48 +1,25 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef POWER_STATE_TOKEN_CLNT_H -#define POWER_STATE_TOKEN_CLNT_H - -#include "hdf_slist.h" -#include "power_state_token_if.h" - -struct PowerStateTokenClnt { - struct HdfSListNode entry; - HdfPowerState powerState; - struct IPowerStateToken* tokenIf; -}; - -struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf); -void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt); - +/* + * 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 POWER_STATE_TOKEN_CLNT_H +#define POWER_STATE_TOKEN_CLNT_H + +#include "hdf_slist.h" +#include "power_state_token_if.h" + +struct PowerStateTokenClnt { + struct HdfSListNode entry; + HdfPowerState powerState; + struct IPowerStateToken* tokenIf; +}; + +struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf); +void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt); + #endif /* POWER_STATE_TOKEN_CLNT_H */ \ No newline at end of file diff --git a/core/manager/src/devhost_service_clnt.c b/core/manager/src/devhost_service_clnt.c old mode 100755 new mode 100644 index 5d9d5262..ee31bab4 --- a/core/manager/src/devhost_service_clnt.c +++ b/core/manager/src/devhost_service_clnt.c @@ -1,36 +1,14 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_token_clnt.h" #include "devhost_service_clnt.h" +#include "devmgr_service_start.h" #include "hdf_base.h" #include "hdf_driver_installer.h" #include "hdf_log.h" @@ -57,7 +35,11 @@ int DevHostServiceClntInstallDriver(struct DevHostServiceClnt *hostClnt) HdfSListIteratorInit(&it, hostClnt->deviceInfos); while (HdfSListIteratorHasNext(&it)) { deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&it); - if ((deviceInfo == NULL) || (deviceInfo->preload != DEVICE_PRELOAD_ENABLE)) { + if ((deviceInfo == NULL) || (deviceInfo->preload == DEVICE_PRELOAD_DISABLE)) { + continue; + } + if ((DeviceManagerIsQuickLoad() == DEV_MGR_QUICK_LOAD) && + (deviceInfo->preload == DEVICE_PRELOAD_ENABLE_STEP2)) { continue; } ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); @@ -80,6 +62,7 @@ struct DevHostServiceClnt *DevHostServiceClntNewInstance(uint16_t hostId, const if (hostClnt != NULL) { hostClnt->hostId = hostId; hostClnt->hostName = hostName; + hostClnt->devCount = 0; DevHostServiceClntConstruct(hostClnt); } return hostClnt; diff --git a/core/manager/src/device_token_clnt.c b/core/manager/src/device_token_clnt.c old mode 100755 new mode 100644 index f90d7f5a..e912a5c8 --- a/core/manager/src/device_token_clnt.c +++ b/core/manager/src/device_token_clnt.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_token_clnt.h" diff --git a/core/manager/src/devmgr_service.c b/core/manager/src/devmgr_service.c old mode 100755 new mode 100644 index d6d5d0c0..3472cf9e --- a/core/manager/src/devmgr_service.c +++ b/core/manager/src/devmgr_service.c @@ -1,36 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devmgr_service.h" -#include #include "devhost_service_clnt.h" #include "device_token_clnt.h" #include "hdf_attribute_manager.h" @@ -47,16 +23,18 @@ static int DevmgrServiceActiveDevice(struct DevHostServiceClnt *hostClnt, struct HdfDeviceInfo *deviceInfo, bool isLoad) { struct IDevHostService *devHostSvcIf = (struct IDevHostService *)hostClnt->hostService; - if (isLoad) { + if (isLoad && (deviceInfo->preload != DEVICE_PRELOAD_ENABLE)) { int ret = devHostSvcIf->AddDevice(devHostSvcIf, deviceInfo); if (ret == HDF_SUCCESS) { deviceInfo->preload = DEVICE_PRELOAD_ENABLE; } return ret; - } else { + } else if (!isLoad && (deviceInfo->preload != DEVICE_PRELOAD_DISABLE)) { devHostSvcIf->DelDevice(devHostSvcIf, deviceInfo); deviceInfo->preload = DEVICE_PRELOAD_DISABLE; return HDF_SUCCESS; + } else { + return HDF_FAILURE; } } @@ -68,6 +46,31 @@ static int DevmgrServiceFindAndActiveDevice(const char *svcName, bool isLoad) struct DevHostServiceClnt *hostClnt = NULL; struct DevmgrService *devMgrSvc = (struct DevmgrService *)DevmgrServiceGetInstance(); if (devMgrSvc == NULL || svcName == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + HdfSListIteratorInit(&itHost, &devMgrSvc->hosts); + while (HdfSListIteratorHasNext(&itHost)) { + hostClnt = (struct DevHostServiceClnt *)HdfSListIteratorNext(&itHost); + HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); + while (HdfSListIteratorHasNext(&itDeviceInfo)) { + deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); + if (strcmp(deviceInfo->svcName, svcName) == 0) { + return DevmgrServiceActiveDevice(hostClnt, deviceInfo, isLoad); + } + } + } + return HDF_FAILURE; +} + +int32_t DevmgrServiceLoadLeftDriver(struct DevmgrService *devMgrSvc) +{ + int32_t ret; + struct HdfSListIterator itHost; + struct HdfSListIterator itDeviceInfo; + struct HdfDeviceInfo *deviceInfo = NULL; + struct DevHostServiceClnt *hostClnt = NULL; + if (devMgrSvc == NULL) { return HDF_FAILURE; } @@ -77,15 +80,18 @@ static int DevmgrServiceFindAndActiveDevice(const char *svcName, bool isLoad) HdfSListIteratorInit(&itDeviceInfo, hostClnt->deviceInfos); while (HdfSListIteratorHasNext(&itDeviceInfo)) { deviceInfo = (struct HdfDeviceInfo *)HdfSListIteratorNext(&itDeviceInfo); - if ((strcmp(deviceInfo->svcName, svcName) == 0) && (deviceInfo->preload == DEVICE_PRELOAD_DISABLE)) { - return DevmgrServiceActiveDevice(hostClnt, deviceInfo, isLoad); + 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("Find %s deviceInfo failed, active is: %u", svcName, isLoad); - return HDF_FAILURE; + return HDF_SUCCESS; } + int DevmgrServiceLoadDevice(const char *svcName) { return DevmgrServiceFindAndActiveDevice(svcName, true); @@ -156,6 +162,7 @@ static int DevmgrServiceAttachDeviceHost( HDF_LOGE("Get device list failed"); return HDF_FAILURE; } + hostClnt->devCount = HdfSListCount(hostClnt->deviceInfos); hostClnt->hostService = hostService; return DevHostServiceClntInstallDriver(hostClnt); } @@ -174,8 +181,8 @@ static int DevmgrServiceStartDeviceHosts(struct DevmgrService *inst) } HdfSListInit(&hostList); if (!HdfAttributeManagerGetHostList(&hostList)) { - HDF_LOGW("Get device host list failed"); - return HDF_FAILURE; + HDF_LOGW("%s get host list is null", __func__); + return HDF_SUCCESS; } HdfSListIteratorInit(&it, &hostList); while (HdfSListIteratorHasNext(&it)) { @@ -207,7 +214,7 @@ int DevmgrServiceStartService(struct IDevmgrService *inst) return DevmgrServiceStartDeviceHosts(dmService); } -static bool DevmgrServiceConstruct(struct DevmgrService *inst) +bool DevmgrServiceConstruct(struct DevmgrService *inst) { if (OsalMutexInit(&inst->devMgrMutex) != HDF_SUCCESS) { HDF_LOGE("%s mutex init failed", __func__); @@ -260,6 +267,7 @@ void DevmgrServiceRelease(struct HdfObject *object) void DevmgrServiceAcquireWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf) { + (void)inst; struct PowerStateManager *stateManager = PowerStateManagerGetInstance(); if ((stateManager != NULL) && (stateManager->AcquireWakeLock != NULL)) { stateManager->AcquireWakeLock(stateManager, tokenIf); @@ -268,6 +276,7 @@ void DevmgrServiceAcquireWakeLock(struct IDevmgrService *inst, struct IPowerStat void DevmgrServiceReleaseWakeLock(struct IDevmgrService *inst, struct IPowerStateToken *tokenIf) { + (void)inst; struct PowerStateManager *stateManager = PowerStateManagerGetInstance(); if ((stateManager != NULL) && (stateManager->ReleaseWakeLock != NULL)) { stateManager->ReleaseWakeLock(stateManager, tokenIf); diff --git a/core/manager/src/devsvc_manager.c b/core/manager/src/devsvc_manager.c old mode 100755 new mode 100644 index 4cdb93f4..7feac34c --- a/core/manager/src/devsvc_manager.c +++ b/core/manager/src/devsvc_manager.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devsvc_manager.h" @@ -82,8 +59,7 @@ int DevSvcManagerAddService(struct IDevSvcManager *inst, const char *svcName, st OsalMutexLock(&devSvcManager->mutex); HdfSListAdd(&devSvcManager->services, &record->entry); OsalMutexUnlock(&devSvcManager->mutex); - return HdfServiceObserverPublishService( - &devSvcManager->observer, svcName, 0, SERVICE_POLICY_PUBLIC, (struct HdfObject *)service->service); + return HDF_SUCCESS; } int DevSvcManagerSubscribeService(struct IDevSvcManager *inst, const char *svcName, struct SubscriberCallback callBack) @@ -94,11 +70,6 @@ int DevSvcManagerSubscribeService(struct IDevSvcManager *inst, const char *svcNa return ret; } - ret = HdfServiceObserverSubscribeService(&devSvcMgr->observer, svcName, 0, callBack); - if (ret != HDF_SUCCESS) { - return ret; - } - struct HdfObject *deviceService = DevSvcManagerGetService(inst, svcName); if (deviceService != NULL) { if (callBack.OnServiceConnected != NULL) { @@ -110,17 +81,6 @@ int DevSvcManagerSubscribeService(struct IDevSvcManager *inst, const char *svcNa return DevmgrServiceLoadDevice(svcName); } -int DevSvcManagerUnsubscribeService(struct IDevSvcManager *inst, const char *svcName) -{ - struct DevSvcManager *devSvcMgr = (struct DevSvcManager *)inst; - if (devSvcMgr == NULL) { - return HDF_FAILURE; - } - HdfServiceObserverRemoveRecord(&devSvcMgr->observer, svcName); - return HDF_SUCCESS; -} - - void DevSvcManagerRemoveService(struct IDevSvcManager *inst, const char *svcName) { struct DevSvcManager *devSvcManager = (struct DevSvcManager *)inst; @@ -147,7 +107,6 @@ struct HdfDeviceObject *DevSvcManagerGetObject(struct IDevSvcManager *inst, cons if (serviceRecord != NULL) { return serviceRecord->value; } - HDF_LOGE("Get object failed, serviceRecord is null, svcName is %s", svcName); return NULL; } @@ -155,18 +114,21 @@ struct HdfObject *DevSvcManagerGetService(struct IDevSvcManager *inst, const cha { struct HdfDeviceObject *deviceObject = DevSvcManagerGetObject(inst, svcName); if (deviceObject == NULL) { - HDF_LOGE("Get service failed"); return NULL; } return (struct HdfObject *)deviceObject->service; } -static bool DevSvcManagerConstruct(struct DevSvcManager *inst) +bool DevSvcManagerConstruct(struct DevSvcManager *inst) { + if (inst == NULL) { + HDF_LOGE("%s: inst is null!", __func__); + return false; + } struct IDevSvcManager *devSvcMgrIf = &inst->super; devSvcMgrIf->AddService = DevSvcManagerAddService; devSvcMgrIf->SubscribeService = DevSvcManagerSubscribeService; - devSvcMgrIf->UnsubscribeService = DevSvcManagerUnsubscribeService; + devSvcMgrIf->UnsubscribeService = NULL; devSvcMgrIf->RemoveService = DevSvcManagerRemoveService; devSvcMgrIf->GetService = DevSvcManagerGetService; devSvcMgrIf->GetObject = DevSvcManagerGetObject; diff --git a/core/manager/src/hdf_driver_installer.c b/core/manager/src/hdf_driver_installer.c old mode 100755 new mode 100644 index b199b7fe..df91b52a --- a/core/manager/src/hdf_driver_installer.c +++ b/core/manager/src/hdf_driver_installer.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_driver_installer.h" diff --git a/core/manager/src/hdf_host_info.c b/core/manager/src/hdf_host_info.c old mode 100755 new mode 100644 index 70e9126a..cf5b79c6 --- a/core/manager/src/hdf_host_info.c +++ b/core/manager/src/hdf_host_info.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_host_info.h" diff --git a/core/manager/src/power_state_manager.c b/core/manager/src/power_state_manager.c old mode 100755 new mode 100644 index 700453c7..99e02f50 --- a/core/manager/src/power_state_manager.c +++ b/core/manager/src/power_state_manager.c @@ -1,107 +1,84 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "power_state_manager.h" -#include "hdf_object_manager.h" -#include "power_state_token_clnt.h" - -static struct PowerStateTokenClnt *PowerStateManagerGetStateTokenClnt( - struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) -{ - struct HdfSListIterator it; - if (inst == NULL) { - return NULL; - } - HdfSListIteratorInit(&it, &inst->tokens); - while (HdfSListIteratorHasNext(&it)) { - struct PowerStateTokenClnt *tokenClnt = - (struct PowerStateTokenClnt *)HdfSListIteratorNext(&it); - if (tokenClnt->tokenIf == tokenIf) { - return tokenClnt; - } - } - return NULL; -} - -static void PowerStateManagerAcquireWakeLock( - struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) -{ - if (inst == NULL) { - return; - } - struct HdfSRef *sref = &inst->wakeRef; - struct PowerStateTokenClnt *stateTokeClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); - if (stateTokeClnt == NULL) { - return; - } - stateTokeClnt->powerState = POWER_STATE_ACTIVE; - if (sref->Acquire != NULL) { - sref->Acquire(sref); - } -} - -static void PowerStateManagerReleaseWakeLock( - struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) -{ - struct HdfSRef *sref = NULL; - struct PowerStateTokenClnt *stateTokeClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); - if (inst == NULL || stateTokeClnt == NULL) { - return; - } - stateTokeClnt->powerState = POWER_STATE_INACTIVE; - sref = &inst->wakeRef; - if (sref->Release != NULL) { - sref->Release(sref); - } -} - -static void PowerStateManagerConstruct(struct PowerStateManager *inst) -{ - // not support system acquire and release - static struct IHdfSRefListener wakeLockRefListener = { - .OnFirstAcquire = NULL, - .OnLastRelease = NULL, - }; - - inst->AcquireWakeLock = PowerStateManagerAcquireWakeLock; - inst->ReleaseWakeLock = PowerStateManagerReleaseWakeLock; - HdfSListInit(&inst->tokens); - HdfSRefConstruct(&inst->wakeRef, &wakeLockRefListener); -} - -struct PowerStateManager *PowerStateManagerGetInstance() -{ - static struct PowerStateManager powerStateManager = { 0 }; - if (powerStateManager.AcquireWakeLock == NULL) { - PowerStateManagerConstruct(&powerStateManager); - } - return &powerStateManager; -} +/* + * 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 "power_state_manager.h" +#include "hdf_object_manager.h" +#include "power_state_token_clnt.h" + +static struct PowerStateTokenClnt *PowerStateManagerGetStateTokenClnt( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + struct HdfSListIterator it; + if (inst == NULL) { + return NULL; + } + HdfSListIteratorInit(&it, &inst->tokens); + while (HdfSListIteratorHasNext(&it)) { + struct PowerStateTokenClnt *tokenClnt = + (struct PowerStateTokenClnt *)HdfSListIteratorNext(&it); + if (tokenClnt->tokenIf == tokenIf) { + return tokenClnt; + } + } + return NULL; +} + +static void PowerStateManagerAcquireWakeLock( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + if (inst == NULL) { + return; + } + struct HdfSRef *sref = &inst->wakeRef; + struct PowerStateTokenClnt *stateTokenClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); + if (stateTokenClnt == NULL) { + return; + } + stateTokenClnt->powerState = POWER_STATE_ACTIVE; + if (sref->Acquire != NULL) { + sref->Acquire(sref); + } +} + +static void PowerStateManagerReleaseWakeLock( + struct PowerStateManager *inst, struct IPowerStateToken *tokenIf) +{ + struct HdfSRef *sref = NULL; + struct PowerStateTokenClnt *stateTokenClnt = PowerStateManagerGetStateTokenClnt(inst, tokenIf); + if (inst == NULL || stateTokenClnt == NULL) { + return; + } + stateTokenClnt->powerState = POWER_STATE_INACTIVE; + sref = &inst->wakeRef; + if (sref->Release != NULL) { + sref->Release(sref); + } +} + +static void PowerStateManagerConstruct(struct PowerStateManager *inst) +{ + // not support system acquire and release + static struct IHdfSRefListener wakeLockRefListener = { + .OnFirstAcquire = NULL, + .OnLastRelease = NULL, + }; + + inst->AcquireWakeLock = PowerStateManagerAcquireWakeLock; + inst->ReleaseWakeLock = PowerStateManagerReleaseWakeLock; + HdfSListInit(&inst->tokens); + HdfSRefConstruct(&inst->wakeRef, &wakeLockRefListener); +} + +struct PowerStateManager *PowerStateManagerGetInstance() +{ + static struct PowerStateManager powerStateManager = { 0 }; + if (powerStateManager.AcquireWakeLock == NULL) { + PowerStateManagerConstruct(&powerStateManager); + } + return &powerStateManager; +} diff --git a/core/manager/src/power_state_token_clnt.c b/core/manager/src/power_state_token_clnt.c old mode 100755 new mode 100644 index ee5dac31..31eedb88 --- a/core/manager/src/power_state_token_clnt.c +++ b/core/manager/src/power_state_token_clnt.c @@ -1,57 +1,34 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "power_state_token_clnt.h" -#include "osal_mem.h" - -static void PowerStateTokenClntConstruct(struct PowerStateTokenClnt *clnt, struct IPowerStateToken *tokenIf) -{ - clnt->tokenIf = tokenIf; - clnt->powerState = POWER_STATE_INACTIVE; -} - -struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf) -{ - struct PowerStateTokenClnt *tokenClnt = - (struct PowerStateTokenClnt *)OsalMemCalloc(sizeof(struct PowerStateTokenClnt)); - if (tokenClnt != NULL) { - PowerStateTokenClntConstruct(tokenClnt, tokenIf); - return tokenClnt; - } - return tokenClnt; -} - -void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt) -{ - if (tokenClnt != NULL) { - OsalMemFree(tokenClnt); - } -} +/* + * 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 "power_state_token_clnt.h" +#include "osal_mem.h" + +static void PowerStateTokenClntConstruct(struct PowerStateTokenClnt *clnt, struct IPowerStateToken *tokenIf) +{ + clnt->tokenIf = tokenIf; + clnt->powerState = POWER_STATE_INACTIVE; +} + +struct PowerStateTokenClnt *PowerStateTokenClntNewInstance(struct IPowerStateToken *tokenIf) +{ + struct PowerStateTokenClnt *tokenClnt = + (struct PowerStateTokenClnt *)OsalMemCalloc(sizeof(struct PowerStateTokenClnt)); + if (tokenClnt != NULL) { + PowerStateTokenClntConstruct(tokenClnt, tokenIf); + return tokenClnt; + } + return tokenClnt; +} + +void PowerStateTokenClntFreeInstance(struct PowerStateTokenClnt *tokenClnt) +{ + if (tokenClnt != NULL) { + OsalMemFree(tokenClnt); + } +} diff --git a/core/manager/test/unittest/common/hdf_ioservice_test.cpp b/core/manager/test/unittest/common/hdf_ioservice_test.cpp new file mode 100644 index 00000000..0542ab9c --- /dev/null +++ b/core/manager/test/unittest/common/hdf_ioservice_test.cpp @@ -0,0 +1,598 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service.h" +#include "osal_time.h" +#include "sample_driver_test.h" +#include "hdf_log.h" + +using namespace testing::ext; + +struct Eventlistener { + struct HdfDevEventlistener listener; + int32_t eventCount; +}; + +class IoServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + static int OnDevEventReceived(struct HdfDevEventlistener *listener, struct HdfIoService *service, uint32_t id, + struct HdfSBuf *data); + + static struct Eventlistener listener0; + static struct Eventlistener listener1; + const char *testSvcName = SAMPLE_SERVICE; + const int eventWaitTimeUs = (50 * 1000); + static int eventCount; +}; + +int IoServiceTest::eventCount = 0; + +struct Eventlistener IoServiceTest::listener0; +struct Eventlistener IoServiceTest::listener1; + +void IoServiceTest::SetUpTestCase() +{ + listener0.listener.onReceive = OnDevEventReceived; + listener0.listener.priv = (void *)"listener0"; + + listener1.listener.onReceive = OnDevEventReceived; + listener1.listener.priv = (void *)"listener1"; +} + +void IoServiceTest::TearDownTestCase() {} + +void IoServiceTest::SetUp() +{ + listener0.eventCount = 0; + listener1.eventCount = 0; + eventCount = 0; +} + +void IoServiceTest::TearDown() {} + +int IoServiceTest::OnDevEventReceived(struct HdfDevEventlistener *listener, struct HdfIoService *service, uint32_t id, + struct HdfSBuf *data) +{ + OsalTimespec time; + OsalGetTime(&time); + 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"); + return 0; + } + struct Eventlistener *l = CONTAINER_OF(listener, struct Eventlistener, listener); + l->eventCount++; + HDF_LOGE("%s: dev event received: %d %s", (char *)service->priv, id, string); + return 0; +} + +static int SendEvent(struct HdfIoService *serv, const char *eventData) +{ + OsalTimespec time; + OsalGetTime(&time); + + int ret; + struct HdfSBuf *data = HdfSBufObtainDefaultSize(); + if (data == nullptr) { + HDF_LOGE("fail to obtain sbuf data"); + return HDF_FAILURE; + } + + struct HdfSBuf *reply = HdfSBufObtainDefaultSize(); + if (reply == nullptr) { + HDF_LOGE("fail to obtain sbuf reply"); + HdfSBufRecycle(data); + return HDF_DEV_ERR_NO_MEMORY; + } + + do { + if (!HdfSbufWriteString(data, eventData)) { + HDF_LOGE("fail to write sbuf"); + ret = HDF_FAILURE; + break; + } + + ret = serv->dispatcher->Dispatch(&serv->object, SAMPLE_DRIVER_SENDEVENT_SINGLE_DEVICE, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("fail to send service call"); + break; + } + + int replyData = 0; + if (!HdfSbufReadInt32(reply, &replyData)) { + HDF_LOGE("fail to get service call reply"); + ret = HDF_ERR_INVALID_OBJECT; + } else if (replyData != INT32_MAX) { + HDF_LOGE("service call reply check fail, replyData=0x%x", replyData); + ret = HDF_ERR_INVALID_OBJECT; + } + HDF_LOGE("send event finish at %llu.%llu", time.sec, time.usec); + } while (0); + + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return ret; +} + +/* * + * @tc.name: HdfIoService001 + * @tc.desc: service bind test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService001, TestSize.Level0) +{ + struct HdfIoService *testServ = HdfIoServiceBind(testSvcName); + ASSERT_NE(testServ, nullptr); + HdfIoServiceRecycle(testServ); +} + +/* * + * @tc.name: HdfIoService002 + * @tc.desc: service group linten test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService002, TestSize.Level0) +{ + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv0"; + + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfDeviceUnregisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + HdfIoServiceGroupRecycle(group); + group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(2, listener0.eventCount); + HdfIoServiceGroupRecycle(group); + + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService003 + * @tc.desc: remove service from service group by recycle group test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService003, TestSize.Level0) +{ + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv0"; + + struct HdfIoService *serv1 = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv1, nullptr); + serv1->priv = (void *)"serv1"; + + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfIoServiceGroupAddService(group, serv1); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfDeviceUnregisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfDeviceRegisterEventListener(serv, &listener1.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(2, listener0.eventCount); + ASSERT_EQ(1, listener1.eventCount); + HdfIoServiceGroupRecycle(group); + HdfDeviceUnregisterEventListener(serv, &listener1.listener); + HdfIoServiceRecycle(serv); + HdfIoServiceRecycle(serv1); +} + +/* * + * @tc.name: HdfIoService004 + * @tc.desc: single service listen test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService004, TestSize.Level0) +{ + struct HdfIoService *serv1 = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv1, nullptr); + serv1->priv = (void *)"serv1"; + + int ret = HdfDeviceRegisterEventListener(serv1, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + ret = SendEvent(serv1, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfDeviceUnregisterEventListener(serv1, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + HdfIoServiceRecycle(serv1); +} + +/* * + * @tc.name: HdfIoService005 + * @tc.desc: service group add remove test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService005, TestSize.Level0) +{ + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + HdfIoServiceGroupRemoveService(group, serv); + + ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(2, listener0.eventCount); + HdfIoServiceGroupRecycle(group); +} + + +/* * + * @tc.name: HdfIoService006 + * @tc.desc: service group add remove listener test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService006, TestSize.Level0) +{ + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + struct HdfIoService *serv1 = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv1, nullptr); + serv1->priv = (void *)"serv1"; + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupAddService(group, serv1); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = SendEvent(serv1, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(2, listener0.eventCount); + + HdfIoServiceGroupRemoveService(group, serv); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(2, listener0.eventCount); + + ret = SendEvent(serv1, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(3, listener0.eventCount); + + ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(4, listener0.eventCount); + + HdfIoServiceGroupRecycle(group); + HdfIoServiceRecycle(serv); + HdfIoServiceRecycle(serv1); +} + + +/* * + * @tc.name: HdfIoService007 + * @tc.desc: duplicate remove group listener + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService007, TestSize.Level0) +{ + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfIoServiceGroupUnregisterListener(group, &listener0.listener); + EXPECT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupUnregisterListener(group, &listener0.listener); + EXPECT_NE(ret, HDF_SUCCESS); + + HdfIoServiceGroupRecycle(group); + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService008 + * @tc.desc: duplicate add group listener + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService008, TestSize.Level0) +{ + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + EXPECT_NE(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupUnregisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + HdfIoServiceGroupRecycle(group); + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService008 + * @tc.desc: duplicate add service + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService009, TestSize.Level0) +{ + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupAddService(group, serv); + EXPECT_NE(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfIoServiceGroupUnregisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + HdfIoServiceGroupRecycle(group); + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService010 + * @tc.desc: duplicate remove service + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService010, TestSize.Level0) +{ + struct HdfIoServiceGroup *group = HdfIoServiceGroupObtain(); + ASSERT_NE(group, nullptr); + + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfIoServiceGroupAddService(group, serv); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupAddService(group, serv); + EXPECT_NE(ret, HDF_SUCCESS); + + ret = HdfIoServiceGroupRegisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + HdfIoServiceGroupRemoveService(group, serv); + HdfIoServiceGroupRemoveService(group, serv); + + ret = HdfIoServiceGroupUnregisterListener(group, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + HdfIoServiceGroupRecycle(group); + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService011 + * @tc.desc: duplicate add service listener + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService011, TestSize.Level0) +{ + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfDeviceRegisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfDeviceRegisterEventListener(serv, &listener0.listener); + EXPECT_NE(ret, HDF_SUCCESS); + + ret = HdfDeviceUnregisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + HdfIoServiceRecycle(serv); +} + +/* * + * @tc.name: HdfIoService012 + * @tc.desc: duplicate remove service listener + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(IoServiceTest, HdfIoService012, TestSize.Level0) +{ + struct HdfIoService *serv = HdfIoServiceBind(testSvcName); + ASSERT_NE(serv, nullptr); + serv->priv = (void *)"serv"; + + int ret = HdfDeviceRegisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = SendEvent(serv, testSvcName); + ASSERT_EQ(ret, HDF_SUCCESS); + + usleep(eventWaitTimeUs); + ASSERT_EQ(1, listener0.eventCount); + + ret = HdfDeviceUnregisterEventListener(serv, &listener0.listener); + ASSERT_EQ(ret, HDF_SUCCESS); + + ret = HdfDeviceUnregisterEventListener(serv, &listener0.listener); + EXPECT_NE(ret, HDF_SUCCESS); + + HdfIoServiceRecycle(serv); +} diff --git a/core/manager/test/unittest/common/hdf_lite_manager_test.cpp b/core/manager/test/unittest/common/hdf_lite_manager_test.cpp new file mode 100644 index 00000000..8af642b1 --- /dev/null +++ b/core/manager/test/unittest/common/hdf_lite_manager_test.cpp @@ -0,0 +1,139 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service.h" +#include "osal_time.h" +#include "sample_driver_test.h" + +using namespace testing::ext; + +class HdfManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfManagerTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfManagerTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfManagerTest::SetUp() +{ +} + +void HdfManagerTest::TearDown() +{ +} + +/** + * @tc.name: HdfIoServiceBind001 + * @tc.desc: service bind test + * @tc.type: FUNC + * @tc.require: AR000F8698 AR000F8699 AR000F869A AR000F869B AR000F869C + */ +HWTEST_F(HdfManagerTest, HdfIoServiceBind001, TestSize.Level0) +{ + const char *svcName = "HDF_TEST"; + struct HdfIoService *hdfSvc = HdfIoServiceBind(svcName); + EXPECT_TRUE(hdfSvc != NULL); + HdfIoServiceRecycle(hdfSvc); +} + +/** + * @tc.name: HdfIoServiceBind002 + * @tc.desc: service bind test + * @tc.type: FUNC + * @tc.require: AR000F8698 AR000F8699 AR000F869A AR000F869B AR000F869C + */ +HWTEST_F(HdfManagerTest, HdfIoServiceBind002, TestSize.Level0) +{ + struct HdfIoService *hdfSvc = HdfIoServiceBind(DEV_MGR_NODE); + EXPECT_TRUE(hdfSvc != NULL); + HdfIoServiceRecycle(hdfSvc); +} + +/** + * @tc.name: HdfRegisterDevice001 + * @tc.desc: register device + * @tc.type: FUNC + * @tc.require: SR000F8697 + */ +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); + data = HdfSBufObtainDefaultSize(); + ASSERT_TRUE(data != NULL); + EXPECT_TRUE(HdfSbufWriteString(data, "sample_driver")); + EXPECT_TRUE(HdfSbufWriteString(data, "sample_service1")); + int64_t timeBefore = OsalGetSysTimeMs(); + ret = ioService->dispatcher->Dispatch(&ioService->object, SAMPLE_DRIVER_REGISTER_DEVICE, data, NULL); + EXPECT_TRUE(ret == HDF_SUCCESS); + int64_t timeAfter = OsalGetSysTimeMs(); + EXPECT_TRUE((timeAfter - timeBefore) < 100); + + struct HdfIoService *ioService1 = HdfIoServiceBind("sample_service1"); + ASSERT_TRUE(ioService1 != NULL); + HdfIoServiceRecycle(ioService1); + + ret = ioService->dispatcher->Dispatch(&ioService->object, SAMPLE_DRIVER_UNREGISTER_DEVICE, data, NULL); + EXPECT_TRUE(ret == HDF_SUCCESS); + + ioService1 = HdfIoServiceBind("sample_service1"); + EXPECT_TRUE(ioService1 == NULL); + HdfIoServiceRecycle(ioService); + HdfIoServiceRecycle(ioService1); + HdfSBufRecycle(data); +} + +/** + * @tc.name: HdfGetServiceNameByDeviceClass001 + * @tc.desc: get service test + * @tc.type: FUNC + * @tc.require: AR000F8698 AR000F8699 AR000F869A AR000F869B AR000F869C + */ +HWTEST_F(HdfManagerTest, HdfGetServiceNameByDeviceClass001, TestSize.Level0) +{ + struct HdfSBuf *data = HdfSBufObtain(1000); + EXPECT_TRUE(data != NULL); + int32_t ret = HdfGetServiceNameByDeviceClass(DEVICE_CLASS_DEFAULT, data); + EXPECT_TRUE(ret == HDF_SUCCESS); + bool flag = false; + const char *svcName = NULL; + while(true) { + svcName = HdfSbufReadString(data); + if (svcName == NULL) { + break; + } + if (strcmp(svcName, "sample_service") == 0) { + flag = true; + break; + } + } + HdfSBufRecycle(data); + EXPECT_TRUE(flag); +} + diff --git a/core/manager/test/unittest/common/hdf_sbuf_test.cpp b/core/manager/test/unittest/common/hdf_sbuf_test.cpp new file mode 100644 index 00000000..a1ebde55 --- /dev/null +++ b/core/manager/test/unittest/common/hdf_sbuf_test.cpp @@ -0,0 +1,811 @@ +/* + * 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 +#include +#include +#include +#include +#include +using namespace testing::ext; + +static const int DEFAULT_SBUF_SIZE = 256; +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 { +protected: + void SetUp() override {} + + void TearDown() override + { + dataTable.clear(); + } + + void GenDataTable() + { + dataTable[UINT8] = std::unique_ptr(new SbufData(sizeof(uint8_t))); + dataTable[UINT16] = std::unique_ptr(new SbufData(sizeof(uint16_t))); + dataTable[UINT32] = std::unique_ptr(new SbufData(sizeof(uint32_t))); + dataTable[UINT64] = std::unique_ptr(new SbufData(sizeof(uint64_t))); + dataTable[INT8] = std::unique_ptr(new SbufData(sizeof(uint8_t))); + dataTable[INT16] = std::unique_ptr(new SbufData(sizeof(uint16_t))); + dataTable[INT32] = std::unique_ptr(new SbufData(sizeof(uint32_t))); + dataTable[INT64] = std::unique_ptr(new SbufData(sizeof(uint64_t))); + dataTable[BUFFER] = std::unique_ptr(new SbufData((rd() % UINT8_MAX) + 1)); + dataTable[STRING] = std::unique_ptr(new SbufData((rd() % UINT8_MAX) + 1)); + dataTable[STRING]->data[dataTable[STRING]->size - 1] = '\0'; + } + + void GenDataSequence(int seqSize) + { + dataSequence.clear(); + std::random_device rnd; + for (int i = 0; i < seqSize; ++i) { + dataSequence.push_back(rnd() % TYPE_MAX); + } + } + + bool PushDataSequence(HdfSBuf *sbuf) + { + for (auto type : dataSequence) { + bool ret = false; + switch (type) { + case UINT8: + ret = HdfSbufWriteUint8(sbuf, *(uint8_t *)dataTable[type]->data); + break; + case UINT16: + ret = HdfSbufWriteUint16(sbuf, *(uint16_t *)dataTable[type]->data); + break; + case UINT32: + ret = HdfSbufWriteUint32(sbuf, *(uint32_t *)dataTable[type]->data); + break; + case UINT64: + ret = HdfSbufWriteUint64(sbuf, *(uint64_t *)dataTable[type]->data); + break; + case INT8: + ret = HdfSbufWriteUint8(sbuf, *(int8_t *)dataTable[type]->data); + break; + case INT16: + ret = HdfSbufWriteUint16(sbuf, *(uint16_t *)dataTable[type]->data); + break; + case INT32: + ret = HdfSbufWriteUint32(sbuf, *(uint32_t *)dataTable[type]->data); + break; + case INT64: + ret = HdfSbufWriteUint64(sbuf, *(uint64_t *)dataTable[type]->data); + break; + case BUFFER: + ret = HdfSbufWriteBuffer(sbuf, (uint8_t *)dataTable[type]->data, dataTable[type]->size); + break; + case STRING: + ret = HdfSbufWriteString(sbuf, (char *)dataTable[type]->data); + break; + default: + break; + } + if (!ret) { + std::cout << "write type " << type << " fail" << std::endl; + return ret; + } + } + return true; + } + + static bool DataCompare(const void *s, const void *t, uint32_t size) + { + return memcmp(s, t, size) == 0; + } + + bool PullDataSequence(HdfSBuf *sbuf) + { + for (auto type : dataSequence) { + bool ret = false; + switch (type) { + case UINT8: { + uint8_t val = 0; + ret = HdfSbufReadUint8(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case UINT16: { + uint16_t val = 0; + ret = HdfSbufReadUint16(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case UINT32: { + uint32_t val = 0; + ret = HdfSbufReadUint32(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case UINT64: { + uint64_t val = 0; + ret = HdfSbufReadUint64(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case INT8: { + int8_t val = 0; + ret = HdfSbufReadInt8(sbuf, &val); + EXPECT_EQ(true, ret); + ret = DataCompare(&val, dataTable[type]->data, dataTable[type]->size); + EXPECT_EQ(true, ret); + break; + } + case INT16: { + int16_t val = 0; + ret = HdfSbufReadInt16(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case INT32: { + int32_t val = 0; + ret = HdfSbufReadInt32(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case INT64: { + int64_t val = 0; + ret = HdfSbufReadInt64(sbuf, &val); + EXPECT_EQ(true, DataCompare(&val, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case BUFFER: { + const char *buf = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(sbuf, reinterpret_cast(&buf), &readSize); + EXPECT_EQ(true, DataCompare(buf, dataTable[type]->data, dataTable[type]->size)); + EXPECT_EQ(true, ret); + break; + } + case STRING: { + auto val = HdfSbufReadString(sbuf); + EXPECT_NE(nullptr, val); + if (val == nullptr) { + return false; + } + EXPECT_EQ(strlen(val), dataTable[type]->size - 1); + EXPECT_EQ(true, DataCompare(val, dataTable[type]->data, dataTable[type]->size)); + ret = true; + break; + } + default: + break; + } + if (!ret) { + std::cout << "write type " << type << " fail" << std::endl; + return ret; + } + } + return true; + } + + enum SbufDataType { + UINT8, + UINT16, + UINT32, + UINT64, + INT8, + INT16, + INT32, + INT64, + BUFFER, + STRING, + TYPE_MAX, + }; + + class SbufData { + public: + explicit SbufData(uint32_t dataSize) : data(nullptr), size(dataSize) + { + std::random_device rnd; + data = new uint8_t[dataSize]; + for (uint32_t i = 0; i < dataSize; ++i) { + data[i] = 'A' + rnd() % DATA_MOD; + } + } + + ~SbufData() + { + if (data != nullptr) { + delete[] data; + } + } + uint8_t *data; + uint32_t size; + }; + + std::map> dataTable; + std::vector dataSequence; + std::random_device rd; +}; + +/** + * @tc.name: SbufTestObtain001 + * @tc.desc: obtain sbuf + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestObtain001, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtain(DEFAULT_SBUF_SIZE); + ASSERT_NE(sBuf, nullptr); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestWriteUint64002 + * @tc.desc: write uint64 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestWriteUint64002, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + auto ret = HdfSbufWriteInt64(sBuf, INT64_MAX); + ASSERT_EQ(ret, true); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestWriteUint64Loop003 + * @tc.desc: write uint64 data sequence + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestWriteUint64Loop003, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + for (int i = 0; i < DEFAULT_BIG_LOOP_COUNT; ++i) { + auto ret = HdfSbufWriteInt64(sBuf, INT64_MAX); + ASSERT_EQ(ret, true); + } + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestReadUint64Loop004 + * @tc.desc: read after write uint64 data sequence + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestReadUint64Loop004, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + int loop = DEFAULT_BIG_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + auto ret = HdfSbufWriteInt64(sBuf, INT64_MAX); + ASSERT_EQ(ret, true); + } + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + uint64_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + auto ret = HdfSbufReadUint64(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, (uint64_t)INT64_MAX); + } + auto ret = HdfSbufReadUint64(readBuf, &val); + ASSERT_EQ(ret, false); + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestInt8005 + * @tc.desc: read write int8 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestInt8005, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteInt8(sBuf, INT8_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + int8_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadInt8(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, INT8_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestInt16006 + * @tc.desc: read write int16 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestInt16006, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteInt16(sBuf, INT16_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + int16_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadInt16(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, INT16_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestInt32007 + * @tc.desc: read write int32 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestInt32007, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteInt32(sBuf, INT32_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + int32_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadInt32(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, INT32_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestInt64008 + * @tc.desc: read write int64 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestInt64008, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteInt64(sBuf, INT64_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint64_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + int64_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadInt64(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, INT64_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestUInt32009 + * @tc.desc: read write uint32 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestUInt32009, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteUint32(sBuf, UINT32_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + uint32_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadUint32(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, UINT32_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestUInt16010 + * @tc.desc: read write uint16 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestUInt16010, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteUint16(sBuf, UINT16_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + uint16_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadUint16(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, UINT16_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestUInt8011 + * @tc.desc: read write uint8 data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestUInt8011, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteUint8(sBuf, UINT8_MAX); + ASSERT_EQ(ret, true); + } + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_EQ(dataSize, loop * sizeof(uint32_t)); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + uint8_t val = 0; + for (int j = 0; j < loop; ++j) { + val = 0; + ret = HdfSbufReadUint8(readBuf, &val); + ASSERT_EQ(ret, true); + ASSERT_EQ(val, UINT8_MAX); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestString012 + * @tc.desc: read write string data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestString012, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = DEFAULT_LOOP_COUNT; + std::string str("test"); + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteString(sBuf, str.data()); + ASSERT_EQ(ret, true); + } + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + 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); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestNullString013 + * @tc.desc: read write bullptr string data test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestNullString013, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + auto ret = HdfSbufWriteString(sBuf, nullptr); + ASSERT_EQ(true, ret); + ret = HdfSbufWriteInt32(sBuf, INT32_MIN); + ASSERT_EQ(true, ret); + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_NE((size_t)0, dataSize); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + auto val = HdfSbufReadString(readBuf); + ASSERT_EQ(nullptr, val); + int32_t intVal = 0; + ret = HdfSbufReadInt32(readBuf, &intVal); + ASSERT_EQ(true, ret); + ASSERT_EQ(INT32_MIN, intVal); + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestBuffer014 + * @tc.desc: read write buffer test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestBuffer014, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + bool ret; + int loop = 1; + std::string str("test"); + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteBuffer(sBuf, str.data(), str.size() + 1); + ASSERT_EQ(ret, true); + } + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + for (int j = 0; j < loop; ++j) { + const char *data = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(readBuf, (const void **)(&data), &readSize); + ASSERT_EQ(ret, true); + ASSERT_EQ(readSize, str.size() + 1); + ASSERT_EQ(std::string(data), str); + } + HdfSBufRecycle(readBuf); + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestNullBuffer015 + * @tc.desc: read write nullptr buffer data + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestNullBuffer015, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + auto ret = HdfSbufWriteBuffer(sBuf, nullptr, 0); + ASSERT_EQ(true, ret); + ret = HdfSbufWriteInt16(sBuf, INT16_MIN); + ASSERT_EQ(true, ret); + size_t dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_NE((size_t)0, dataSize); + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + const uint8_t *buffVal = nullptr; + uint32_t buffLen = 0; + ret = HdfSbufReadBuffer(readBuf, (const void **)(&buffVal), &buffLen); + ASSERT_EQ(true, ret); + ASSERT_EQ((uint32_t)0, buffLen); + dataSize = HdfSbufGetDataSize(sBuf); + ASSERT_NE((size_t)0, dataSize); + int16_t intVal = 0; + ret = HdfSbufReadInt16(readBuf, &intVal); + ASSERT_EQ(true, ret); + ASSERT_EQ(INT16_MIN, intVal); + HdfSBufRecycle(sBuf); + HdfSBufRecycle(readBuf); +} + +/** + * @tc.name: SbufTestRandomDataSeq016 + * @tc.desc: read write random data test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestRandomDataSeq016, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + + GenDataTable(); + GenDataSequence(100); + bool ret = PushDataSequence(sBuf); + ASSERT_EQ(true, ret); + + HdfSBuf *readBuf = HdfSBufBind((uintptr_t)sBuf->data, sBuf->writePos); + ASSERT_NE(readBuf, nullptr); + + ret = PullDataSequence(readBuf); + ASSERT_EQ(true, ret); + HdfSBufRecycle(sBuf); + HdfSBufRecycle(readBuf); +} + +/** + * @tc.name: SbufTestRandomRWDataSeq017 + * @tc.desc: read write random data sequence test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestRandomRWDataSeq017, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + + GenDataTable(); + GenDataSequence(100); + bool ret = PushDataSequence(sBuf); + ASSERT_EQ(true, ret); + + ret = PullDataSequence(sBuf); + ASSERT_EQ(true, ret); + + ret = PushDataSequence(sBuf); + ASSERT_EQ(true, ret); + + ret = PullDataSequence(sBuf); + ASSERT_EQ(true, ret); + + uint8_t val = 0; + ret = HdfSbufReadUint8(sBuf, &val); + ASSERT_EQ(false, ret); + ASSERT_EQ(0, val); + + HdfSBufRecycle(sBuf); +} + +/** + * @tc.name: SbufTestSbufMove018 + * @tc.desc: move sbuf test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestSbufMove018, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + + GenDataTable(); + GenDataSequence(100); + + bool ret; + int loop = 1; + std::string str("test"); + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteBuffer(sBuf, str.data(), str.size() + 1); + ASSERT_EQ(ret, true); + } + + HdfSBuf *readBuf = HdfSBufMove(sBuf); + ASSERT_NE(readBuf, nullptr); + + for (int j = 0; j < loop; ++j) { + const char *data = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(readBuf, (const void **)(&data), &readSize); + ASSERT_EQ(ret, true); + ASSERT_EQ(readSize, str.size() + 1); + ASSERT_EQ(std::string(data), str); + } + HdfSBufRecycle(sBuf); + HdfSBufRecycle(readBuf); +} + +/** + * @tc.name: SbufTestSbufMoveHalf019 + * @tc.desc: move sbuf after read test + * @tc.type: FUNC + * @tc.require: AR000F869B + */ +HWTEST_F(SBufTest, SbufTestSbufMoveHalf019, TestSize.Level0) +{ + HdfSBuf *sBuf = HdfSBufObtainDefaultSize(); + ASSERT_NE(sBuf, nullptr); + + bool ret; + int loop = 1; + std::string str("test"); + for (int i = 0; i < loop; ++i) { + ret = HdfSbufWriteBuffer(sBuf, str.data(), str.size() + 1); + ASSERT_EQ(ret, true); + } + for (int j = 0; j < loop/2; ++j) { + const char *data = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(sBuf, (const void **)(&data), &readSize); + ASSERT_EQ(ret, true); + ASSERT_EQ(readSize, str.size() + 1); + ASSERT_EQ(std::string(data), str); + } + + HdfSBuf *readBuf = HdfSBufMove(sBuf); + ASSERT_NE(readBuf, nullptr); + + for (int j = 0; j < loop; ++j) { + const char *data = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(readBuf, (const void **)(&data), &readSize); + ASSERT_EQ(ret, true); + ASSERT_EQ(readSize, str.size() + 1); + ASSERT_EQ(std::string(data), str); + } + + const char *data = nullptr; + uint32_t readSize = 0; + ret = HdfSbufReadBuffer(readBuf, (const void **)(&data), &readSize); + ASSERT_EQ(ret, false); + + HdfSBufRecycle(sBuf); + HdfSBufRecycle(readBuf); +} diff --git a/core/shared/include/devhost_service_if.h b/core/shared/include/devhost_service_if.h old mode 100755 new mode 100644 index a09a958b..83e9d21a --- a/core/shared/include/devhost_service_if.h +++ b/core/shared/include/devhost_service_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVHOST_SERVICE_IF_H diff --git a/core/shared/include/device_token_if.h b/core/shared/include/device_token_if.h old mode 100755 new mode 100644 index a91672c2..c086152c --- a/core/shared/include/device_token_if.h +++ b/core/shared/include/device_token_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVICE_TOKEN_IF_H diff --git a/core/shared/include/devmgr_service_if.h b/core/shared/include/devmgr_service_if.h old mode 100755 new mode 100644 index cc1d127d..136f2832 --- a/core/shared/include/devmgr_service_if.h +++ b/core/shared/include/devmgr_service_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVMGR_SERVICE_IF_H @@ -38,6 +15,7 @@ #include "power_state_token_if.h" struct IDevmgrService { + struct HdfObject base; struct HdfDeviceObject object; int (*AttachDeviceHost)(struct IDevmgrService *, uint16_t, struct IDevHostService *); int (*AttachDevice)(struct IDevmgrService *, const struct HdfDeviceInfo *, struct IHdfDeviceToken *); diff --git a/core/shared/include/devsvc_manager_if.h b/core/shared/include/devsvc_manager_if.h old mode 100755 new mode 100644 index d1787ec4..394f4b50 --- a/core/shared/include/devsvc_manager_if.h +++ b/core/shared/include/devsvc_manager_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVSVC_MANAGER_IF_H diff --git a/core/shared/include/hdf_attribute_manager.h b/core/shared/include/hdf_attribute_manager.h old mode 100755 new mode 100644 index 8b0dd595..ec90ee01 --- a/core/shared/include/hdf_attribute_manager.h +++ b/core/shared/include/hdf_attribute_manager.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_ATTRIBUTE_MANAGER_H @@ -34,8 +11,10 @@ #include "hdf_slist.h" +const struct DeviceResourceNode *HdfGetRootNode(void); bool HdfAttributeManagerGetHostList(struct HdfSList *hostList); struct HdfSList *HdfAttributeManagerGetDeviceList(uint16_t hostId, const char *hostName); -void ReleaseHcsTree(void); +bool HdfDeviceListAdd(const char *moduleName, const char *serviceName); +void HdfDeviceListDel(const char *moduleName, const char *serviceName); #endif /* HDF_ATTRIBUTE_MANAGER_H */ diff --git a/core/shared/include/hdf_device_info.h b/core/shared/include/hdf_device_info.h old mode 100755 new mode 100644 index eaebf28a..a5fa7812 --- a/core/shared/include/hdf_device_info.h +++ b/core/shared/include/hdf_device_info.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_DEVICE_INFO_H @@ -37,6 +14,7 @@ struct HdfDeviceInfo { struct HdfSListNode node; + bool isDynamic; uint16_t hostId; uint16_t deviceId; uint16_t policy; @@ -49,6 +27,7 @@ struct HdfDeviceInfo { }; struct HdfDeviceInfo *HdfDeviceInfoNewInstance(void); +void HdfDeviceInfoConstruct(struct HdfDeviceInfo *deviceInfo); void HdfDeviceInfoFreeInstance(struct HdfDeviceInfo *deviceInfo); void HdfDeviceInfoDelete(struct HdfSListNode *listEntry); diff --git a/core/shared/include/hdf_io_service.h b/core/shared/include/hdf_io_service.h old mode 100755 new mode 100644 index cd9e2f10..6887fa61 --- a/core/shared/include/hdf_io_service.h +++ b/core/shared/include/hdf_io_service.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_IO_SERVICE_H @@ -38,14 +15,42 @@ extern "C" { #endif /* __cplusplus */ -#define DEV_NODE_PATH "/dev/" +#define DEV_NODE_PATH "/dev/hdf/" +#define DEV_PATH "/dev/" #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_LISTEN_EVENT_START _IO('b', 3) +#define HDF_LISTEN_EVENT_STOP _IO('b', 4) +#define HDF_LISTEN_EVENT_WAKEUP _IO('b', 5) +#define HDF_LISTEN_EVENT_EXIT _IO('b', 6) -struct HdfIoService *HdfIoServiceObtain( - struct HdfObject *object, struct HdfIoDispatcher *dispatcher); -struct HdfIoService *HdfIoServiceAdapterObtain(const char* serviceName, mode_t mode); +typedef enum { + DEVMGR_LOAD_SERVICE = 0, + DEVMGR_UNLOAD_SERVICE, + DEVMGR_GET_SERVICE, +} DevMgrCmd; + +struct HdfWriteReadBuf { + int cmdCode; + size_t writeSize; // bytes to write + size_t writeConsumed; // bytes consumed by driver (for ERESTARTSYS) + uintptr_t writeBuffer; + size_t readSize; // bytes to read + size_t readConsumed; // bytes consumed by driver (for ERESTARTSYS) + uintptr_t readBuffer; +}; + +struct HdfIoService *HdfIoServicePublish(const char *serviceName, uint32_t mode); +void HdfIoServiceRemove(struct HdfIoService *service); + +struct HdfIoService *HdfIoServiceAdapterObtain(const char *serviceName); void HdfIoServiceAdapterRecycle(struct HdfIoService *service); +struct HdfIoService *HdfIoServiceAdapterPublish(const char *serviceName, uint32_t mode) __attribute__((weak)); +void HdfIoServiceAdapterRemove(struct HdfIoService *service) __attribute__((weak)); +int32_t HdfLoadDriverByServiceName(const char *serviceName); #ifdef __cplusplus } diff --git a/core/shared/include/hdf_object_manager.h b/core/shared/include/hdf_object_manager.h old mode 100755 new mode 100644 index b0471275..d98e47b1 --- a/core/shared/include/hdf_object_manager.h +++ b/core/shared/include/hdf_object_manager.h @@ -1,38 +1,14 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_OBJECT_MANAGER_H #define HDF_OBJECT_MANAGER_H -#include #include "hdf_object.h" enum { diff --git a/core/shared/include/hdf_service_record.h b/core/shared/include/hdf_service_record.h old mode 100755 new mode 100644 index 8d510cd0..0e8651dc --- a/core/shared/include/hdf_service_record.h +++ b/core/shared/include/hdf_service_record.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 DEVSVC_RECORD_H diff --git a/core/shared/include/power_state_token_if.h b/core/shared/include/power_state_token_if.h old mode 100755 new mode 100644 index 0ccb291f..fe828f1e --- a/core/shared/include/power_state_token_if.h +++ b/core/shared/include/power_state_token_if.h @@ -1,46 +1,23 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef POWER_STATE_TOKEN_IF_H -#define POWER_STATE_TOKEN_IF_H - -typedef enum { - POWER_STATE_IDLE, /* Idle state */ - POWER_STATE_ACTIVE, /* Activated state */ - POWER_STATE_INACTIVE, /* Error state */ -} HdfPowerState; - -struct IPowerStateToken { - void (*AcquireWakeLock)(struct IPowerStateToken *); - void (*ReleaseWakeLock)(struct IPowerStateToken *); -}; - +/* + * 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 POWER_STATE_TOKEN_IF_H +#define POWER_STATE_TOKEN_IF_H + +typedef enum { + POWER_STATE_IDLE, /* Idle state */ + POWER_STATE_ACTIVE, /* Activated state */ + POWER_STATE_INACTIVE, /* Error state */ +} HdfPowerState; + +struct IPowerStateToken { + void (*AcquireWakeLock)(struct IPowerStateToken *); + void (*ReleaseWakeLock)(struct IPowerStateToken *); +}; + #endif /* POWER_STATE_TOKEN_IF_H */ \ No newline at end of file diff --git a/core/shared/src/hdf_device_info.c b/core/shared/src/hdf_device_info.c old mode 100755 new mode 100644 index 5048a506..d30bb3fb --- a/core/shared/src/hdf_device_info.c +++ b/core/shared/src/hdf_device_info.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_device_info.h" @@ -35,8 +12,12 @@ #define HDF_LOG_TAG device_info -static void HdfDeviceInfoConstruct(struct HdfDeviceInfo *deviceInfo) +void HdfDeviceInfoConstruct(struct HdfDeviceInfo *deviceInfo) { + if (deviceInfo == NULL) { + return; + } + deviceInfo->isDynamic = false; deviceInfo->hostId = 0; deviceInfo->deviceId = 0; deviceInfo->policy = SERVICE_POLICY_INVALID; @@ -63,6 +44,9 @@ struct HdfDeviceInfo *HdfDeviceInfoNewInstance() void HdfDeviceInfoFreeInstance(struct HdfDeviceInfo *deviceInfo) { if (deviceInfo != NULL) { + if (deviceInfo->isDynamic && deviceInfo->svcName != NULL) { + OsalMemFree((void *)deviceInfo->svcName); + } OsalMemFree(deviceInfo); } } diff --git a/core/shared/src/hdf_io_service.c b/core/shared/src/hdf_io_service.c old mode 100755 new mode 100644 index 43df0750..aa6ac64f --- a/core/shared/src/hdf_io_service.c +++ b/core/shared/src/hdf_io_service.c @@ -1,51 +1,17 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_io_service.h" #include "hdf_vnode_adapter.h" -struct HdfIoService *HdfIoServiceObtain( - struct HdfObject *object, struct HdfIoDispatcher *dispatcher) +struct HdfIoService *HdfIoServiceBind(const char *serviceName) { - struct HdfIoService *service = HdfIoServiceAdapterObtain(NULL, 0); - if ((service != NULL) && (service->dispatcher == NULL)) { - service->dispatcher = dispatcher; - service->target = object; - } - return service; -} - -struct HdfIoService *HdfIoServiceBind(const char *serviceName, mode_t permission) -{ - return HdfIoServiceAdapterObtain(serviceName, permission); + return HdfIoServiceAdapterObtain(serviceName); } void HdfIoServiceRecycle(struct HdfIoService *service) @@ -53,3 +19,18 @@ void HdfIoServiceRecycle(struct HdfIoService *service) HdfIoServiceAdapterRecycle(service); } +struct HdfIoService *HdfIoServicePublish(const char *serviceName, uint32_t mode) +{ + if (HdfIoServiceAdapterPublish != NULL) { + return HdfIoServiceAdapterPublish(serviceName, mode); + } + + return NULL; +} + +void HdfIoServiceRemove(struct HdfIoService *service) +{ + if (HdfIoServiceAdapterRemove != NULL) { + HdfIoServiceAdapterRemove(service); + } +} diff --git a/core/shared/src/hdf_object_manager.c b/core/shared/src/hdf_object_manager.c old mode 100755 new mode 100644 index bf8640c7..ee90d1ff --- a/core/shared/src/hdf_object_manager.c +++ b/core/shared/src/hdf_object_manager.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_object_manager.h" diff --git a/core/shared/src/hdf_service_record.c b/core/shared/src/hdf_service_record.c old mode 100755 new mode 100644 index 91f53d84..269fcd7e --- a/core/shared/src/hdf_service_record.c +++ b/core/shared/src/hdf_service_record.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_service_record.h" diff --git a/figures/architecture-of-the-hdf.png b/figures/architecture-of-the-hdf.png new file mode 100644 index 00000000..2bd6a1d8 Binary files /dev/null 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 old mode 100755 new mode 100644 index 85918cbd..4bc009ff --- a/include/config/device_resource_if.h +++ b/include/config/device_resource_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -127,8 +104,8 @@ struct DeviceResourceIface { * @param node Indicates the pointer to the configuration tree node. * @param attrName Indicates the pointer to the name of the attribute. * - * @return Returns the value of the BOOL attribute if the operation is successful; - * returns false if node and attrName are null pointers. + * @return Returns true if the operation is successful and the value of the BOOL attribute is + * true; returns false otherwise. * @since 1.0 * @version 1.0 */ diff --git a/include/core/hdf_device_desc.h b/include/core/hdf_device_desc.h old mode 100755 new mode 100644 index 500f7020..ed8f2d62 --- a/include/core/hdf_device_desc.h +++ b/include/core/hdf_device_desc.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -53,6 +30,7 @@ #define HDF_DEVICE_DESC_H #include "hdf_device_section.h" +#include "hdf_io_service_if.h" #include "hdf_object.h" #include "hdf_sbuf.h" @@ -95,6 +73,7 @@ typedef enum { */ typedef enum { DEVICE_PRELOAD_ENABLE = 0, /**< The driver is loaded during system startup by default. */ + DEVICE_PRELOAD_ENABLE_STEP2, /**< The driver is loaded after OS startup if quick start is enabled. */ DEVICE_PRELOAD_DISABLE, /**< The driver is not loaded during system startup by default. */ DEVICE_PRELOAD_INVALID /**< The loading policy is incorrect. */ } DevicePreload; @@ -110,9 +89,12 @@ typedef enum { struct HdfDeviceObject { /** Pointer to the service interface object, which is registered with the HDF by the driver */ struct IDeviceIoService *service; - /** Pointer to the private data of the device, which is read by the HDF from the configuration file and + /** Pointer to the property of the device, which is read by the HDF from the configuration file and transmitted to the driver. */ const struct DeviceResourceNode *property; + DeviceClass deviceClass; + /** Pointer to the private data of the device */ + void *private; }; /** @@ -323,7 +305,6 @@ int32_t HdfDeviceSubscribeService( */ int32_t HdfDeviceSendEvent(const struct HdfDeviceObject *deviceObject, uint32_t id, const struct HdfSBuf *data); - /** * @brief Sends an event message to a specified client object. * @@ -339,5 +320,19 @@ int32_t HdfDeviceSendEvent(const struct HdfDeviceObject *deviceObject, uint32_t * @since 1.0 */ int32_t HdfDeviceSendEventToClient(const struct HdfDeviceIoClient *client, uint32_t id, const struct HdfSBuf *data); +/** + * @brief Sets the driver device class. + * + * After setting the driver device class, you can obtain the service name of this driver device type via + * {@link HdfGetServiceNameByDeviceClass}. + * + * + * @param deviceObject Indicates the pointer to the driver device object. + * @param deviceClass Indicates the device class defined by {@link DeviceClass}. + * + * @return Returns true if the operation is successful; returns false otherwise. + * @since 1.0 */ +bool HdfDeviceSetClass(struct HdfDeviceObject *deviceObject, DeviceClass deviceClass); + #endif /* HDF_DEVICE_DESC_H */ /** @} */ diff --git a/include/core/hdf_io_service_if.h b/include/core/hdf_io_service_if.h old mode 100755 new mode 100644 index 918f0077..9dc9fd90 --- a/include/core/hdf_io_service_if.h +++ b/include/core/hdf_io_service_if.h @@ -1,41 +1,18 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup Core * @{ * - * @brief Provides OpenHarmony Driver Foundation (HDF) APIs. + * @brief Provides functions to use the Hardware 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 */ @@ -43,16 +20,16 @@ /** * @file hdf_io_service_if.h * - * @brief Declares the structures defining driver service objects and event listeners, as well as the functions for - * obtaining a driver service object, dispatching a driver service call, and registering or unregistering an - * event listener. + * @brief Declares the structures defining driver service objects and event listeners, as well as the functions + * for obtaining a driver service object, dispatching a driver service call, and registering or unregistering + * an event listener. * * @since 1.0 */ + #ifndef HDF_IO_SERVICE_IF_H #define HDF_IO_SERVICE_IF_H -#include #include "hdf_dlist.h" #include "hdf_object.h" #include "hdf_sbuf.h" @@ -61,6 +38,29 @@ extern "C" { #endif /* __cplusplus */ +struct HdfDevEventlistener; +struct HdfIoService; + +/** + * @brief Enumerates different classes of driver devices. + * + * @since 1.0 + */ +typedef enum { + /** Default device */ + DEVICE_CLASS_DEFAULT = 0, + /** Platform device */ + DEVICE_CLASS_PAL, + /** Sensor device */ + DEVICE_CLASS_SENSOR, + /** Input device */ + DEVICE_CLASS_INPUT, + /** Display device */ + DEVICE_CLASS_DISPLAY, + /** Maximum value of a device class */ + DEVICE_CLASS_MAX +} DeviceClass; + /** * @brief Called when a driver event occurs. * @@ -75,17 +75,35 @@ extern "C" { */ typedef int (*OnEventReceived)(void *priv, uint32_t id, struct HdfSBuf *data); +/** + * @brief Called when a driver event occurs. + * + * You can implement this function and bind it to the custom {@link HdfDevEventlistener} object. \n + * + * @param listener Indicates the pointer to the listener that receives the driver event. + * @param service Indicates the pointer to the driver service object that generates the driver event. + * @param id Indicates the serial number of the driver event occurred. + * @param data Indicates the pointer to the content data of the driver event. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +typedef int (*OnDevEventReceive)(struct HdfDevEventlistener *listener, + struct HdfIoService *service, uint32_t id, struct HdfSBuf *data); + /** * @brief Defines a driver event listener object. * * @since 1.0 */ struct HdfDevEventlistener { - /** Callback invoked when the monitored device reports an event */ + /** Deprecated. Use {@link onReceive} instead. */ OnEventReceived callBack; + /** Callback invoked when the monitored device reports an event */ + OnDevEventReceive onReceive; /** Intrusive list node used by the HDF to manage listeners. You can ignore this node. */ struct DListHead listNode; - /** Private data of the listener, which is passed as the first input parameter in callback */ + /** Private data of the listener */ void *priv; }; @@ -112,21 +130,102 @@ struct HdfIoService { /** Pointer to the bound service entity, which is used for framework management. You can ignore it. */ struct HdfObject *target; /** Service call dispatcher */ - struct HdfIoDispatcher *dispatcher; + struct HdfIoDispatcher* dispatcher; + /** Private data of the service */ + void* priv; }; +/** + * @brief Defines a driver service group object. + * + * @since 1.0 + */ +struct HdfIoServiceGroup { + /** Base class object */ + struct HdfObject object; +}; + +/** + * @brief Obtains an instance of the driver service group object. + * + * @return Returns the pointer to the driver service group object if the operation is successful; + * returns NULL otherwise. + * + * @since 1.0 + */ +struct HdfIoServiceGroup *HdfIoServiceGroupObtain(void); + +/** + * @brief Destroys a driver service group object. + * + * @param group Indicates the pointer to the driver service group object to destroy. + * + * @since 1.0 + */ +void HdfIoServiceGroupRecycle(struct HdfIoServiceGroup *group); + +/** + * @brief Adds a driver service object to a specified driver service group. + * + * @param group Indicates the pointer to the driver service group object to + * which the driver service object is to be added. + * @param service Indicates the pointer to the driver service object to add. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t HdfIoServiceGroupAddService(struct HdfIoServiceGroup *group, struct HdfIoService *service); + + +/** + * @brief Removes a driver service object from a specified driver service group. + * + * @param group Indicates the pointer to the driver service group object from + * which the driver service object is to be removed. + * @param service Indicates the pointer to the driver service object to remove. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +void HdfIoServiceGroupRemoveService(struct HdfIoServiceGroup *group, struct HdfIoService *service); + +/** + * @brief Registers a custom {@link HdfDevEventlistener} for listening for events reported by driver services + * in a specified driver service group object. + * + * @param group Indicates the pointer to the driver service group object to listen to, + * which is obtained via {@link HdfIoServiceGroupObtain}. + * @param listener Indicates the pointer to the {@link HdfDevEventlistener} to register. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t HdfIoServiceGroupRegisterListener(struct HdfIoServiceGroup *group, struct HdfDevEventlistener *listener); + +/** + * @brief Unregisters a previously registered {@link HdfDevEventlistener} that is used for listening for events + * reported by driver services in a specified driver service group object. + * + * @param group Indicates the pointer to the driver service group object that has been listened to. + * @param listener Indicates the pointer to the {@link HdfDevEventlistener} to unregister. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t HdfIoServiceGroupUnregisterListener(struct HdfIoServiceGroup *group, struct HdfDevEventlistener *listener); + /** * @brief Obtains a driver service object. * + * + * * @param serviceName Indicates the pointer to the name of the service to obtain. - * @param permission Indicates the permission to create device nodes. The default value 0 can be used - * when this function is called from user space. * @return Returns the pointer to the driver service object if the operation is successful; * returns NULL otherwise. * * @since 1.0 */ -struct HdfIoService *HdfIoServiceBind(const char *serviceName, mode_t permission); +struct HdfIoService *HdfIoServiceBind(const char *serviceName); /** * @brief Destroys a specified driver service object to release resources if it is no longer required. @@ -161,9 +260,53 @@ int HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDevEve * @since 1.0 */ int HdfDeviceUnregisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener); + +/** + * @brief Obtains the number of event listeners that are registered for a specified driver service object. + * + * @param service Indicates the pointer to the driver service object for which the event listeners are registered. + * @return Returns the number of listeners if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfIoserviceGetListenerCount(const struct HdfIoService *service); + +/** + * @brief Obtains the number of event listeners that are registered for a specified driver service group object. + * + * @param group Indicates the pointer to the driver service group object for which the event listeners are registered. + * @return Returns the number of listeners if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfIoserviceGroupGetListenerCount(const struct HdfIoServiceGroup *group); + +/** + * @brief Obtains the number of driver services included in a specified driver service group. + * + * @param group Indicates the pointer to the driver service group object. + * @return Returns the number of services if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int HdfIoserviceGroupGetServiceCount(const struct HdfIoServiceGroup *group); + +/** + * @brief Obtains the names of device services of a specified device class defined by {@link DeviceClass}. + * + * + * @param deviceClass Indicates the device class to query. + * @param reply Indicates the pointer to the service name, which is stored as a string in an HdfSBuf structure. + * You can use {@link HdfSbufReadString} to continuously read the service names until a null pointer appears. + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t HdfGetServiceNameByDeviceClass(DeviceClass deviceClass, struct HdfSBuf *reply); + #ifdef __cplusplus } -#endif /* __cplusplus */ +#endif /* __cplusplus */ #endif /* HDF_IO_SERVICE_IF_H */ /** @} */ diff --git a/include/core/hdf_object.h b/include/core/hdf_object.h old mode 100755 new mode 100644 index af028d27..d73da125 --- a/include/core/hdf_object.h +++ b/include/core/hdf_object.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -52,7 +29,7 @@ #ifndef HDF_OBJECT_H #define HDF_OBJECT_H -#include +#include "hdf_base.h" /** * @brief Describes base class objects defined by the HDF. diff --git a/include/net/hdf_netbuf.h b/include/net/hdf_netbuf.h old mode 100755 new mode 100644 index cd7b24e6..f3046646 --- a/include/net/hdf_netbuf.h +++ b/include/net/hdf_netbuf.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -59,9 +38,7 @@ #ifndef HDF_NETBUF_H #define HDF_NETBUF_H -#include "los_spinlock.h" -#include "hdf_dlist.h" -#include "lwip/pbuf.h" +#include "netbuf_adapter.h" #ifdef __cplusplus #if __cplusplus @@ -69,82 +46,15 @@ extern "C" { #endif #endif /* __cplusplus */ -/** - * @brief Enumerates the segments of a network data buffer. - * - * The entire network data buffer is divided into three segments: a header, data, and a tail. - * The header and tail are used to extend both ends of the data segment. - * - * @since 1.0 - */ -enum { - E_HEAD_BUF, /**< Header buffer segment */ - E_DATA_BUF, /**< Data segment */ - E_TAIL_BUF, /**< Tail buffer segment */ - MAX_BUF_NUM /**< Maximum number of buffer segments */ -}; - -struct BufField { - uint32_t offset; - uint32_t len; -}; - -/** - * @brief Defines the reserved field of a network data buffer used to store private information. - * - * The length of the reserved field is 68 bytes. - */ -#define MAX_NETBUF_RESEVER_SIZE 68 - -/** - * @brief Records and saves a network data buffer. - * - * This structure is used to transmit network data between the protocol stack and network driver. - * - * @since 1.0 - */ -struct NetBuf { - struct DListHead dlist; /**< Doubly linked list. Generally, multiple network data buffers are - linked by using a doubly linked list. */ - struct BufField bufs[MAX_BUF_NUM]; /**< Defines buffer segments used to record the offset address - (based on the memory buffer address) and length of each buffer segment, - including the header buffer segment, data segment, and tail buffer segment. - For details, see {@link MAX_BUF_NUM}. */ - uint8_t *mem; /**< Memory buffer address */ - uint32_t len; /**< Length of the memory buffer */ - uint32_t dataLen; /**< Actual data length of the network data buffer */ - void *dev; /**< Network device that receives the network data */ - uint32_t qmap; /**< Queue mappings of the network data buffer */ - uint8_t rsv[MAX_NETBUF_RESEVER_SIZE]; /**< Reserved field. For details, see {@link MAX_NETBUF_RESEVER_SIZE}. */ -}; - -/** - * @brief Indicates the queues for storing network data. - * - * Queues can be used to process multiple pieces of network data in a centralized manner, improving efficiency. - * - * @since 1.0 - */ -struct NetBufQueue { - struct DListHead dlist; /**< Doubly linked list. Generally, multiple network data buffers are linked - by using a doubly linked list. */ - uint32_t size; /**< Number of network data buffers in the queue */ - struct Spinlock lock; /**< Queue operation lock */ -}; - /** * @brief Initializes a network data buffer queue. * * @param q Indicates the pointer to the network data buffer queue. * * @since 1.0 + * @version 1.0 */ -static inline void NetBufQueueInit(struct NetBufQueue *q) -{ - DListHeadInit(&q->dlist); - LOS_SpinInit(&q->lock); - q->size = 0; -} +void NetBufQueueInit(NetBufQueue *q); /** * @brief Obtains the size of a network data buffer queue. @@ -154,11 +64,9 @@ static inline void NetBufQueueInit(struct NetBufQueue *q) * @return Returns the size of the network data buffer queue. * * @since 1.0 + * @version 1.0 */ -static inline uint32_t NetBufQueueSize(const struct NetBufQueue *q) -{ - return q->size; -} +uint32_t NetBufQueueSize(const NetBufQueue *q); /** * @brief Checks whether the network data buffer queue is empty. @@ -168,11 +76,9 @@ static inline uint32_t NetBufQueueSize(const struct NetBufQueue *q) * @return Returns true if the queue is empty; returns false otherwise. * * @since 1.0 + * @version 1.0 */ -static inline bool NetBufQueueIsEmpty(const struct NetBufQueue *q) -{ - return DListIsEmpty(&q->dlist); -} +bool NetBufQueueIsEmpty(const NetBufQueue *q); /** * @brief Adds a network data buffer to the tail of a queue. @@ -181,8 +87,9 @@ static inline bool NetBufQueueIsEmpty(const struct NetBufQueue *q) * @param nb Indicates the pointer to the network data buffer. * * @since 1.0 + * @version 1.0 */ -void NetBufQueueEnqueue(struct NetBufQueue *q, struct NetBuf *nb); +void NetBufQueueEnqueue(NetBufQueue *q, NetBuf *nb); /** * @brief Adds a network data buffer to the header of a queue. @@ -191,8 +98,9 @@ void NetBufQueueEnqueue(struct NetBufQueue *q, struct NetBuf *nb); * @param nb Indicates the pointer to the network data buffer. * * @since 1.0 + * @version 1.0 */ -void NetBufQueueEnqueueHead(struct NetBufQueue *q, struct NetBuf *nb); +void NetBufQueueEnqueueHead(NetBufQueue *q, NetBuf *nb); /** * @brief Obtains a network data buffer from the header of a queue and deletes it from the queue. @@ -203,8 +111,9 @@ void NetBufQueueEnqueueHead(struct NetBufQueue *q, struct NetBuf *nb); * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -struct NetBuf *NetBufQueueDequeue(struct NetBufQueue *q); +NetBuf *NetBufQueueDequeue(NetBufQueue *q); /** * @brief Obtains a network data buffer from the tail of a queue and deletes it from the queue. @@ -215,8 +124,9 @@ struct NetBuf *NetBufQueueDequeue(struct NetBufQueue *q); * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -struct NetBuf *NetBufQueueDequeueTail(struct NetBufQueue *q); +NetBuf *NetBufQueueDequeueTail(NetBufQueue *q); /** * @brief Obtains the network data buffer from the header of a queue, without deleting it from the queue. @@ -227,11 +137,9 @@ struct NetBuf *NetBufQueueDequeueTail(struct NetBufQueue *q); * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -static inline struct NetBuf *NetBufQueueAtHead(const struct NetBufQueue *q) -{ - return (DListIsEmpty(&q->dlist)) ? NULL : DLIST_FIRST_ENTRY(&q->dlist, struct NetBuf, dlist); -} +NetBuf *NetBufQueueAtHead(const NetBufQueue *q); /** * @brief Obtains the network data buffer from the tail of a queue, without deleting it from the queue. @@ -242,11 +150,9 @@ static inline struct NetBuf *NetBufQueueAtHead(const struct NetBufQueue *q) * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -static inline struct NetBuf *NetBufQueueAtTail(const struct NetBufQueue *q) -{ - return (DListIsEmpty(&q->dlist)) ? NULL : DLIST_LAST_ENTRY(&q->dlist, struct NetBuf, dlist); -} +NetBuf *NetBufQueueAtTail(const NetBufQueue *q); /** * @brief Clears a network data buffer queue and releases the network data buffer in the queue. @@ -254,8 +160,9 @@ static inline struct NetBuf *NetBufQueueAtTail(const struct NetBufQueue *q) * @param q Indicates the pointer to the network data buffer queue. * * @since 1.0 + * @version 1.0 */ -void NetBufQueueClear(struct NetBufQueue *q); +void NetBufQueueClear(NetBufQueue *q); /** * @brief Moves all network data buffers from one queue to another and clears the source queue. @@ -264,10 +171,9 @@ void NetBufQueueClear(struct NetBufQueue *q); * @param add Indicates the pointer to the source network data buffer queue. * * @since 1.0 + * @version 1.0 */ -void NetBufQueueConcat(struct NetBufQueue *q, struct NetBufQueue *add); - -struct NetDevice; +void NetBufQueueConcat(NetBufQueue *q, NetBufQueue *add); /** * @brief Applies for a network data buffer. @@ -278,8 +184,9 @@ struct NetDevice; * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -struct NetBuf *NetBufAlloc(uint32_t size); +NetBuf *NetBufAlloc(uint32_t size); /** * @brief Releases a network data buffer. @@ -287,9 +194,11 @@ struct NetBuf *NetBufAlloc(uint32_t size); * @param nb Indicates the pointer to the network data buffer. * * @since 1.0 + * @version 1.0 */ -void NetBufFree(struct NetBuf *nb); +void NetBufFree(NetBuf *nb); +struct NetDevice; /** * @brief Applies for a network data buffer based on the reserved space and requested size set by a network device. * @@ -300,8 +209,9 @@ void NetBufFree(struct NetBuf *nb); * returns NULL otherwise. * * @since 1.0 + * @version 1.0 */ -struct NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size); +NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size); /** * @brief Performs operations based on the segment ID of a network data buffer. @@ -322,8 +232,9 @@ struct NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size); * returns NULL if the operation length exceeds the space of a specified buffer segment. * * @since 1.0 + * @version 1.0 */ -void *NetBufPush(struct NetBuf *nb, uint32_t id, uint32_t len); +void *NetBufPush(NetBuf *nb, uint32_t id, uint32_t len); /** * @brief Performs operations based on the segment ID of a network data buffer. @@ -344,8 +255,9 @@ void *NetBufPush(struct NetBuf *nb, uint32_t id, uint32_t len); * returns NULL if the operation length exceeds the space of a specified buffer segment. * * @since 1.0 + * @version 1.0 */ -void *NetBufPop(struct NetBuf *nb, uint32_t id, uint32_t len); +void *NetBufPop(NetBuf *nb, uint32_t id, uint32_t len); /** * @brief Obtains the address of a specified buffer segment in a network data buffer. @@ -357,15 +269,9 @@ void *NetBufPop(struct NetBuf *nb, uint32_t id, uint32_t len); * returns NULL if the buffer segment ID is invalid. * * @since 1.0 + * @version 1.0 */ -static inline uint8_t *NetBufGetAddress(const struct NetBuf *nb, uint32_t id) -{ - if (id < MAX_BUF_NUM) { - return (nb->mem + nb->bufs[id].offset); - } - - return NULL; -} +uint8_t *NetBufGetAddress(const NetBuf *nb, uint32_t id); /** * @brief Obtains the size of a specified buffer segment space in a network data buffer. @@ -377,15 +283,9 @@ static inline uint8_t *NetBufGetAddress(const struct NetBuf *nb, uint32_t id) * returns NULL if the buffer segment ID is invalid. * * @since 1.0 + * @version 1.0 */ -static inline uint32_t NetBufGetRoom(const struct NetBuf *nb, uint32_t id) -{ - if (id < MAX_BUF_NUM) { - return nb->bufs[id].len; - } - - return 0; -} +uint32_t NetBufGetRoom(const NetBuf *nb, uint32_t id); /** * @brief Obtains the actual data length of the data segment of a network data buffer. @@ -395,11 +295,9 @@ static inline uint32_t NetBufGetRoom(const struct NetBuf *nb, uint32_t id) * @return Returns the actual data length of the data segment. * * @since 1.0 + * @version 1.0 */ -static inline uint32_t NetBufGetDataLen(const struct NetBuf *nb) -{ - return nb->dataLen; -} +uint32_t NetBufGetDataLen(const NetBuf *nb); /** * @brief Adjusts the size of a network data buffer space. @@ -414,8 +312,9 @@ static inline uint32_t NetBufGetDataLen(const struct NetBuf *nb) * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t NetBufResizeRoom(struct NetBuf *nb, uint32_t head, uint32_t tail); +int32_t NetBufResizeRoom(NetBuf *nb, uint32_t head, uint32_t tail); /** * @brief Copies data in a network data buffer to another network data buffer. @@ -426,36 +325,9 @@ int32_t NetBufResizeRoom(struct NetBuf *nb, uint32_t head, uint32_t tail); * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. * * @since 1.0 + * @version 1.0 */ -uint32_t NetBufConcat(struct NetBuf *nb, struct NetBuf *cnb); - -/** - * @brief Converts the pbuf structure of Lightweight TCP/IP Stack (lwIP) to a network data buffer. - * - * When a network device is specified, the reserved space of the network device will be added to - * the size of the converted network data buffer. - * - * @param netdev Indicates the pointer to the network device. - * @param lwip_buf Indicates the pointer to the data buffer of lwIP. - * - * @return Returns the pointer to the network data buffer if the operation is successful; - * returns NULL otherwise. - * - * @since 1.0 - */ -struct NetBuf *Pbuf2NetBuf(const struct NetDevice *netdev, struct pbuf *lwipBuf); - -/** - * @brief Converts a network data buffer to the pbuf structure of Lightweight TCP/IP Stack (lwIP). - * - * @param nb Indicates the pointer to the network data buffer. - * - * @return Returns the pointer to the pbuf structure if the operation is successful; - * returns NULL otherwise. - * - * @since 1.0 - */ -struct pbuf *NetBuf2Pbuf(const struct NetBuf *nb); +int32_t NetBufConcat(NetBuf *nb, NetBuf *cnb); #ifdef __cplusplus #if __cplusplus @@ -464,3 +336,4 @@ struct pbuf *NetBuf2Pbuf(const struct NetBuf *nb); #endif /* __cplusplus */ #endif /* HDF_NETBUF_H */ +/** @} */ diff --git a/include/osal.h b/include/osal.h old mode 100755 new mode 100644 index 837354df..0153e1c1 --- a/include/osal.h +++ b/include/osal.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_H diff --git a/include/osal/osal_atomic.h b/include/osal/osal_atomic.h old mode 100755 new mode 100644 index db472553..63aaeed6 --- a/include/osal/osal_atomic.h +++ b/include/osal/osal_atomic.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * @@ -60,7 +37,7 @@ #ifndef OSAL_ATOMIC_H #define OSAL_ATOMIC_H -#include "hdf_base.h" +#include "osal_atomic_def.h" #ifdef __cplusplus extern "C" { @@ -68,6 +45,9 @@ extern "C" { /** * @brief Describes an atomic. + * + * @since 1.0 + * @version 1.0 */ typedef struct { volatile int32_t counter;/**< Counter (an atomic variable). @@ -81,10 +61,11 @@ typedef struct { * @param v Indicates the pointer to the atomic {@link OsalAtomic}. * * @return Returns the counter. + * * @since 1.0 * @version 1.0 */ -int32_t OsalAtomicRead(const OsalAtomic *v); +#define OsalAtomicRead(v) OsalAtomicReadWrapper(v) /** * @brief Sets the counter for an atomic. @@ -95,7 +76,7 @@ int32_t OsalAtomicRead(const OsalAtomic *v); * @since 1.0 * @version 1.0 */ -void OsalAtomicSet(OsalAtomic *v, int32_t counter); +#define OsalAtomicSet(v, counter) OsalAtomicSetWrapper(v, counter) /** * @brief Increments the counter of an atomic by 1. @@ -105,7 +86,19 @@ void OsalAtomicSet(OsalAtomic *v, int32_t counter); * @since 1.0 * @version 1.0 */ -void OsalAtomicInc(OsalAtomic *v); +#define OsalAtomicInc(v) OsalAtomicIncWrapper(v) + +/** + * @brief Increments the counter of an atomic by 1 and returns the new counter. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * + * @return Returns the new counter. + * + * @since 1.0 + * @version 1.0 + */ +#define OsalAtomicIncReturn(v) OsalAtomicIncRetWrapper(v) /** * @brief Decrements the counter of an atomic by 1. @@ -115,7 +108,19 @@ void OsalAtomicInc(OsalAtomic *v); * @since 1.0 * @version 1.0 */ -void OsalAtomicDec(OsalAtomic *v); +#define OsalAtomicDec(v) OsalAtomicDecWrapper(v) + +/** + * @brief Decrements the counter of an atomic by 1 and returns the new counter. + * + * @param v Indicates the pointer to the atomic {@link OsalAtomic}. + * + * @return Returns the new counter. + * + * @since 1.0 + * @version 1.0 + */ +#define OsalAtomicDecReturn(v) OsalAtomicDecRetWrapper(v) /** * @brief Tests the value of a specified bit of a variable. @@ -124,10 +129,11 @@ void OsalAtomicDec(OsalAtomic *v); * @param addr Indicates the pointer to the variable. * * @return Returns the bit value. + * * @since 1.0 * @version 1.0 */ -int32_t OsalTestBit(unsigned long nr, const volatile unsigned long *addr); +#define OsalTestBit(nr, addr) OsalTestBitWrapper(nr, addr) /** * @brief Sets the value of a specified bit of the variable and returns the bit value before the setting. @@ -136,10 +142,11 @@ int32_t OsalTestBit(unsigned long nr, const volatile unsigned long *addr); * @param addr Indicates the pointer to the variable. * * @return Returns the bit value before the setting. + * * @since 1.0 * @version 1.0 */ -int32_t OsalTestSetBit(unsigned long nr, volatile unsigned long *addr); +#define OsalTestSetBit(nr, addr) OsalTestSetBitWrapper(nr, addr) /** * @brief Clears the value of a specified bit of the variable and returns the bit value before clearing. @@ -148,10 +155,11 @@ int32_t OsalTestSetBit(unsigned long nr, volatile unsigned long *addr); * @param addr Indicates the pointer to the variable. * * @return Returns the bit value before the bit is cleared. + * * @since 1.0 * @version 1.0 */ -int32_t OsalTestClearBit(unsigned long nr, volatile unsigned long *addr); +#define OsalTestClearBit(nr, addr) OsalTestClearBitWrapper(nr, addr) /** * @brief Clears the value of a specified bit of the variable. @@ -162,7 +170,7 @@ int32_t OsalTestClearBit(unsigned long nr, volatile unsigned long *addr); * @since 1.0 * @version 1.0 */ -void OsalClearBit(unsigned long nr, volatile unsigned long *addr); +#define OsalClearBit(nr, addr) OsalClearBitWrapper(nr, addr) #ifdef __cplusplus } diff --git a/include/osal/osal_cdev.h b/include/osal/osal_cdev.h new file mode 100644 index 00000000..b6895493 --- /dev/null +++ b/include/osal/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/include/osal/osal_file.h b/include/osal/osal_file.h old mode 100755 new mode 100644 index 0601b391..482e56df --- a/include/osal/osal_file.h +++ b/include/osal/osal_file.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * @@ -58,7 +35,6 @@ #define OSAL_FILE_H #include "hdf_base.h" -#include #ifdef __cplusplus extern "C" { diff --git a/include/osal/osal_firmware.h b/include/osal/osal_firmware.h old mode 100755 new mode 100644 index 7c394cd7..6053643a --- a/include/osal/osal_firmware.h +++ b/include/osal/osal_firmware.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_io.h b/include/osal/osal_io.h old mode 100755 new mode 100644 index 916c55ee..358810da --- a/include/osal/osal_io.h +++ b/include/osal/osal_io.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * @@ -59,8 +36,7 @@ #ifndef OSAL_IO_H #define OSAL_IO_H -#include -#include +#include "osal_io_adapter.h" #ifdef __cplusplus extern "C" { diff --git a/include/osal/osal_irq.h b/include/osal/osal_irq.h old mode 100755 new mode 100644 index f0eb190c..51751c12 --- a/include/osal/osal_irq.h +++ b/include/osal/osal_irq.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * @@ -64,23 +41,27 @@ extern "C" { /** * @brief Enumerates interrupt trigger modes. * - * @since 1.1 + * @since 1.0 + * @version 1.0 */ typedef enum { OSAL_IRQF_TRIGGER_NONE = 0, /**< Edge-triggered is not set */ OSAL_IRQF_TRIGGER_RISING = 1, /**< Rising edge triggered */ - OSAL_IRQF_TRIGGER_FALLING = 2, /**< Failing edge triggered */ + OSAL_IRQF_TRIGGER_FALLING = 2, /**< Falling edge triggered */ OSAL_IRQF_TRIGGER_HIGH = 4, /**< High-level triggered */ OSAL_IRQF_TRIGGER_LOW = 8, /**< Low-level triggered */ } OSAL_IRQ_TRIGGER_MODE; /** * @brief Defines an IRQ type. + * + * @since 1.0 + * @version 1.0 */ typedef uint32_t (*OsalIRQHandle)(uint32_t irqId, void *dev); /** - * @brief Registers an IRQ. + * @brief Registers the function for processing the specified IRQ. * * @param irqId Indicates the IRQ ID. * @param config Indicates the interrupt trigger mode. For details, see {@link OSAL_IRQ_TRIGGER_MODE}. @@ -101,9 +82,11 @@ typedef uint32_t (*OsalIRQHandle)(uint32_t irqId, void *dev); int32_t OsalRegisterIrq(uint32_t irqId, uint32_t config, OsalIRQHandle handle, const char *name, void *dev); /** - * @brief Unregisters an IRQ. + * @brief Unregisters the interrupt processing function so that the system will no longer process the specified IRQ. * * @param irqId Indicates the IRQ ID. + * @param dev Indicates the pointer to the parameter passed to the interrupt processing function + * in {@link OsalRegisterIrq}. * * @return Returns a value listed below: \n * HDF_STATUS | Description @@ -115,10 +98,10 @@ int32_t OsalRegisterIrq(uint32_t irqId, uint32_t config, OsalIRQHandle handle, c * @since 1.0 * @version 1.0 */ -int32_t OsalUnregisterIrq(uint32_t irqId); +int32_t OsalUnregisterIrq(uint32_t irqId, void *dev); /** - * @brief Enables an IRQ. + * @brief Enables the processing of the specified IRQ. * * @param irqId Indicates the IRQ ID. * @@ -134,7 +117,7 @@ int32_t OsalUnregisterIrq(uint32_t irqId); int32_t OsalEnableIrq(uint32_t irqId); /** - * @brief Disables an IRQ. + * @brief Disables the IRQ function of a device. * * @param irqId Indicates the IRQ ID. * diff --git a/include/osal/osal_mem.h b/include/osal/osal_mem.h old mode 100755 new mode 100644 index f9516d63..1c4fa1c3 --- a/include/osal/osal_mem.h +++ b/include/osal/osal_mem.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_mutex.h b/include/osal/osal_mutex.h old mode 100755 new mode 100644 index 65d4a48a..17d0366b --- a/include/osal/osal_mutex.h +++ b/include/osal/osal_mutex.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_sem.h b/include/osal/osal_sem.h old mode 100755 new mode 100644 index fe59a08b..80409757 --- a/include/osal/osal_sem.h +++ b/include/osal/osal_sem.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_spinlock.h b/include/osal/osal_spinlock.h old mode 100755 new mode 100644 index a7c7a6f2..4531f827 --- a/include/osal/osal_spinlock.h +++ b/include/osal/osal_spinlock.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_thread.h b/include/osal/osal_thread.h old mode 100755 new mode 100644 index 796d03b4..136783e1 --- a/include/osal/osal_thread.h +++ b/include/osal/osal_thread.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * @@ -48,6 +25,9 @@ * * @brief Declares thread types and interfaces. * + * Threads created by the OSAL module are in the detached state. When releasing threads, the service module must + * first terminate its own threads and then {@link OsalThreadDestroy} can be called to release applied resources. + * * @since 1.0 * @version 1.0 */ @@ -62,6 +42,9 @@ extern "C" { /** * @brief Enumerates thread priorities. + * + * @since 1.0 + * @version 1.0 */ typedef enum { OSAL_THREAD_PRI_LOW, /**< Low priority */ @@ -72,28 +55,39 @@ typedef enum { /** * @brief Describes thread parameters. + * + * @since 1.0 + * @version 1.0 */ struct OsalThreadParam { char *name; /**< Thread name */ - size_t stackSize; /**< Stack size of a thread */ + size_t stackSize; /**< Thread stack size, which may cause thread stack overflow if it is too small */ OSAL_THREAD_PRIORITY priority; /**< Thread priority */ }; /** * @brief Defines a thread callback function type. + * + * @since 1.0 + * @version 1.0 */ typedef int (*OsalThreadEntry)(void *); /** * @brief Describes a thread. + * + * @since 1.0 + * @version 1.0 */ struct OsalThread { - int32_t status; /**< Thread running status */ void *realThread; /**< Pointer to a created thread object */ }; /** * @brief Defines a thread macro. + * + * @since 1.0 + * @version 1.0 */ #define OSAL_DECLARE_THREAD(thread) struct OsalThread thread @@ -115,6 +109,27 @@ struct OsalThread { * @version 1.0 */ int32_t OsalThreadCreate(struct OsalThread *thread, OsalThreadEntry threadEntry, void *entryPara); + +/** + * @brief Binds a thread to a specified CPU. + * + * Call this function before {@link OsalThreadStart} and after {@link OsalThreadCreate} + * if you need to run a created thread on a specified CPU. + * + * @param thread Indicates the pointer to the thread {@link OsalThread}. + * @param cpuID Indicates the ID of the specified CPU. + * + * @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 OsalThreadBind(struct OsalThread *thread, unsigned int cpuID); + /** * @brief Starts a thread. * @@ -169,7 +184,6 @@ int32_t OsalThreadSuspend(struct OsalThread *thread); * @brief Resumes a thread. * * @param thread Indicates the pointer to the thread {@link OsalThread}. - * @since 1.0 * @return Returns a value listed below: \n * HDF_STATUS | Description * ----------------------| ----------------------- @@ -177,6 +191,7 @@ int32_t OsalThreadSuspend(struct OsalThread *thread); * HDF_FAILURE | Failed to invoke the system function to resume the thread. * HDF_ERR_INVALID_PARAM | Invalid parameter. * + * @since 1.0 * @version 1.0 */ int32_t OsalThreadResume(struct OsalThread *thread); diff --git a/include/osal/osal_time.h b/include/osal/osal_time.h old mode 100755 new mode 100644 index 71152dab..b7496227 --- a/include/osal/osal_time.h +++ b/include/osal/osal_time.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/osal/osal_timer.h b/include/osal/osal_timer.h old mode 100755 new mode 100644 index 3adeb79c..23efecdb --- a/include/osal/osal_timer.h +++ b/include/osal/osal_timer.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -35,7 +12,7 @@ * * @brief Defines the structures and interfaces for the Operating System Abstraction Layer (OSAL) module. * - * The OSAL module harmonizes OS interface differences and provides unified OS interfaces externally, + * The OSAL module OpenHarmony OS interface differences and provides unified OS interfaces externally, * including the memory management, thread, mutex, spinlock, semaphore, timer, file, interrupt, time, * atomic, firmware, and I/O operation modules. * diff --git a/include/platform/emmc_if.h b/include/platform/emmc_if.h new file mode 100644 index 00000000..0d5a807e --- /dev/null +++ b/include/platform/emmc_if.h @@ -0,0 +1,105 @@ +/* + * 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. + */ + +/** + * @addtogroup EMMC + * @{ + * + * @brief Declares standard APIs of basic embedded multi media card (EMMC) capabilities. + * + * You can use this module to access the EMMC and enable the driver to operate an EMMC-compliant device. + * These capabilities include get CID of EMMC device. + * + * @since 1.0 + */ + + /** + * @file emmc_if.h + * + * @brief Declares the standard EMMC APIs. + * + * @since 1.0 + */ + +#ifndef EMMC_IF_H +#define EMMC_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Indicates that the CID len of EMMC device is 16 bytes. + * + * @since 1.0 + */ +#define EMMC_CID_LEN 16 + +/** + * @brief Opens an EMMC controller with a specified bus number. + * + * Before using the EMMC interface, you can obtain the device handle of the EMMC controller + * by calling {@link EmmcOpen}. This function is used in pair with {@link EmmcClose}. + * + * @param busNum Indicates the bus number. + * + * @return Returns the device handle {@link DevHandle} of the EMMC controller if the operation is successful; + * returns NULL otherwise. + * @since 1.0 + */ +DevHandle EmmcOpen(int16_t busNum); + +/** + * @brief Closes an EMMC controller. + * + * After the EMMC interface is used, you can close the EMMC controller by calling {@link EmmcClose}. + * This function is used in pair with {@link EmmcOpen}. + * + * @param handle Indicates the pointer to the device handle of the EMMC controller. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * + * @since 1.0 + */ +void EmmcClose(DevHandle handle); + +/** + * @brief Get The CID of EMMC device. + * + * @param handle Indicates the pointer to the device handle of the EMMC controller. + * @param cid Indicates the pointer to the CID to read. + * @param size Indicates the length of the CID. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * + * @since 1.0 + */ +int32_t EmmcGetCid(DevHandle handle, uint8_t *cid, uint32_t size); + +/** + * @brief Get The HUID(Hardware Unique ID, that is CID) of EMMC device, + * + * @param cid Indicates the pointer to the CID to read. + * @param size Indicates the length of the CID. + * + * @since 1.0 + */ +void EmmcGetHuid(uint8_t *cid, uint32_t size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* EMMC_IF_H */ +/** @} */ diff --git a/include/platform/gpio_if.h b/include/platform/gpio_if.h old mode 100755 new mode 100644 index b6277e46..8e1f1525 --- a/include/platform/gpio_if.h +++ b/include/platform/gpio_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -53,6 +30,7 @@ #define GPIO_IF_H #include "hdf_platform.h" +#include "osal_irq.h" #ifdef __cplusplus #if __cplusplus @@ -82,6 +60,26 @@ enum GpioDirType { GPIO_DIR_ERR, /**< Invalid direction */ }; +/** + * @brief Enumerates GPIO irq types. + * + * @since 1.0 + */ +enum GpioIrqType { + /** Trigger is not set */ + GPIO_IRQ_TRIGGER_NONE = OSAL_IRQF_TRIGGER_NONE, + /** Rising edge triggered */ + GPIO_IRQ_TRIGGER_RISING = OSAL_IRQF_TRIGGER_RISING, + /** Falling edge triggered */ + GPIO_IRQ_TRIGGER_FALLING = OSAL_IRQF_TRIGGER_FALLING, + /** High-level triggered */ + GPIO_IRQ_TRIGGER_HIGH = OSAL_IRQF_TRIGGER_HIGH, + /** Low-level triggered */ + GPIO_IRQ_TRIGGER_LOW = OSAL_IRQF_TRIGGER_LOW, + /** execute interrupt service routine in thread context */ + GPIO_IRQ_USING_THREAD = (0x1 << 8), +}; + /** * @brief Defines the function type of a GPIO interrupt service routine (ISR). * diff --git a/include/platform/hdf_platform.h b/include/platform/hdf_platform.h old mode 100755 new mode 100644 index 040e5afe..970eef64 --- a/include/platform/hdf_platform.h +++ b/include/platform/hdf_platform.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -67,10 +44,7 @@ extern "C" { * * @since 1.0 */ -struct DevHandle { - /** Pointer to a specific platform device */ - void *object; -}; +typedef void* DevHandle; #ifdef __cplusplus #if __cplusplus diff --git a/include/platform/i2c_if.h b/include/platform/i2c_if.h old mode 100755 new mode 100644 index a78c518a..9ff1f251 --- a/include/platform/i2c_if.h +++ b/include/platform/i2c_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -128,7 +105,7 @@ enum I2cFlag { * returns NULL otherwise. * @since 1.0 */ -struct DevHandle *I2cOpen(int16_t number); +DevHandle I2cOpen(int16_t number); /** * @brief Releases the handle of an I2C controller. @@ -140,7 +117,7 @@ struct DevHandle *I2cOpen(int16_t number); * * @since 1.0 */ -void I2cClose(struct DevHandle *handle); +void I2cClose(DevHandle handle); /** * @brief Launches a custom transfer to an I2C device. @@ -157,7 +134,7 @@ void I2cClose(struct DevHandle *handle); * * @since 1.0 */ -int32_t I2cTransfer(struct DevHandle *handle, struct I2cMsg *msgs, int16_t count); +int32_t I2cTransfer(DevHandle handle, struct I2cMsg *msgs, int16_t count); #ifdef __cplusplus #if __cplusplus diff --git a/include/platform/mipi_dsi_if.h b/include/platform/mipi_dsi_if.h new file mode 100644 index 00000000..9e173de5 --- /dev/null +++ b/include/platform/mipi_dsi_if.h @@ -0,0 +1,287 @@ +/* + * 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. + */ + +/** + * @addtogroup MIPI DSI + * @{ + * + * @brief Defines standard MIPI DSI APIs for display driver development. + * + * This MIPI DSI module abstracts MIPI DSI capabilities of different system platforms to provide stable APIs + * for display driver development. You can use this module to obtain/release the MIPI DSI device handle, + * initialize the MIPI DSI device, and send/receive commands that interact with display peripherals. + * + * @since 1.0 + */ + +/** + * @file mipi_dsi_if.h + * + * @brief Declares standard MIPI DSI APIs for display driver development. + * + * + * + * @since 1.0 + */ + +#ifndef MIPI_DSI_IF_H +#define MIPI_DSI_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Enumerates the supported DSI operation modes. + * + * You can specify the operation mode via {@link MipiDsiSetCfg}. + * + * @since 1.0 + */ +enum DsiMode { +/** Invalid mode */ + DSI_NONE = 0, +/** Video mode */ + DSI_VIDEO_MODE, +/** Command mode */ + DSI_CMD_MODE, +}; + +/** + * @brief Enumerates the number of data lanes connected to the DSI device. + * + * You can specify the number of data lanes via {@link MipiDsiSetCfg}. + * + * @since 1.0 + */ +enum DsiLane { +/** One data lane is connected to the display device. */ + DSI_1_LANES = 1, +/** Two data lanes are connected to the display device. */ + DSI_2_LANES, +/** Three data lanes are connected to the display device */ + DSI_3_LANES, +/** Four data lanes are connected to the display device. */ + DSI_4_LANES, +}; + +/** + * @brief Enumerates the synchronization modes used for data transmission in Video mode. + * This enumeration is invalid in Command mode. + * + * You can specify the synchronization mode via {@link MipiDsiSetCfg}. + * + * @since 1.0 + */ +enum DsiBurstMode { +/** Pixel data is transferred efficiently using a time-compressed burst format, + leaving more time during a scan line for low power (LP) mode and reducing the DSI power consumption. */ + VIDEO_BURST_MODE = 0x0, +/** Peripherals can accurately reproduce original video timing, including synchronization pulse widths. */ + VIDEO_NON_BURST_MODE_SYNC_PULSES = 0x1, +/** Peripherals can accurately reproduce original video timing, + but accurate synchronization pulse widths are not required. */ + VIDEO_NON_BURST_MODE_SYNC_EVENTS = 0x2, +}; + +/** + * @brief Enumerates the output DSI image data formats. + * + * You can specify the image data format via {@link MipiDsiSetCfg}. + * + * @since 1.0 + */ +enum DsiOutFormat { +/** 16-bit RGB */ + FORMAT_RGB_16_BIT = 0x0, +/** 18-bit RGB */ + FORMAT_RGB_18_BIT = 0x1, +/** 24-bit RGB */ + FORMAT_RGB_24_BIT = 0x2, +/** 8-bit YUV420 */ + FORMAT_YUV420_8_BIT_NORMAL = 0x3, +/** Legacy-version 8-bit YUV420 */ + FORMAT_YUV420_8_BIT_LEGACY = 0x4, +/** 8-bit YUV422 */ + FORMAT_YUV422_8_BIT = 0x5, +/** Invalid value */ + FORMAT_BUTT +}; + +/** + * @brief Defines the MIPI DSI timing information. + * + * Before image data transmission, you must specify the timing parameters + * to ensure that images can be correctly displayed on the screen. + * + * @since 1.0 + */ +struct DsiTimingInfo { +/** Effective pixels in the X direction, that is, resolution of the peer screen in the X direction */ + uint16_t xPixels; +/** Horizontal sync active (HSA) pixels in the X direction, which is specified based on the peer screen */ + uint16_t hsaPixels; +/** Horizontal back porch (HBP) pixels in the X direction, which is specified based on the peer screen */ + uint16_t hbpPixels; +/** Total number of pixels in the X direction. The value is equal to + the sum value of xResPixels, hsaPixels, hbpPixels, and hfpPixels. */ + uint16_t hlinePixels; +/** Vertical sync active (VSA) lines in the Y direction, which is specified based on the peer screen */ + uint16_t vsaLines; +/** Vertical back porch (VBP) lines in the Y direction, which is specified based on the peer screen */ + uint16_t vbpLines; +/** Vertical front porch (VFP) lines in the Y direction, which is specified based on the peer screen */ + uint16_t vfpLines; +/** Effective lines in the Y direction, that is, resolution of the peer screen in the Y direction */ + uint16_t ylines; +/** Number of bytes of the command for writing memory. + This parameter is invalid in Video mode and is set to xPixels in Command mode. */ + uint16_t edpiCmdSize; +}; + +/** + * @brief Defines MIPI DSI configuration parameters. + * + * Before image data transmission, you must set MIPI DSI configuration parameters to ensure + * that images can be correctly displayed on the screen. + * + * @since 1.0 + */ +struct MipiCfg { +/** Number of MIPI DSI lanes connected to the display device */ + enum DsiLane lane; +/** Refresh mode (Video mode or Command mode) supported by the display device */ + enum DsiMode mode; +/** Synchronous mode of the display device, which is valid only in Video mode */ + enum DsiBurstMode burstMode; +/** Format of the output DSI image data. For details, see {@link DsiOutFormat}. */ + enum DsiOutFormat format; +/** MIPI DSI timing information, which is set based on the display device requirements */ + struct DsiTimingInfo timing; +/** MIPI DSI clock (unit: Mbit/s) */ + uint32_t phyDataRate; +/** Pixel clock output by the MIPI DSI (unit: kHz) */ + uint32_t pixelClk; +}; + +/** + * @brief Defines a MIPI DSI command. + * + * + * + * @since 1.0 + */ +struct DsiCmdDesc { +/** MIPI data type. For details about available values, see the MIPI protocol. */ + uint16_t dataType; +/** Delay required after the command is sent, in ms */ + uint16_t delay; +/** Length of the transferred data */ + uint16_t dataLen; +/** Pointer to the data to be transferred */ + uint8_t *payload; +}; + +/** + * @brief Obtains the MIPI DSI device handle with a specified channel ID. + * + * @param id Indicates the MIPI DSI channel ID. + * + * @return Returns the MIPI DSI device handle if the operation is successful; returns NULL otherwise. + * + * @since 1.0 + */ +DevHandle MipiDsiOpen(uint8_t id); + +/** + * @brief Releases the MIPI DSI device handle. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * + * @since 1.0 + */ +void MipiDsiClose(DevHandle handle); +/** + * @brief Sets configuration parameters for a MIPI DSI device. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * @param cfg Indicates the pointer to the configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t MipiDsiSetCfg(DevHandle handle, struct MipiCfg *cfg); + +/** + * @brief Obtains the configuration parameters of a MIPI DSI device. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * @param cfg Indicates the pointer to the configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t MipiDsiGetCfg(DevHandle handle, struct MipiCfg *cfg); + +/** + * @brief Sets LP mode for a MIPI DSI device. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * + * @since 1.0 + */ +void MipiDsiSetLpMode(DevHandle handle); + +/** + * @brief Sets the high-speed (HS) mode for a MIPI DSI device. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * + * @since 1.0 + */ +void MipiDsiSetHsMode(DevHandle handle); + +/** + * @brief Sends a display command set (DCS) command used for sending the initial parameters of a peripheral. + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * @param cmd Indicates the pointer to the command to be sent. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t MipiDsiTx(DevHandle handle, struct DsiCmdDesc *cmd); + +/** +* @brief Receives a DCS command used for reading data, such as the status and parameters of a peripheral + * + * @param handle Indicates the MIPI DSI device handle obtained via {@link MipiDsiOpen}. + * @param cmd Indicates the pointer to the command to be received. + * @param readLen Indicates the length of the data to read, in bytes. + * @param out Indicates the pointer to the read data. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t MipiDsiRx(DevHandle handle, struct DsiCmdDesc *cmd, int32_t readLen, uint8_t *out); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* MIPI_DSI_IF_H */ diff --git a/include/platform/pwm_if.h b/include/platform/pwm_if.h new file mode 100644 index 00000000..a7fb0b08 --- /dev/null +++ b/include/platform/pwm_if.h @@ -0,0 +1,209 @@ +/* + * 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. + */ + +/** + * @addtogroup PWM + * @{ + * + * @brief Provides standard pulse width modulation (PWM) interfaces for driver development. + * + * The PWM module abstracts the PWM capabilities of different system platforms to provide stable APIs for driver + * development. You can use this module to create/release PWM device handles, set the PWM period, polarity, and duty + * cycle, enable/disable PWM devices, and set/obtain the PWM configuration. + * + * @since 1.0 + */ + +/** + * @file pwm_if.h + * + * @brief Declares standard PWM interfaces for driver development. + * + * A driver needs to use the PWM interfaces to perform operations on a PWM device. + * + * @since 1.0 + */ + +#ifndef PWM_IF_H +#define PWM_IF_H + +#include "hdf_platform.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Indicates the normal polarity of a PWM device. + * + * @since 1.0 + */ +#define PWM_NORMAL_POLARITY 0 + +/** + * @brief Indicates the inverted polarity of a PWM device. + * + * @since 1.0 + */ +#define PWM_INVERTED_POLARITY 1 + +/** + * @brief Indicates that a PWM device is in the disabled state. + * + * @since 1.0 + */ +#define PWM_DISABLE_STATUS 0 + +/** + * @brief Indicates that a PWM device is in the enabled state. + * + * @since 1.0 + */ +#define PWM_ENABLE_STATUS 1 + +/** + * @brief Defines the PWM device configuration parameters. + * + * @attention The specific PWM device determines which variables in this structure are supported. + * + * @since 1.0 + */ +struct PwmConfig { + uint32_t duty; /**< Duty cycle, in nanoseconds */ + uint32_t period; /**< PWM period, in nanoseconds */ + uint32_t number; /**< Number of square waves to generate. A positive value indicates that + * the specified number of square waves will be generated, and 0 indicates + * that square waves will be continuously generated. + */ + uint8_t polarity; /**< Polarity + * --------------------- | --------------------- + * PWM_NORMAL_POLARITY | Normal polarity + * PWM_INVERTED_POLARITY | Inverted polarity + */ + uint8_t status; /**< Running status + * ------------------ | ------------------ + * PWM_DISABLE_STATUS | Disabled + * PWM_ENABLE_STATUS | Enabled + */ +}; + +/** + * @brief Obtains the PWM device handle. + * + * @param num Indicates the PWM device number. + * + * @return Returns the PWM device handle if the operation is successful; returns NULL otherwise. + * + * @since 1.0 + */ +DevHandle PwmOpen(uint32_t num); + +/** + * @brief Releases the PWM device handle. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * + * @since 1.0 + */ +void PwmClose(DevHandle handle); + +/** + * @brief Sets the PWM period. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * @param period Indicates the PWM device period to set, in nanoseconds. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmSetPeriod(DevHandle handle, uint32_t period); + +/** + * @brief Sets the PWM duty cycle. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * @param duty Indicates the duty cycle to set, in nanoseconds. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmSetDuty(DevHandle handle, uint32_t duty); + +/** + * @brief Sets the PWM polarity. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * @param polarity Indicates the polarity to set, which can be {@link PWM_NORMAL_POLARITY} + * or {@link PWM_INVERTED_POLARITY}. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmSetPolarity(DevHandle handle, uint8_t polarity); + +/** + * @brief Enables the PWM device. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmEnable(DevHandle handle); + +/** + * @brief Disables the PWM device. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmDisable(DevHandle handle); + +/** + * @brief Sets the PWM device configuration parameters. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * @param config Indicates the pointer to the {@link PwmConfig} structure that + * contains PWM device configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmSetConfig(DevHandle handle, struct PwmConfig *config); + +/** + * @brief Obtains the PWM device configuration parameters. + * + * @param handle Indicates the PWM device handle obtained via {@link PwmOpen}. + * @param config Indicates the pointer to the {@link PwmConfig} structure that contains + * PWM device configuration parameters. + * + * @return Returns 0 if the operation is successful; returns a negative value otherwise. + * + * @since 1.0 + */ +int32_t PwmGetConfig(DevHandle handle, struct PwmConfig *config); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PWM_IF_H */ +/** @} */ diff --git a/include/platform/rtc_if.h b/include/platform/rtc_if.h old mode 100755 new mode 100644 index b73a433f..2f8a454d --- a/include/platform/rtc_if.h +++ b/include/platform/rtc_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -106,7 +83,7 @@ struct RtcTime { * @return Returns {@link DevHandle} if the operation is successful; returns NULL if the operation fails. * @since 1.0 */ -struct DevHandle *RtcOpen(void); +DevHandle RtcOpen(void); /** * @brief Releases a specified handle of the RTC device. @@ -115,7 +92,7 @@ struct DevHandle *RtcOpen(void); * * @since 1.0 */ -void RtcClose(struct DevHandle *handle); +void RtcClose(DevHandle handle); /** * @brief Reads time from the RTC driver. @@ -130,7 +107,7 @@ void RtcClose(struct DevHandle *handle); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcReadTime(struct DevHandle *handle, struct RtcTime *time); +int32_t RtcReadTime(DevHandle handle, struct RtcTime *time); /** * @brief Writes format-compliant time to the RTC driver. @@ -145,7 +122,7 @@ int32_t RtcReadTime(struct DevHandle *handle, struct RtcTime *time); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time); +int32_t RtcWriteTime(DevHandle handle, const struct RtcTime *time); /** * @brief Reads the RTC alarm time that was set last time. @@ -158,7 +135,7 @@ int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcReadAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time); +int32_t RtcReadAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time); /** * @brief Writes the RTC alarm time based on the alarm index. @@ -174,7 +151,7 @@ int32_t RtcReadAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, st * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time); +int32_t RtcWriteAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time); /** * @brief Registers {@link RtcAlarmCallback} that will be invoked when an alarm is generated at the specified time. @@ -187,7 +164,7 @@ int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, c * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcRegisterAlarmCallback(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb); +int32_t RtcRegisterAlarmCallback(DevHandle handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb); /** * @brief Enables or disables alarm interrupts. @@ -204,7 +181,7 @@ int32_t RtcRegisterAlarmCallback(struct DevHandle *handle, enum RtcAlarmIndex al * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcAlarmInterruptEnable(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, uint8_t enable); +int32_t RtcAlarmInterruptEnable(DevHandle handle, enum RtcAlarmIndex alarmIndex, uint8_t enable); /** * @brief Reads the RTC external frequency. @@ -218,7 +195,7 @@ int32_t RtcAlarmInterruptEnable(struct DevHandle *handle, enum RtcAlarmIndex ala * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq); +int32_t RtcGetFreq(DevHandle handle, uint32_t *freq); /** * @brief Sets the frequency of the external crystal oscillator connected to the RTC driver. @@ -233,7 +210,7 @@ int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcSetFreq(struct DevHandle *handle, uint32_t freq); +int32_t RtcSetFreq(DevHandle handle, uint32_t freq); /** * @brief Resets the RTC driver. @@ -246,7 +223,7 @@ int32_t RtcSetFreq(struct DevHandle *handle, uint32_t freq); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcReset(struct DevHandle *handle); +int32_t RtcReset(DevHandle handle); /** * @brief Reads the configuration of a custom RTC register based on the register index. @@ -261,7 +238,7 @@ int32_t RtcReset(struct DevHandle *handle); * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcReadReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t *value); +int32_t RtcReadReg(DevHandle handle, uint8_t usrDefIndex, uint8_t *value); /** * @brief Writes the configuration of a custom RTC register based on the register index. @@ -276,7 +253,7 @@ int32_t RtcReadReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t *value * For details, see {@link HDF_STATUS}. * @since 1.0 */ -int32_t RtcWriteReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t value); +int32_t RtcWriteReg(DevHandle handle, uint8_t usrDefIndex, uint8_t value); #ifdef __cplusplus #if __cplusplus diff --git a/include/platform/sdio_if.h b/include/platform/sdio_if.h old mode 100755 new mode 100644 index a26c9e4d..743fe322 --- a/include/platform/sdio_if.h +++ b/include/platform/sdio_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -127,7 +104,7 @@ typedef void SdioIrqHandler(void *); * returns NULL otherwise. * @since 1.0 */ -struct DevHandle *SdioOpen(int16_t busNum); +DevHandle SdioOpen(int16_t busNum); /** * @brief Closes an SDIO controller. @@ -139,7 +116,7 @@ struct DevHandle *SdioOpen(int16_t busNum); * * @since 1.0 */ -void SdioClose(struct DevHandle *handle); +void SdioClose(DevHandle handle); /** * @brief Incrementally reads a given length of data from the specified SDIO address. @@ -158,7 +135,7 @@ void SdioClose(struct DevHandle *handle); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, +int32_t SdioReadBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -178,7 +155,7 @@ int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, +int32_t SdioWriteBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -198,7 +175,7 @@ int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, +int32_t SdioReadBytesFromFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -218,7 +195,7 @@ int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, +int32_t SdioWriteBytesToFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -237,7 +214,7 @@ int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, +int32_t SdioReadBytesFromFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -256,7 +233,7 @@ int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, +int32_t SdioWriteBytesToFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut); /** @@ -271,7 +248,7 @@ int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioSetBlockSize(struct DevHandle *handle, uint32_t blockSize); +int32_t SdioSetBlockSize(DevHandle handle, uint32_t blockSize); /** * @brief Obtains common information. @@ -287,7 +264,7 @@ int32_t SdioSetBlockSize(struct DevHandle *handle, uint32_t blockSize); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType); +int32_t SdioGetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType); /** * @brief Sets common information. @@ -303,7 +280,7 @@ int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCo * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType); +int32_t SdioSetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType); /** * @brief Flushes data. @@ -315,7 +292,7 @@ int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCo * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioFlushData(struct DevHandle *handle); +int32_t SdioFlushData(DevHandle handle); /** * @brief Claims a host exclusively. @@ -328,7 +305,7 @@ int32_t SdioFlushData(struct DevHandle *handle); * * @since 1.0 */ -void SdioClaimHost(struct DevHandle *handle); +void SdioClaimHost(DevHandle handle); /** * @brief Releases the exclusively claimed host. @@ -339,7 +316,7 @@ void SdioClaimHost(struct DevHandle *handle); * * @since 1.0 */ -void SdioReleaseHost(struct DevHandle *handle); +void SdioReleaseHost(DevHandle handle); /** * @brief Enables the SDIO device so that its register can be accessed. @@ -349,7 +326,7 @@ void SdioReleaseHost(struct DevHandle *handle); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioEnableFunc(struct DevHandle *handle); +int32_t SdioEnableFunc(DevHandle handle); /** * @brief Disables the SDIO device. @@ -361,7 +338,7 @@ int32_t SdioEnableFunc(struct DevHandle *handle); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioDisableFunc(struct DevHandle *handle); +int32_t SdioDisableFunc(DevHandle handle); /** * @brief Claims an SDIO IRQ. @@ -374,7 +351,7 @@ int32_t SdioDisableFunc(struct DevHandle *handle); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler); +int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler *irqHandler); /** * @brief Releases an SDIO IRQ. @@ -386,7 +363,7 @@ int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler); * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. * @since 1.0 */ -int32_t SdioReleaseIrq(struct DevHandle *handle); +int32_t SdioReleaseIrq(DevHandle handle); #ifdef __cplusplus #if __cplusplus @@ -395,4 +372,4 @@ int32_t SdioReleaseIrq(struct DevHandle *handle); #endif /* __cplusplus */ #endif /* SDIO_IF_H */ -/** @} */ \ No newline at end of file +/** @} */ diff --git a/include/platform/spi_if.h b/include/platform/spi_if.h old mode 100755 new mode 100644 index ea4f4752..166bd921 --- a/include/platform/spi_if.h +++ b/include/platform/spi_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -199,7 +176,7 @@ struct SpiCfg { * * @since 1.0 */ -struct DevHandle *SpiOpen(const struct SpiDevInfo *info); +DevHandle SpiOpen(const struct SpiDevInfo *info); /** * @brief Releases the handle of an SPI device. @@ -208,7 +185,7 @@ struct DevHandle *SpiOpen(const struct SpiDevInfo *info); * * @since 1.0 */ -void SpiClose(struct DevHandle *handle); +void SpiClose(DevHandle handle); /** * @brief Launches a custom transfer to an SPI device. @@ -221,7 +198,7 @@ void SpiClose(struct DevHandle *handle); * @see SpiMsg * @since 1.0 */ -int32_t SpiTransfer(struct DevHandle *handle, struct SpiMsg *msgs, uint32_t count); +int32_t SpiTransfer(DevHandle handle, struct SpiMsg *msgs, uint32_t count); /** * @brief Reads data of a specified length from an SPI device. @@ -234,7 +211,7 @@ int32_t SpiTransfer(struct DevHandle *handle, struct SpiMsg *msgs, uint32_t coun * * @since 1.0 */ -int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len); +int32_t SpiRead(DevHandle handle, uint8_t *buf, uint32_t len); /** * @brief Writes data of a specified length to an SPI device. @@ -247,7 +224,7 @@ int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len); * * @since 1.0 */ -int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len); +int32_t SpiWrite(DevHandle handle, uint8_t *buf, uint32_t len); /** * @brief Sets configuration parameters for an SPI device. @@ -259,7 +236,7 @@ int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len); * * @since 1.0 */ -int32_t SpiSetCfg(struct DevHandle *handle, struct SpiCfg *cfg); +int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg); /** * @brief Obtains the configuration parameters of an SPI device. @@ -271,7 +248,7 @@ int32_t SpiSetCfg(struct DevHandle *handle, struct SpiCfg *cfg); * * @since 1.0 */ -int32_t SpiGetCfg(struct DevHandle *handle, struct SpiCfg *cfg); +int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg); #ifdef __cplusplus #if __cplusplus diff --git a/include/platform/uart_if.h b/include/platform/uart_if.h old mode 100755 new mode 100644 index 15394259..1269dde6 --- a/include/platform/uart_if.h +++ b/include/platform/uart_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -266,6 +243,23 @@ enum UartTransMode { UART_MODE_DMA_TX_DIS, /**< DMA disabled for data transmitting */ }; +/** + * @brief Enumerates UART I/O commands. + * + * @since 1.0 + */ +enum UartIoCmd { + UART_IO_INIT = 0, /**< Initialize the UART device. */ + UART_IO_DEINIT, /**< Deinitialize the UART device. */ + UART_IO_READ, /**< Read data. */ + UART_IO_WRITE, /**< Write data. */ + UART_IO_GET_BAUD, /**< Obtain the baud rate. */ + UART_IO_SET_BAUD, /**< Set the baud rate. */ + UART_IO_GET_ATTRIBUTE, /**< Obtain the device attributes. */ + UART_IO_SET_ATTRIBUTE, /**< Set the device attributes. */ + UART_IO_SET_TRANSMODE, /**< Set the transmission mode. */ +}; + /** * @brief Obtains the UART device handle. * @@ -276,7 +270,7 @@ enum UartTransMode { * @return Returns the pointer to the UART device handle if the handle is obtained; returns NULL otherwise. * @since 1.0 */ -struct DevHandle *UartOpen(uint32_t port); +DevHandle UartOpen(uint32_t port); /** * @brief Releases the UART device handle. @@ -288,7 +282,7 @@ struct DevHandle *UartOpen(uint32_t port); * * @since 1.0 */ -void UartClose(struct DevHandle *handle); +void UartClose(DevHandle handle); /** * @brief Reads data of a specified size from a UART device. @@ -300,7 +294,7 @@ void UartClose(struct DevHandle *handle); * @return Returns the size of the data that is successfully read; returns a negative number if the reading fails. * @since 1.0 */ -int32_t UartRead(struct DevHandle *handle, uint8_t *data, uint32_t size); +int32_t UartRead(DevHandle handle, uint8_t *data, uint32_t size); /** * @brief Writes data of a specified size into a UART device. @@ -312,7 +306,7 @@ int32_t UartRead(struct DevHandle *handle, uint8_t *data, uint32_t size); * @return Returns 0 if the data is successfully written; returns a negative number otherwise. * @since 1.0 */ -int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size); +int32_t UartWrite(DevHandle handle, uint8_t *data, uint32_t size); /** * @brief Obtains the baud rate of the UART device. @@ -323,7 +317,7 @@ int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size); * @return Returns 0 if the baud rate is obtained; returns a negative number otherwise. * @since 1.0 */ -int32_t UartGetBaud(struct DevHandle *handle, uint32_t *baudRate); +int32_t UartGetBaud(DevHandle handle, uint32_t *baudRate); /** * @brief Sets the baud rate for the UART device. @@ -334,7 +328,7 @@ int32_t UartGetBaud(struct DevHandle *handle, uint32_t *baudRate); * @return Returns 0 if the setting is successful; returns a negative number otherwise. * @since 1.0 */ -int32_t UartSetBaud(struct DevHandle *handle, uint32_t baudRate); +int32_t UartSetBaud(DevHandle handle, uint32_t baudRate); /** * @brief Obtains the UART attribute. @@ -346,7 +340,7 @@ int32_t UartSetBaud(struct DevHandle *handle, uint32_t baudRate); * * @return Returns 0 if the UART attribute is obtained; returns a negative number otherwise. * @since 1.0 */ -int32_t UartGetAttribute(struct DevHandle *handle, struct UartAttribute *attribute); +int32_t UartGetAttribute(DevHandle handle, struct UartAttribute *attribute); /** * @brief Sets the UART attribute. @@ -359,7 +353,7 @@ int32_t UartGetAttribute(struct DevHandle *handle, struct UartAttribute *attribu * @return Returns 0 if the setting is successful; returns a negative number otherwise. * @since 1.0 */ -int32_t UartSetAttribute(struct DevHandle *handle, struct UartAttribute *attribute); +int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute); /** * @brief Sets the UART transmission mode. @@ -370,7 +364,7 @@ int32_t UartSetAttribute(struct DevHandle *handle, struct UartAttribute *attribu * @return Returns 0 if the setting is successful; returns a negative number otherwise. * @since 1.0 */ -int32_t UartSetTransMode(struct DevHandle *handle, enum UartTransMode mode); +int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode); #ifdef __cplusplus #if __cplusplus diff --git a/include/platform/watchdog_if.h b/include/platform/watchdog_if.h old mode 100755 new mode 100644 index 8816e2c4..be268267 --- a/include/platform/watchdog_if.h +++ b/include/platform/watchdog_if.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -86,7 +63,7 @@ enum WatchdogStatus { * * @since 1.0 */ -struct DevHandle *WatchdogOpen(int16_t wdtId); +DevHandle WatchdogOpen(int16_t wdtId); /** * @brief Closes a watchdog. @@ -98,7 +75,7 @@ struct DevHandle *WatchdogOpen(int16_t wdtId); * * @since 1.0 */ -void WatchdogClose(struct DevHandle *handle); +void WatchdogClose(DevHandle handle); /** * @brief Obtains the watchdog status. @@ -112,7 +89,7 @@ void WatchdogClose(struct DevHandle *handle); * * @since 1.0 */ -int32_t WatchdogGetStatus(struct DevHandle *handle, int32_t *status); +int32_t WatchdogGetStatus(DevHandle handle, int32_t *status); /** * @brief Starts a watchdog. @@ -128,7 +105,7 @@ int32_t WatchdogGetStatus(struct DevHandle *handle, int32_t *status); * * @since 1.0 */ -int32_t WatchdogStart(struct DevHandle *handle); +int32_t WatchdogStart(DevHandle handle); /** * @brief Stops a watchdog. @@ -140,7 +117,7 @@ int32_t WatchdogStart(struct DevHandle *handle); * @return Returns 0 if the watchdog is successfully stopped; returns a negative value otherwise. * @since 1.0 */ -int32_t WatchdogStop(struct DevHandle *handle); +int32_t WatchdogStop(DevHandle handle); /** * @brief Sets the watchdog timeout duration. @@ -151,7 +128,7 @@ int32_t WatchdogStop(struct DevHandle *handle); * @return Returns 0 if the setting is successful; returns a negative value otherwise. * @since 1.0 */ -int32_t WatchdogSetTimeout(struct DevHandle *handle, uint32_t seconds); +int32_t WatchdogSetTimeout(DevHandle handle, uint32_t seconds); /** * @brief Obtains the watchdog timeout duration. @@ -162,7 +139,7 @@ int32_t WatchdogSetTimeout(struct DevHandle *handle, uint32_t seconds); * @return Returns 0 if the watchdog timeout duration is obtained; returns a negative value otherwise. * @since 1.0 */ -int32_t WatchdogGetTimeout(struct DevHandle *handle, uint32_t *seconds); +int32_t WatchdogGetTimeout(DevHandle handle, uint32_t *seconds); /** * @brief Feeds a watchdog, that is, resets a watchdog timer. @@ -175,7 +152,7 @@ int32_t WatchdogGetTimeout(struct DevHandle *handle, uint32_t *seconds); * @return Returns 0 if the watchdog is fed; returns a negative value otherwise. * @since 1.0 */ -int32_t WatchdogFeed(struct DevHandle *handle); +int32_t WatchdogFeed(DevHandle handle); #ifdef __cplusplus #if __cplusplus diff --git a/include/utils/hdf_base.h b/include/utils/hdf_base.h old mode 100755 new mode 100644 index 3d07aa35..3996738b --- a/include/utils/hdf_base.h +++ b/include/utils/hdf_base.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -53,13 +30,7 @@ #ifndef HDF_BASE_TYPE_H #define HDF_BASE_TYPE_H -#if defined(__KERNEL__) -#include -#else -#include -#include -#include -#endif +#include "hdf_types.h" #ifdef __cplusplus extern "C" { diff --git a/include/utils/hdf_dlist.h b/include/utils/hdf_dlist.h old mode 100755 new mode 100644 index 531420e7..cc243f40 --- a/include/utils/hdf_dlist.h +++ b/include/utils/hdf_dlist.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup DriverUtils diff --git a/include/utils/hdf_log.h b/include/utils/hdf_log.h old mode 100755 new mode 100644 index 397e7270..b4759eb4 --- a/include/utils/hdf_log.h +++ b/include/utils/hdf_log.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** @@ -68,23 +45,12 @@ #define LOG_TAG LOG_TAG_MARK(HDF_LOG_TAG) #endif /* LOG_TAG */ -#if defined(_LINUX_USER_) -#include "cutils/log.h" -#elif defined(__KERNEL__) -#include -#elif defined(__LITEOS__) && defined(__USER__) -#include -#elif defined(__LITEOS__) -#include "los_printf.h" -#else -#include -#endif /* __KERNEL__ */ +#include "hdf_log_adapter.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -#if defined(_LINUX_USER_) /** * @brief Prints logs at the verbose level. * @@ -93,7 +59,7 @@ extern "C" { * @since 1.0 * @version 1.0 */ -#define HDF_LOGV(...) ALOGV(__VA_ARGS__) +#define HDF_LOGV(fmt, args...) HDF_LOGV_WRAPPER(fmt, ##args) /** * @brief Prints logs at the debug level. * @@ -102,7 +68,7 @@ extern "C" { * @since 1.0 * @version 1.0 */ -#define HDF_LOGD(...) ALOGD(__VA_ARGS__) +#define HDF_LOGD(fmt, args...) HDF_LOGD_WRAPPER(fmt, ##args) /** * @brief Prints logs at the information level. * @@ -111,8 +77,7 @@ extern "C" { * @since 1.0 * @version 1.0 */ -#define HDF_LOGI(...) ALOGI(__VA_ARGS__) - +#define HDF_LOGI(fmt, args...) HDF_LOGI_WRAPPER(fmt, ##args) /** * @brief Prints logs at the warning level. * @@ -121,8 +86,7 @@ extern "C" { * @since 1.0 * @version 1.0 */ -#define HDF_LOGW(...) ALOGW(__VA_ARGS__) - +#define HDF_LOGW(fmt, args...) HDF_LOGW_WRAPPER(fmt, ##args) /** * @brief Prints logs at the error level. * @@ -131,198 +95,7 @@ extern "C" { * @since 1.0 * @version 1.0 */ -#define HDF_LOGE(...) ALOGE(__VA_ARGS__) - -#elif defined(__KERNEL__) -#define _HDF_FMT_TAG(TAG, LEVEL) "[" #LEVEL "/" #TAG "] " -#define HDF_FMT_TAG(TAG, LEVEL) _HDF_FMT_TAG(TAG, LEVEL) - -/** - * @brief Prints logs at the verbose level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGV(fmt, args...) printk(KERN_DEBUG HDF_FMT_TAG(HDF_LOG_TAG, V) fmt, ## args) -/** - * @brief Prints logs at the debug level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGD(fmt, args...) printk(KERN_DEBUG HDF_FMT_TAG(HDF_LOG_TAG, D) fmt, ## args) -/** - * @brief Prints logs at the information level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGI(fmt, args...) printk(KERN_INFO HDF_FMT_TAG(HDF_LOG_TAG, I) fmt, ## args) -/** - * @brief Prints logs at the warning level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGW(fmt, args...) printk(KERN_WARNING HDF_FMT_TAG(HDF_LOG_TAG, W) fmt, ## args) -/** - * @brief Prints logs at the error level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGE(fmt, args...) printk(KERN_ERR HDF_FMT_TAG(HDF_LOG_TAG, E) fmt, ## args) - -#elif defined(__LITEOS__) && defined(__USER__) -/** - * @brief Prints logs at the verbose level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGV(fmt, arg...) printf("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the debug level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGD(fmt, arg...) printf("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the information level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGI(fmt, arg...) printf("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the warning level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGW(fmt, arg...) printf("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the error level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGE(fmt, arg...) printf("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) -#elif defined(__LITEOS__) -/** - * @brief Prints logs at the verbose level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGV(fmt, arg...) PRINT_DEBUG("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the debug level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGD(fmt, arg...) PRINT_DEBUG("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the information level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGI(fmt, arg...) PRINT_INFO("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the warning level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGW(fmt, arg...) PRINT_WARN("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the error level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGE(fmt, arg...) PRINT_ERR("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) -#else -/** - * @brief Prints logs at the verbose level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGV(fmt, arg...) printf("[HDF:V/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the debug level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGD(fmt, arg...) printf("[HDF:D/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the information level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGI(fmt, arg...) printf("[HDF:I/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the warning level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGW(fmt, arg...) printf("[HDF:W/" LOG_TAG "]" fmt "\r\n", ##arg) -/** - * @brief Prints logs at the error level. - * - * To use this function, you must define HDF_LOG_TAG, for example, #define HDF_LOG_TAG evt. - * - * @since 1.0 - * @version 1.0 - */ -#define HDF_LOGE(fmt, arg...) printf("[HDF:E/" LOG_TAG "]" fmt "\r\n", ##arg) - -#endif /* __KERNEL__ */ +#define HDF_LOGE(fmt, args...) HDF_LOGE_WRAPPER(fmt, ##args) #ifdef __cplusplus } diff --git a/include/utils/hdf_workqueue.h b/include/utils/hdf_workqueue.h old mode 100755 new mode 100644 index 7d009666..0bc522a3 --- a/include/utils/hdf_workqueue.h +++ b/include/utils/hdf_workqueue.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** diff --git a/include/wifi/hdf_wifi_event.h b/include/wifi/hdf_wifi_event.h old mode 100755 new mode 100644 index a7535d75..a1c68fc8 --- a/include/wifi/hdf_wifi_event.h +++ b/include/wifi/hdf_wifi_event.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -59,7 +38,6 @@ #include "hdf_wifi_cmd.h" #include "wifi_mac80211_ops.h" #include "net_device.h" -#include #ifdef __cplusplus #if __cplusplus @@ -71,6 +49,7 @@ extern "C" { * @brief Defines the rate information received or sent over WLAN. * * @since 1.0 + * @version 1.0 */ struct RateInfo { uint8_t flags; /**< Flag field, used to indicate a specific rate transmission type of 802.11n */ @@ -84,6 +63,7 @@ struct RateInfo { * @brief Defines parameters related to the WLAN module that works in station mode. * * @since 1.0 + * @version 1.0 */ struct StaBssParameters { uint8_t flags; /**< Flag, used to indicate a specific rate transmission type of 802.11n */ @@ -95,6 +75,7 @@ struct StaBssParameters { * @brief Defines the update of the Sta flag. * * @since 1.0 + * @version 1.0 */ struct StaFlagUpdate { uint32_t mask; /**< Flag mask */ @@ -105,6 +86,7 @@ struct StaFlagUpdate { * @brief Defines station information. * * @since 1.0 + * @version 1.0 */ struct StationInfo { uint32_t filled; /**< Flag values of relevant structures */ @@ -145,6 +127,7 @@ struct StationInfo { * @brief Defines authentication information. * * @since 1.0 + * @version 1.0 */ struct Auth { uint16_t authAlg; /**< Authentication algorithm */ @@ -157,6 +140,7 @@ struct Auth { * @brief Defines deauthentication information. * * @since 1.0 + * @version 1.0 */ struct Deauth { uint16_t reasonCode; /**< Deauthentication cause code */ @@ -166,6 +150,7 @@ struct Deauth { * @brief Defines station association request. * * @since 1.0 + * @version 1.0 */ struct AssocReq { uint16_t capabInfo; /**< WLAN capability information */ @@ -177,6 +162,7 @@ struct AssocReq { * @brief Defines station association response. * * @since 1.0 + * @version 1.0 */ struct AssocResp { uint16_t capabInfo; /**< WLAN capability information */ @@ -189,6 +175,7 @@ struct AssocResp { * @brief Defines station reassociation request. * * @since 1.0 + * @version 1.0 */ struct ReassocReq { uint16_t capabInfo; /**< WLAN capability information */ @@ -201,6 +188,7 @@ struct ReassocReq { * @brief Defines station reassociation response. * * @since 1.0 + * @version 1.0 */ struct ReassocResp { uint16_t capabInfo; /**< WLAN capability information */ @@ -213,6 +201,7 @@ struct ReassocResp { * @brief Defines station disconnection. * * @since 1.0 + * @version 1.0 */ struct Disassoc { uint16_t reasonCode; /**< Cause code */ @@ -222,6 +211,7 @@ struct Disassoc { * @brief Defines the update of the Sta flag. * * @since 1.0 + * @version 1.0 */ struct Beacon { uint64_t timestamp; /**< Timestamp */ @@ -234,6 +224,7 @@ struct Beacon { * @brief Defines scanning response. * * @since 1.0 + * @version 1.0 */ struct ProbeResp { uint64_t timestamp; /**< Timestamp */ @@ -246,6 +237,7 @@ struct ProbeResp { * @brief Defines management frame information. * * @since 1.0 + * @version 1.0 */ struct Ieee80211Mgmt { uint16_t frameControl; /**< Frame control field */ @@ -271,6 +263,7 @@ struct Ieee80211Mgmt { * @brief Represents the scanned BSS information. * * @since 1.0 + * @version 1.0 */ struct ScannedBssInfo { int32_t signal; /**< Signal strength */ @@ -284,6 +277,7 @@ struct ScannedBssInfo { * @brief Defines association results. * * @since 1.0 + * @version 1.0 */ struct ConnetResult { uint8_t bssid[ETH_ADDR_LEN]; /**< MAC address of the AP associated with the station */ @@ -301,6 +295,7 @@ struct ConnetResult { * fails to be associated. * * @since 1.0 + * @version 1.0 */ enum WifiHmacMgmtStatus { WIFI_HMAC_MGMT_SUCCESS = 0, /**< Association succeeds */ @@ -314,7 +309,7 @@ enum WifiHmacMgmtStatus { /** * @brief Reports a new STA event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param macAddr Indicates the pointer to the MAC address of the station. This parameter cannot be null. * @param addrLen Indicates the length of the MAC address of the station. The length is fixed to six bytes. * @param info Indicates the pointer to the station information. @@ -322,81 +317,86 @@ enum WifiHmacMgmtStatus { * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventNewSta(const struct NetDevice *netdev, const uint8_t *macAddr, uint8_t addrLen, +int32_t HdfWifiEventNewSta(const struct NetDevice *netDev, const uint8_t *macAddr, uint8_t addrLen, const struct StationInfo *info); /** * @brief Reports a station deletion event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param macAddr Indicates the pointer to the MAC address of the station. This parameter cannot be null. * @param addrLen Indicates the length of the MAC address of the station. The length is fixed to six bytes. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventDelSta(struct NetDevice *netdev, const uint8_t *macAddr, uint8_t addrLen); +int32_t HdfWifiEventDelSta(struct NetDevice *netDev, const uint8_t *macAddr, uint8_t addrLen); /** * @brief Reports a scanned BSS event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. - * @param wiphy Indicates the pointer to the physical layer of the wireless network. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param channel Indicates the pointer to the channel information. This parameter cannot be null. * @param bssInfo Indicates the pointer to the BSS information. This parameter cannot be null. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventInformBssFrame(const struct NetDevice *netdev, struct Wiphy *wiphy, - const struct Ieee80211Channel *channel, const struct ScannedBssInfo *bssInfo); +int32_t HdfWifiEventInformBssFrame(const struct NetDevice *netDev, const struct WlanChannel *channel, + const struct ScannedBssInfo *bssInfo); /** * @brief Reports a scanning completion event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param status Indicates the scanning completion status. Value 0 indicates that the scanning is successful, * and other values indicate that the scanning fails. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventScanDone(const struct NetDevice *netdev, WifiScanStatus status); +int32_t HdfWifiEventScanDone(const struct NetDevice *netDev, WifiScanStatus status); /** * @brief Reports a connection result event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param result Indicates the pointer to the connection result. This parameter cannot be null. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventConnectResult(const struct NetDevice *netdev, const struct ConnetResult *result); +int32_t HdfWifiEventConnectResult(const struct NetDevice *netDev, const struct ConnetResult *result); /** * @brief Reports a disconnection event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param reason Indicates the reason for disconnection. * @param ie Indicates the pointer to the deauth/disassoc frame IE. - * @param ieLen Indicates the length of the deauth/disassoc IE. + * @param len Indicates the length of the deauth/disassoc IE. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventDisconnected(const struct NetDevice *netdev, uint16_t reason, const uint8_t *ie, uint32_t len); +int32_t HdfWifiEventDisconnected(const struct NetDevice *netDev, uint16_t reason, const uint8_t *ie, uint32_t len); /** * @brief Reports a transmission management status event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param buf Indicates the pointer to the transmission management frame. This parameter cannot be null. * @param len Indicates the length of the transmission management frame. * @param ack Indicates whether the transmission management frame is acknowledged. @@ -404,13 +404,14 @@ int32_t HdfWifiEventDisconnected(const struct NetDevice *netdev, uint16_t reason * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventMgmtTxStatus(const struct NetDevice *netdev, const uint8_t *buf, size_t len, uint8_t ack); +int32_t HdfWifiEventMgmtTxStatus(const struct NetDevice *netDev, const uint8_t *buf, size_t len, uint8_t ack); /** * @brief Reports a receive management status event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param freq Indicates the frequency of receiving management frame. * @param sigMbm Indicates the signal strength (in dBm). * @param buf Indicates the pointer to the receive management frame. This parameter cannot be null. @@ -419,31 +420,35 @@ int32_t HdfWifiEventMgmtTxStatus(const struct NetDevice *netdev, const uint8_t * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventRxMgmt(const struct NetDevice *netdev, int32_t freq, int32_t sigMbm, +int32_t HdfWifiEventRxMgmt(const struct NetDevice *netDev, int32_t freq, int32_t sigMbm, const uint8_t *buf, size_t len); /** * @brief Reports a CSA channel switching event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * @param freq Indicates the frequency of the channel. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ -int32_t HdfWifiEventCsaChannelSwitch(const struct NetDevice *netdev, int32_t freq); +int32_t HdfWifiEventCsaChannelSwitch(const struct NetDevice *netDev, int32_t freq); /** * @brief Reports a timeout disconnection event. * - * @param netdev Indicates the pointer to the network device. This parameter cannot be null. + * @param netDev Indicates the pointer to the network device. This parameter cannot be null. * * @return Returns 0 if the event is reported successfully; returns -1 otherwise. * - * @since 1.0 */ -int32_t HdfWifiEventTimeoutDisconnected(const struct NetDevice *netdev); + * @since 1.0 + * @version 1.0 + */ +int32_t HdfWifiEventTimeoutDisconnected(const struct NetDevice *netDev); /** * @brief Reports the event of receiving the EAPOL frame and notifies WPA to read the EAPOL frame. @@ -454,14 +459,28 @@ int32_t HdfWifiEventTimeoutDisconnected(const struct NetDevice *netdev); * @return Returns 0 if the operation is successful; returns -1 otherwise. * * @since 1.0 + * @version 1.0 */ int32_t HdfWifiEventEapolRecv(const char *name, void *context); +/** + * @brief Reports the WLAN driver reset result. + * + * @param chipId Indicates the chip ID. This parameter cannot be null. + * @param resetStatus Indicates the WLAN driver reset result. + * + * @return Returns 0 if the result is reported successfully; returns -1 otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t HdfWifiEventResetResult(const uint8_t chipId, int32_t resetStatus); + #ifdef __cplusplus #if __cplusplus - } +} #endif #endif #endif /* __HDF_WIFI_EVENT_H__ */ - +/** @} */ diff --git a/include/wifi/hdf_wifi_product.h b/include/wifi/hdf_wifi_product.h old mode 100755 new mode 100644 index ad3d0a4f..1007523c --- a/include/wifi/hdf_wifi_product.h +++ b/include/wifi/hdf_wifi_product.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -53,36 +32,121 @@ #ifndef HDFLITE_HDF_WIFI_PRODUCT_H #define HDFLITE_HDF_WIFI_PRODUCT_H -#include "wifi_module.h" #include "hdf_device_desc.h" +#include "hdf_wlan_config.h" +#include "hdf_wlan_power_manager.h" +#include "hdf_wlan_reset_manager.h" #ifdef __cplusplus extern "C" { #endif /** - * @brief Defines the WLAN module. - * - * @since 1.0 - */ -struct HdfWifiProductData { - char product_name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< WLAN module name, which contains a maximum of 10 bytes */ - char state; /**< WLAN module state */ - struct WifiModule *module; /**< Structure of the WLAN module */ - struct HdfDeviceObject *device; /**< Structure of the Device Object */ -}; - -/** - * @brief Obtains the data structure of the WLAN module. - * - * @return Returns the pointer to the data structure of the WLAN module. For details, see {@link HdfWifiProductData}. + * @brief Defines the WLAN chip manufacturer. * * @since 1.0 * @version 1.0 */ -struct HdfWifiProductData *HdfWifiGetProduct(void); +struct HdfWlanManufacturer { + int32_t vendorId; /**< Vendor ID of the chip */ + int32_t deviceId; /**< Device ID of the chip */ +}; + +/** + * @brief Indicates the maximum number of interfaces. + * + * The value is 32. + * @since 1.0 + * @version 1.0 + */ +#define MAX_IF_COUNT 32 + +/** + * @brief Defines the WLAN device. + * + * @since 1.0 + */ +struct HdfWlanDevice { + uint8_t id; + const char *driverName; /**< Driver name */ + const char *chipName; /**< Chip name */ + uint32_t netIfMap; /**< WLAN device bitmap */ + struct HdfWlanManufacturer manufacturer; /**< WLAN device manufacturer */ + struct ResetManager *reset; /**< Chip reset management API */ + struct PowerManager *powers; /**< Chip power management APIs */ +}; + +/** + * @brief Initializes the WLAN module. + * + * @param device Indicates the pointer to the Hardware Driver Foundation (HDF) device. + * @param config Indicates the pointer to the WLAN module configuration generated by + * the HDF Configuration Source (HCS). + * + * @return Returns 0 if the WLAN module is initialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int HdfWlanInitProduct(struct HdfDeviceObject *device, const struct HdfConfigWlanModuleConfig *config); + +/** + * @brief Obtains the data structure of the WLAN module. + * + * @return Returns the data structure if obtained; returns NULL otherwise. + * + * @since 1.0 + * @version 1.0 + */ +struct WifiModule* HdfWlanGetModule(void); + +/** + * @brief Obtains the HdfWlanDevice structure. + * + * @param chipId Indicates the chip ID. + * + * @return Returns the pointer to the HdfWlanDevice structure if obtained; returns NULL otherwise. + * + * @since 1.1 + * @version 1.0 + */ +struct HdfWlanDevice *HdfWlanGetWlanDevice(uint8_t chipId); + +/** + * @brief Send broadcast event. + * + * @param id Indicates the ID of the event to send. + * @param data Indicates the pointer to the event information. + * + * @return Returns 0 if the broadcast event is sent; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int HdfWlanSendBroadcastEvent(uint32_t id, const struct HdfSBuf *data); + +/** + * @brief Adds a WLAN device. + * + * @param device Indicates the pointer to the device to add. + * + * @return Returns 0 if the WLAN device is added; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int HdfWlanAddDevice(struct HdfWlanDevice *device); + +/** + * @brief Deinitializes the WLAN module. + * + * @since 1.0 + * @version 1.0 + */ +void HdfWlanDeinitProduct(void); #ifdef __cplusplus } #endif #endif // HDFLITE_HDF_WIFI_PRODUCT_H +/** @} */ diff --git a/include/wifi/hdf_wlan_chipdriver_manager.h b/include/wifi/hdf_wlan_chipdriver_manager.h new file mode 100644 index 00000000..d4277387 --- /dev/null +++ b/include/wifi/hdf_wlan_chipdriver_manager.h @@ -0,0 +1,197 @@ +/* + * 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. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_wlan_chipdriver_manager.h + * + * @brief Declares data structures and functions of the WLAN chip driver manager. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_WLAN_CHIPDRIVER_MANGER_H +#define HDF_WLAN_CHIPDRIVER_MANGER_H +#include "hdf_wifi_product.h" +#include "hdf_wlan_power_manager.h" +#include "hdf_wlan_reset_manager.h" +#include "wifi_module.h" + +/** + * @brief Indicates the maximum number of chip drivers. + * + * @since 1.0 + * @version 1.0 + */ +#define MAX_CHIPDRIVER_COUNT 16 + +/** + * @brief Indicates the maximum number of WLAN chip driver managers. + * + * @since 1.0 + * @version 1.0 + */ +#define HDF_WLAN_MAX_MANAGER_COUNT 8 + +/** + * @brief Describes WLAN device data. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfWifiNetDeviceData { + uint8_t netInterfaceId; /**< Network interface ID */ + struct HdfChipDriver *chipDriver; /**< Chip driver */ + struct HdfWlanDevice *device; /**< WLAN device */ +}; + +/** + * @brief Describes the HdfChipDriverFactory instance and provides functions such as initializing and + * deinitializing a chip, and obtaining the maximum number of interfaces. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfChipDriverFactory { + const char *driverName; /**< Driver name */ + + /** + * @brief Initializes a specified chip. + * + * @param device Indicates the pointer to the WLAN device where the chip resides. + * @return Returns 0 if the chip is initialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*InitChip)(struct HdfWlanDevice *device); + + /** + * @brief Deinitializes a specified chip. + * + * @param device Indicates the pointer to the WLAN device where the chip resides. + * @return Returns 0 if the chip is deinitialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*DeinitChip)(struct HdfWlanDevice *device); + + /** + * @brief Releases a specified HdfChipDriverFactory instance. + * + * @param factory Indicates the pointer to the HdfChipDriverFactory instance. + * + * @since 1.0 + * @version 1.0 + */ + void (*ReleaseFactory)(struct HdfChipDriverFactory *factory); + + /** + * @brief Creates a HdfChipDriver instance with the initialization and deinitialization functions. + * + * @param device Indicates the pointer to the WLAN device. + * @param ifIndex Indicates the interface index. + * @return Returns the pointer to the HdfChipDriver instance. + * + * @since 1.0 + * @version 1.0 + */ + struct HdfChipDriver *(*Build)(struct HdfWlanDevice *device, uint8_t ifIndex); + + /** + * @brief Releases a specified HdfChipDriver instance. + * + * @param chipDriver Indicates the pointer to the HdfChipDriver instance. + * + * @since 1.0 + * @version 1.0 + */ + void (*Release)(struct HdfChipDriver *chipDriver); + + /** + * @brief Obtains the maximum number of interfaces of a specified HdfChipDriverFactory instance. + * + * @param factory Indicates the pointer to the HdfChipDriverFactory instance. + * @return Returns 0 if the maximum number of interfaces is obtained; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + uint8_t (*GetMaxIFCount)(struct HdfChipDriverFactory *factory); +}; + +/** + * @brief Manages chip drivers. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfChipDriverManager { + struct HdfChipDriverFactory **chipFactoryInsts; /**< HdfChipDriverFactory instances */ + + /** + * @brief Registers a chip driver. + * + * @param factoryInst Indicates the pointer to the HdfChipDriverFactory instance. + * @return Returns 0 if the chip driver is registered; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*RegChipDriver)(struct HdfChipDriverFactory *factoryInst); + + /** + * @brief Obtains the chip driver based on the network device name. + * + * @param name Indicates the pointer to the network device name. + * @return Returns the pointer to the HdfChipDriverFactory instance. + * + * @since 1.0 + * @version 1.0 + */ + struct HdfChipDriverFactory *(*GetChipDriverByName)(const char *name); +}; + +/** + * @brief Obtains an HdfChipDriverManager instance. + * + * @return Returns the pointer to the HdfChipDriverManager instance. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfChipDriverManager *HdfWlanGetChipDriverMgr(void); + +/** + * @brief Deinitializes an HdfChipDriverManager instance. + * + * @return Returns 0 if the HdfChipDriverManager instance is deinitialized; returns a + * negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t ChipDriverMgrDeInit(void); + +#endif +/** @} */ diff --git a/include/wifi/hdf_wlan_power_manager.h b/include/wifi/hdf_wlan_power_manager.h new file mode 100644 index 00000000..5706eb99 --- /dev/null +++ b/include/wifi/hdf_wlan_power_manager.h @@ -0,0 +1,88 @@ +/* + * 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. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_wlan_power_manager.h + * + * @brief Declares data structures and functions of the WLAN power manager. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_WLAN_POWER_MANAGE_H +#define HDF_WLAN_POWER_MANAGE_H + +/** + * @brief Provides functions for powering on and off the device, releasing power, and creating a power manager. + * + * @since 1.0 + * @version 1.0 + */ +struct PowerManager { + /** + * @brief Powers on the device using a specified power manager. + * + * @param powerMgr Indicates the pointer to the power manager. + * @return Returns 0 if the device is powered on; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*On)(struct PowerManager *powerMgr); + + /** + * @brief Powers off the device using a specified power manager. + * + * @param powerMgr Indicates the pointer to the power manager. + * @return Returns 0 if the device is powered off; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Off)(struct PowerManager *powerMgr); + + /** + * @brief Releases power using a specified power manager. + * + * @param powerMgr Indicates the pointer to the power manager. + * @return Returns 0 if power is released; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Release)(struct PowerManager *powerMgr); +}; + +/** + * @brief Creates a WLAN power manager. + * + * @param configPowers Indicates the pointer to the power configuration. + * @return Returns a pointer to the created power manager. + * + * @since 1.0 + * @version 1.0 + */ +struct PowerManager *HdfWlanCreatePowerManager(const struct HdfConfWlanPowers *configPowers); + +#endif +/** @} */ diff --git a/include/wifi/hdf_wlan_reset_manager.h b/include/wifi/hdf_wlan_reset_manager.h new file mode 100644 index 00000000..509dd17c --- /dev/null +++ b/include/wifi/hdf_wlan_reset_manager.h @@ -0,0 +1,78 @@ +/* + * 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. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file hdf_wlan_reset_manager.h + * + * @brief Declares data structures and functions of the WLAN reset manager. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDF_WLAN_RESET_MANAGE_H +#define HDF_WLAN_RESET_MANAGE_H + +/** + * @brief Describes the reset manager, including its configuration and functions. + * + * @since 1.0 + * @version 1.0 + */ +struct ResetManager { + /** + * @brief Resets the WLAN module using a specified reset manager. + * + * @param resetManager Indicates the pointer to the reset manager. + * @return Returns 0 if the WLAN module is reset; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Reset)(struct ResetManager *resetManager); + + /** + * @brief Releases a specified reset manager. + * + * @param resetMgr Indicates the pointer to the reset manager. + * @return Returns 0 if the reset manager is released; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Release)(struct ResetManager *resetMgr); +}; + +/** + * @brief Creates a WLAN reset manager. + * + * @param resetConfig Indicates the pointer to the reset configuration. + * @param holdTime Indicates the time for the reset configuration to take effect. + * @return Returns a pointer to the created reset manager. + * + * @since 1.0 + * @version 1.0 + */ +struct ResetManager *HdfWlanCreateResetManager(const struct HdfConfWlanRest *resetConfig, uint8_t holdTime); + +#endif +/** @} */ diff --git a/include/wifi/net_device.h b/include/wifi/net_device.h old mode 100755 new mode 100644 index 7165154a..d13adb0f --- a/include/wifi/net_device.h +++ b/include/wifi/net_device.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -58,124 +37,219 @@ #ifndef HDF_NET_DEVICE_MODULE_H #define HDF_NET_DEVICE_MODULE_H -#include -#include +#include "hdf_base.h" #include "hdf_netbuf.h" #include "hdf_log.h" +#include "net_device_types_adapter.h" #ifdef __cplusplus extern "C" { #endif -#ifndef IFNAMSIZ -#define IFNAMSIZ 16 -#endif - /** * @brief Indicates a 6-byte MAC address. + * + * @since 1.0 + * @version 1.0 */ #define MAC_ADDR_SIZE 6 /** * @brief Indicates that the network port is working. + * + * @since 1.0 + * @version 1.0 */ #define NET_DEVICE_IFF_RUNNING IFF_RUNNING /** * @brief Indicates Reverse Address Resolution Protocol (RARP). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_RARP 0x8035 /** * @brief Indicates Port Access Entity (PAE). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_PAE 0x888e /** * @brief Indicates Internet Protocol (IP). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_IP 0x0800 /** * @brief Indicates AppleTalk Address Resolution Protocol (AARP). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_AARP 0x80f3 /** * @brief Indicates Internetwork Packet Exchange (IPX). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_IPX 0x8137 /** * @brief Indicates Address Resolution Protocol (ARP). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_ARP 0x0806 /** * @brief Indicates Internet Protocol version 6 (IPv6). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_IPV6 0x86dd /** * @brief Indicates Tunneled Direct Link Setup (TDLS). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_TDLS 0x890d /** * @brief Indicates Virtual Local Area Network (VLAN). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_VLAN 0x8100 /** * @brief Indicates WLAN Authentication and Privacy Infrastructure (WAPI). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_WAI 0x88b4 /** * @brief Indicates Link Layer Topology Discovery (LLTD). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_LLTD_TYPE 0x88D9 /** * @brief Indicates 802.1x network port authentication. + * + * @since 1.0 + * @version 1.0 */ #define ETHER_ONE_X_TYPE 0x888E /** * @brief Indicates a tunnel protocol. + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TUNNEL_TYPE 0x88bd /** * @brief Indicates the point-to-point discovery type. + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_PPP_DISC 0x8863 /** * @brief Indicates the point-to-point session discovery type. + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_PPP_SES 0x8864 /** * @brief Indicates IPv6 over Low Power Wireless Personal Area Networks (6LoWPANs). + * + * @since 1.0 + * @version 1.0 */ #define ETHER_TYPE_6LO 0xa0ed /** * @brief Indicates the Transmission Control Protocol (TCP). + * + * @since 1.0 + * @version 1.0 */ -#define TCP_PROTOCAL 6 +#define TCP_PROTOCOL 6 /** * @brief Indicates the User Datagram Protocol (UDP). + * + * @since 1.0 + * @version 1.0 */ -#define UDP_PROTOCAL 17 +#define UDP_PROTOCOL 17 /** * @brief Indicates the shift in the priority for an IP address. + * + * @since 1.0 + * @version 1.0 */ #define IP_PRI_SHIFT 5 /** * @brief Indicates the source port number of DHCP. + * + * @since 1.0 + * @version 1.0 */ #define DHCP_UDP_SRC_PORT 68 /** * @brief Indicates the destination port number of DHCP. + * + * @since 1.0 + * @version 1.0 */ #define DHCP_UDP_DES_PORT 67 /** - * @brief Enumerates network interface categories, including lightweight OS and rich OS. + * @brief Indicates the default MTU value of the WLAN. + * + * @since 1.0 + * @version 1.0 + */ +#define DEFAULT_MTU 1500 + +/** + * @brief Indicates the maximum MTU value of the WLAN. + * + * @since 1.0 + * @version 1.0 + */ +#define WLAN_MAX_MTU 1500 + +/** + * @brief Indicates the minimum MTU value of the WLAN. + * + * @since 1.0 + * @version 1.0 + */ +#define WLAN_MIN_MTU 576 + +/** + * @brief Enumerates network interface categories, including lightweight OS and full OS. + * + * @since 1.0 + * @version 1.0 */ typedef enum { LITE_OS, /**< Lightweight OS */ - RICH_OS /**< Rich OS */ + FULL_OS /**< Full OS */ } NetIfCategory; /** * @brief Enumerates network interface states, including online and offline. + * + * @since 1.0 + * @version 1.0 */ typedef enum { NETIF_DOWN, /**< Network interface offline */ @@ -184,6 +258,9 @@ typedef enum { /** * @brief Enumerates network link layer states, including online and offline. + * + * @since 1.0 + * @version 1.0 */ typedef enum { NETIF_LINK_DOWN, /**< Data link offline */ @@ -192,6 +269,9 @@ typedef enum { /** * @brief Enumerates data link types, including Ethernet and WLAN. + * + * @since 1.0 + * @version 1.0 */ typedef enum { ETHERNET_LINK = 1, /**< Ethernet */ @@ -200,6 +280,9 @@ typedef enum { /** * @brief Enumerates data processing results, including continuing processing, processing completed, and error. + * + * @since 1.0 + * @version 1.0 */ typedef enum { PROCESSING_CONTINUE, /**< Continuing processing */ @@ -207,18 +290,11 @@ typedef enum { PROCESSING_ERROR /**< Error */ } ProcessingResult; -/** - * @brief Enumerates data sending results, including sending succeeded, other data being sent at the link layer, - * and data link layer being locked. - */ -typedef enum { - NETDEV_TX_OK = 0x00, /**< Sending succeeded */ - NETDEV_TX_BUSY = 0x10, /**< Other data being sent at the link layer */ - NETDEV_TX_LOCKED = 0x20, /**< Data link layer being locked */ -} NetDevTxResult; - /** * @brief Enumerates 802.11 network port types, including AP, STA, and P2P. + * + * @since 1.0 + * @version 1.0 */ typedef enum { PROTOCOL_80211_IFTYPE_UNSPECIFIED, /**< Unspecified */ @@ -238,6 +314,9 @@ typedef enum { /** * @brief Enumerates network device errors, including common errors and errors in adding network devices to LwIP. + * + * @since 1.0 + * @version 1.0 */ typedef enum { COMMON_ERROR = 1, /**< Common errors */ @@ -249,6 +328,7 @@ typedef enum { * and Ethernet type. * * @since 1.0 + * @version 1.0 */ struct EtherHeader { uint8_t etherDhost[MAC_ADDR_SIZE]; /**< Destination address {@link MAC_ADDR_SIZE} */ @@ -263,6 +343,7 @@ struct EtherHeader { * and total length. * * @since 1.0 + * @version 1.0 */ struct IpHeader { uint8_t versionAndHl; /**< Version and header length */ @@ -286,6 +367,7 @@ struct IpHeader { * port number. * * @since 1.0 + * @version 1.0 */ struct UdpHeader { uint16_t source; /**< Source port number */ @@ -298,7 +380,9 @@ struct UdpHeader { * @brief Defines the TCP header information of a data frame, including the source port number and destination * port number. * - * @since 1.0 */ + * @since 1.0 + * @version 1.0 + */ struct TcpHeader { uint16_t sPort; /**< Source port number */ uint16_t dPort; /**< Destination port number */ @@ -315,6 +399,7 @@ struct TcpHeader { * @brief Defines an IPv4 address. * * @since 1.0 + * @version 1.0 */ typedef struct { uint32_t addr; /**< IPv4 address */ @@ -324,6 +409,7 @@ typedef struct { * @brief Defines a network device notification, including an IP address and the notification type. * * @since 1.0 + * @version 1.0 */ typedef struct { uint32_t ipAddr; /**< IP address */ @@ -334,11 +420,18 @@ typedef struct { * @brief Defines the network port type, for example, the WLAN network port. * * @since 1.0 + * @version 1.0 */ typedef union { Protocol80211IfType wlanType; /**< WLAN network port type: AP or STA */ } IfType; +/** + * @brief Describes the status of a network device. + * + * @since 1.0 + * @version 1.0 + */ struct NetDevStats { uint32_t rxPackets; /**< Total number of received packets */ uint32_t txPackets; /**< Total number of transmitted packets */ @@ -347,13 +440,14 @@ struct NetDevStats { uint32_t rxErrors; /**< Number of received error packets */ uint32_t txErrors; /**< Transmitted error packets */ uint32_t rxDropped; /**< Packets that are dropped after being received */ - uint32_t txDropped; /**< Packets dropped before transmission*/ + uint32_t txDropped; /**< Packets dropped before transmission */ }; /** * @brief Defines ioctrl data. * * @since 1.0 + * @version 1.0 */ typedef struct { uint32_t fake; /**< magic field */ @@ -364,6 +458,7 @@ typedef struct { * @brief Defines a network device, including the network interface category and name, and network port type. * * @since 1.0 + * @version 1.0 */ typedef struct NetDevice { NetIfCategory netifCateg; /**< Network interface category {@link NetIfCategory} */ @@ -379,11 +474,13 @@ typedef struct NetDevice { uint16_t neededHeadRoom; /**< Length reserved for the header in netbuff{@link NetBuf} */ uint16_t neededTailRoom; /**< Length reserved for the tail in netbuff{@link NetBuf} */ uint8_t addrLen; /**< MAC address length */ + const char* classDriverName; /**< driver name of class driver */ + void *classDriverPriv; /**< Private structure for the platform */ void *mlPriv; /**< Private structure for the driver */ - struct WirelessDev *ieee80211Ptr; /**< Pointer to a wireless device */ + void *ieee80211Ptr; /**< Pointer to a wireless device */ void *specialProcPriv; /**< Private structure for data processing */ struct NetDeviceInterFace *netDeviceIf; /**< Network device interface */ - struct NetDevice *owner; /**< Network device */ + struct NetDevice *owner; /**< Network device */ struct NetDevStats stats; /**< Network statistics */ } NetDevice; @@ -392,23 +489,24 @@ typedef struct NetDevice { * opening, and closing a network device. * * @since 1.0 + * @version 1.0 */ struct NetDeviceInterFace { int32_t (*init)(struct NetDevice *netDev); /**< Initializes a network device to be added. */ void (*deInit)(struct NetDevice *netDev); /**< Deinitializes a network device to be delete. */ int32_t (*open)(struct NetDevice *netDev); /**< Opens the data link layer. */ int32_t (*stop)(struct NetDevice *netDev); /**< Closes the data link layer. */ - NetDevTxResult (*xmit)(struct NetDevice *netDev, struct NetBuf *netBuff); /**< Sends data. */ + 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, struct 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. */ - ProcessingResult (*specialEtherTypeProcess)(const struct NetDevice *netDev, struct NetBuf *buff); + ProcessingResult (*specialEtherTypeProcess)(const struct NetDevice *netDev, NetBuf *buff); /**< Performs private processing without * involving network-layer data. */ @@ -446,7 +544,7 @@ int32_t NetDeviceDeInit(struct NetDevice *netDevice); * @brief Adds a network device to a protocol stack. * * @param netDevice Indicates the pointer to the network device structure obtained during initialization. - * @param netDevice Indicates the network port type, as enumerated in {@link Protocol80211IfType}. + * @param ifType Indicates the network port type, as enumerated in {@link Protocol80211IfType}. * * @return Returns 0 if the operation is successful; returns a negative value representing {@link HDF_STATUS} * if the operation fails. @@ -561,6 +659,7 @@ int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, * * @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}. * * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. * @@ -569,6 +668,20 @@ int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, */ int32_t NetIfSetStatus(const struct NetDevice *netDevice, NetIfStatus status); +/** + * @brief Sets a specified MAC address for a given {@link NetDevice}. + * + * @param netDevice Indicates the pointer to the {@link NetDevice}. + * @param macAddr Indicates the pointer to the MAC address to set. + * @param length Indicates the length of the MAC address to set. + * + * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t NetIfSetMacAddr(struct NetDevice *netDevice, const unsigned char *macAddr, unsigned char length); + /** * @brief Notifies the network layer of the data link layer status. * @@ -585,6 +698,8 @@ int32_t NetIfSetLinkStatus(const struct NetDevice *netDevice, NetIfLinkStatus st /** * @brief Transfers the input data packets from the network side to a protocol stack. * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained + * during initialization. * @param buff Indicates the network-side data, in Ether format. * * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. @@ -592,11 +707,13 @@ int32_t NetIfSetLinkStatus(const struct NetDevice *netDevice, NetIfLinkStatus st * @since 1.0 * @version 1.0 */ -int32_t NetIfRx(const struct NetDevice *netDevice, struct NetBuf *buff); +int32_t NetIfRx(const struct NetDevice *netDevice, NetBuf *buff); /** * @brief Transfers data packets from the network side to a protocol stack in an interrupt processing thread. * + * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained + * during initialization. * @param buff Indicates the network-side data, in Ether format. * * @return Returns 0 if the operation is successful; returns a non-zero value {@link HDF_STATUS} if the @@ -605,14 +722,14 @@ int32_t NetIfRx(const struct NetDevice *netDevice, struct NetBuf *buff); * @since 1.0 * @version 1.0 */ -int32_t NetIfRxNi(const struct NetDevice *netDevice, struct NetBuf *buff); +int32_t NetIfRxNi(const struct NetDevice *netDevice, NetBuf *buff); /** * @brief Starts the DHCP server. * * @param netDevice Indicates the pointer to the network device structure {@link netDevice} obtained * during initialization. - * @param beginIp Indicates the IP address to start. + * @param ip Indicates the IP address to start. * @param ipNum Indicates the number of IP addresses. * * @return Returns 0 if the operation is successful; returns a non-zero value otherwise. @@ -620,7 +737,7 @@ int32_t NetIfRxNi(const struct NetDevice *netDevice, struct NetBuf *buff); * @since 1.0 * @version 1.0 */ -int32_t NetIfDhcpsStart(const struct NetDevice *netDevice, char *ip, u16_t ipNum); +int32_t NetIfDhcpsStart(const struct NetDevice *netDevice, char *ip, uint16_t ipNum); /** * @brief Stops the DHCP server. @@ -675,7 +792,7 @@ int32_t NetIfDhcpIsBound(const struct NetDevice *netDevice); #define GET_NET_DEV_HEAD_ROOM(dev) ((dev)->neededHeadRoom) #define GET_NET_DEV_TAIL_ROOM(dev) ((dev)->neededTailRoom) #define GET_NET_DEV_MTU(dev) ((dev)->mtu) -#define GET_NET_DEV_WIRELESS(dev) ((dev)->ieee80211Ptr) +#define GET_NET_DEV_CFG80211_WIRELESS(dev) ((struct wireless_dev*)((dev)->ieee80211Ptr)) #define GET_NET_DEV_PRIV(dev) ((dev)->mlPriv) #define GET_NET_DEV_MAC_ADDR(dev) ((dev)->macAddr) #define GET_NET_DEV_IF(dev) ((dev)->netDeviceIf) @@ -688,3 +805,4 @@ int32_t NetIfDhcpIsBound(const struct NetDevice *netDevice); #endif #endif /* HDF_NET_DEVICE_MODULE_H */ +/** @} */ diff --git a/include/wifi/wifi_inc.h b/include/wifi/wifi_inc.h old mode 100755 new mode 100644 index d4288880..f1ec5336 --- a/include/wifi/wifi_inc.h +++ b/include/wifi/wifi_inc.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -60,7 +39,7 @@ extern "C" { struct WifiModule; struct WifiFeature; struct WifiFeatureList; -struct HdfWifiChipData; +struct HdfChipDriver; struct BusDev; /** @@ -70,6 +49,7 @@ struct BusDev; * and cannot be identified. * * @since 1.0 + * @version 1.0 */ #define MAX_WIFI_COMPONENT_NAME_LEN 10 @@ -79,9 +59,9 @@ struct BusDev; * You can query and register a feature or bind a feature to a WLAN module based on the feature type. * * @since 1.0 + * @version 1.0 */ enum WifiMainFeatureType { - HDF_WIFI_FEATURE_BASE, /**< Base feature */ HDF_WIFI_FEATURE_AP, /**< AP */ HDF_WIFI_FEATURE_STA, /**< Station */ HDF_WIFI_FEATURE_P2P, /**< Peer-to-peer (P2P) */ @@ -94,6 +74,7 @@ enum WifiMainFeatureType { * @brief Enumerates bus types of a WLAN module. * * @since 1.0 + * @version 1.0 */ enum WifiBusType { BUS_SDIO, /**< Secure Digital Input and Output (SDIO) */ @@ -105,4 +86,4 @@ enum WifiBusType { #endif #endif // HDFLITE_WIFI_MODULE_INC_H - +/** @} */ diff --git a/include/wifi/wifi_mac80211_ops.h b/include/wifi/wifi_mac80211_ops.h old mode 100755 new mode 100644 index 14873fd7..eb498f91 --- a/include/wifi/wifi_mac80211_ops.h +++ b/include/wifi/wifi_mac80211_ops.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -59,423 +38,734 @@ #include "net_device.h" #include "hdf_wifi_cmd.h" -#define WLAN_MAC_ADDR_LEN 6 /** - * @brief Enumerates setting types of MAC addresses. + * @brief Indicates the length of the MAC address of the device. + * + * The value is 6. * * @since 1.0 + * @version 1.0 */ -enum MacSetType { - MAC_BEACON_SET = 0, /**< Setting a beacon MAC address */ - MAC_BEACON_ADD = 1, /**< Adding a beacon MAC address */ +#define IEEE80211_MAC_ADDR_LEN 6 +/** + * @brief Indicates the maximum length of the SSID of the device. + * + * The value is 32. + * + * @since 1.0 + * @version 1.0 + */ +#define IEEE80211_MAX_SSID_LEN 32 +/** + * @brief Indicates the length of a reserved field for the WLAN connection parameters. + * + * The value is 3. + * + * @since 1.0 + * @version 1.0 + */ +#define WIFI_CONNECT_PARM_RESV_SIZE 3 +/** + * @brief Indicates that the frequency is not specified. + * + * The value is 0. + * + * @since 1.0 + * @version 1.0 + */ +#define WLAN_FREQ_NOT_SPECFIED 0 +/** + * @brief Indicates the maximum length of the hotspot SSID array. + * + * The value is 32. + * + * @since 1.0 + * @version 1.0 + */ +#define OAL_IEEE80211_MAX_SSID_LEN 32 +/** + * @brief Indicates the maximum number of channels to scan for. + * + * The value is 14. + * + * @since 1.0 + * @version 1.0 + */ +#define MAX_SCAN_CHANNELS 14 +/** + * @brief Indicates a reserved field for a scan request. + * + * The value is 2. + * + * @since 1.0 + * @version 1.0 + */ +#define SCAN_REQUEST_RESV_SIZE 2 +/** + * @brief Indicates the maximum number of frequency filters. + * + * The value is 200. + * + * @since 1.0 + * @version 1.0 + */ +#define MAX_FREQ_FTILTER_COUNT 200 +/** + * @brief Indicates the maximum number of cipher suites. + * + * The value is 5. + * + * @since 1.0 + * @version 1.0 + */ +#define NL80211_MAX_NR_CIPHER_SUITES 5 +/** + * @brief Indicates the maximum number of AKM suites. + * + * The value is 2. + * + * @since 1.0 + * @version 1.0 + */ +#define NL80211_MAX_NR_AKM_SUITES 2 + +/** + * @brief Enumerates frequency bands. + * + * @since 1.0 + * @version 1.0 + */ +enum Ieee80211Band { + IEEE80211_BAND_2GHZ = 0, /**< 2.4 GHz */ + IEEE80211_BAND_5GHZ, /**< 5 GHz */ + IEEE80211_NUM_BANDS /**< Number of frequency bands */ +}; + +/** + * @brief Enumerates channel widths. + * + * @since 1.0 + * @version 1.0 + */ +enum Ieee80211ChannelWidth { + WLAN_CHANNEL_WIDTH_10 = BIT(0), /**< 10 MHz */ + WLAN_CHANNEL_WIDTH_20 = BIT(1), /**< 20 MHz */ + WLAN_CHANNEL_WIDTH_40P = BIT(2), /**< 40 MHz (two 20 MHz channels, with the primary channel + * having a higher frequency + */ + WLAN_CHANNEL_WIDTH_40M = BIT(3), /**< 40 MHz (two 20 MHz channels, with the primary channel + * having a lower frequency + */ + WLAN_CHANNEL_WIDTH_80 = BIT(4), /**< 80 MHz */ + WLAN_CHANNEL_WIDTH_160 = BIT(5), /**< 160 MHz */ +}; + +/** + * @brief Enumerates WLAN modes. + * + * @since 1.0 + * @version 1.0 + */ +enum WlanWorkMode { + WLAN_WORKMODE_STA = 2, /**< STA mode */ + WLAN_WORKMODE_AP = 3 /**< AP mode */ }; /** * @brief Describes a key. * * @since 1.0 + * @version 1.0 */ struct KeyParams { - uint8_t *key; /**< Key content */ - uint8_t *seq; /**< Content of a Temporal Key Integrity Protocol (TKIP) or Counter Mode Cipher Block Chaining - * Message Authentication Code Protocol (CCMP) key - */ - int32_t keyLen; /**< Key length */ - int32_t seqLen; /**< Length of a TKIP or CCMP key */ - uint32_t cipher; /**< Cipher suite */ + uint8_t *key; /**< Key content */ + uint8_t *seq; /**< Content of a Temporal Key Integrity Protocol (TKIP) or Counter Mode Cipher Block Chaining + * Message Authentication Code Protocol (CCMP) key + */ + int32_t keyLen; /**< Key length */ + int32_t seqLen; /**< Length of a TKIP or CCMP key */ + uint32_t cipher; /**< Cipher suite */ }; +#define UINT32_BIT(BIT) ((uint32_t)1) << BIT + +#define WLAN_CHANNEL_FLAG_DFS_UNKNOWN 0x00000000 +#define WLAN_CHANNEL_FLAG_DFS_MASK 0x00000300 + /** - * @brief Enumerates frequency bands. + * @brief Enumerates WLAN channel capability flags. * * @since 1.0 + * @version 1.0 */ -enum Ieee80211Band { - IEEE80211_BAND_2GHZ, /**< 2.4 GHz */ - IEEE80211_BAND_5GHZ, /**< 5 GHz */ - IEEE80211_NUM_BANDS /**< Reserved */ +enum WlanChannelCapabilityFlags { + WLAN_CHANNEL_FLAG_DISABLED = UINT32_BIT(0), /**< Channel disabled */ + WLAN_CHANNEL_FLAG_NO_IR = UINT32_BIT(1), /**< Infrared light (IR) not supported */ + WLAN_CHANNEL_FLAG_RADAR = UINT32_BIT(3), /**< Radar supported */ + WLAN_CHANNEL_FLAG_HT40PLUS = UINT32_BIT(4), /**< A 40 MHz channel that consists of two 20 MHz channels, + * with the primary channel having a higher frequency + */ + WLAN_CHANNEL_FLAG_HT40MINUS = UINT32_BIT(5), /**< A 40 MHz channel that consists of two 20 MHz channels, + * with the primary channel having a lower frequency + */ + WLAN_CHANNEL_FLAG_HT40 = UINT32_BIT(6), /**< 40 MHz channel */ + WLAN_CHANNEL_FLAG_SURVEY_LIST_INITIALIZED = UINT32_BIT(7), /**< Survey list initialized */ + WLAN_CHANNEL_FLAG_DFS_USABLE = UINT32_BIT(8), /**< Dynamic frequency selection (DFS) supported */ + WLAN_CHANNEL_FLAG_DFS_UNAVAILABLE = UINT32_BIT(9), /**< DFS disabled */ + WLAN_CHANNEL_FLAG_DFS_AVAILABLE = WLAN_CHANNEL_FLAG_DFS_USABLE | WLAN_CHANNEL_FLAG_DFS_UNAVAILABLE, + WLAN_CHANNEL_FLAG_VHT_10_70 = + UINT32_BIT(11), /**< A 80 MHz channel: Frequency + * band = Channel's center frequency - 10 MHz to the channel's center frequency + 70 MHz + */ + WLAN_CHANNEL_FLAG_VHT_30_50 = + UINT32_BIT(12), /**< A 80 MHz channel: Frequency + * band = Channel's center frequency - 30 MHz to the channel's center frequency + 50 MHz + */ + WLAN_CHANNEL_FLAG_VHT_50_30 = + UINT32_BIT(13), /**< A 80 MHz channel: Frequency + * band = Channel's center frequency - 50 MHz to the channel's center frequency + 30 MHz + */ + WLAN_CHANNEL_FLAG_VHT_70_10 = + UINT32_BIT(14), /**< A 80 MHz channel: Frequency + * band = Channel's center frequency - 70 MHz to the channel's center frequency + 10 MHz + */ + WLAN_CHANNEL_FLAG_INDOOR_ONLY = UINT32_BIT(16), /**< Used only indoors */ + WLAN_CHANNEL_FLAG_GO_CONCURRENT = UINT32_BIT(17), /**< Go Concurrent supported */ + WLAN_CHANNEL_FLAG_VHT_10_150 = UINT32_BIT(20), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 10 MHz to the channel's center frequency + 150 MHz + */ + WLAN_CHANNEL_FLAG_VHT_30_130 = UINT32_BIT(21), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 30 MHz to the channel's center frequency + 130 MHz + */ + WLAN_CHANNEL_FLAG_VHT_50_110 = UINT32_BIT(22), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 50 MHz to the channel's center frequency + 110 MHz + */ + WLAN_CHANNEL_FLAG_VHT_70_90 = UINT32_BIT(23), /**< A 160 MHz channel: Frequency band = Channel's center + frequency - 70 MHz to the channel's center frequency + 90 MHz + */ + WLAN_CHANNEL_FLAG_VHT_90_70 = UINT32_BIT(24), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 90 MHz to the channel's center frequency + 70 MHz + */ + WLAN_CHANNEL_FLAG_VHT_110_50 = UINT32_BIT(25), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 110 MHz to the channel's center frequency + 50 MHz + */ + WLAN_CHANNEL_FLAG_VHT_130_30 = UINT32_BIT(26), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 130 MHz to the channel's center frequency + 30 MHz + */ + WLAN_CHANNEL_FLAG_VHT_150_10 = UINT32_BIT(27), /**< A 160 MHz channel: Frequency band = Channel's center + * frequency - 150 MHz to the channel's center frequency + 10 MHz + */ }; -#define IEEE80211_CHANNEL_RESV 3 /** * @brief Describes a communication channel. * * @since 1.0 + * @version 1.0 */ -struct Ieee80211Channel { - enum Ieee80211Band band; /**< Frequency band, either 2.4 GHz or 5 GHz */ - uint16_t centerFreq; /**< Center frequency */ - uint16_t hwValue; /**< Hardware information */ - uint32_t flags; /**< WLAN channel flag */ - int32_t maxAntennaGain; /**< Maximum antenna gain, in dBi */ - int32_t maxPower; /**< Maximum transmit power, in dBm */ - int8_t beaconFound; /**< When a beacon frame is found in this channel */ - uint8_t resv[IEEE80211_CHANNEL_RESV]; /**< Reserved field */ - uint32_t origFlags; /**< Channel flags */ - int32_t origMag; /**< Reserved field */ - int32_t origMpwr; /**< Reserved field */ -}; - -#define IEEE80211_RATE_RESV 2 -/** - * @brief Describes the IEEE 802.11 rate. - * - * @since 1.0 - */ -struct Ieee80211Rate { - uint32_t flags; /**< Rate flag */ - uint16_t bitrate; /**< Bit rate, in 100 kbit/s */ - uint16_t hwValue; /**< Hardware information */ - uint16_t hwValueShort; /**< Hardware information specified when a short preamble is used */ - uint8_t rsv[IEEE80211_RATE_RESV]; /**< Reserved field */ -}; - -#define IEEE80211_HT_MCS_MASK_LEN 10 -#define IEEE80211_MACINFO_RESV 3 -/** - * @brief Describes IEEE 802.11 Modulation and Coding Scheme (MCS) information. - * - * @since 1.0 - */ -struct Ieee80211McsInfo { - uint8_t rxMask[IEEE80211_HT_MCS_MASK_LEN]; /**< Mask for receiving data */ - uint16_t rxHighest; /**< Maximum rate for receiving data */ - uint8_t txParams; /**< Parameters for sending data */ - uint8_t reserved[IEEE80211_MACINFO_RESV]; /**< Reserved field */ -}; - -#define IEEE80211_STAHTCAP_RESV 3 -/** - * @brief Describes the IEEE 802.11 high-throughput (HT) capability. - * - * @since 1.0 - */ -struct Ieee80211StaHtCap { - uint16_t cap; /**< HT capability table provided in 802.11n */ - uint8_t htSupported; /**< Whether the station supports HT */ - uint8_t ampduFactor; /**< Maximum length of an aggregated MAC Protocol Data Unit (A-MPDU) */ - uint8_t ampduDensity; /**< Minimum MPDU start spacing */ - uint8_t aucRsv[IEEE80211_STAHTCAP_RESV]; /**< Reserved field */ - struct Ieee80211McsInfo mcs; /**< MCS rate */ +struct WlanChannel { + uint8_t channelId; /**< Channel ID */ + uint32_t centerFreq; /**< Center frequency */ + uint32_t flags; /**< Flags for the channel, as enumerated in WlanChannelCapabilityFlags */ }; /** - * @brief Describes IEEE 802.11 band information. + * @brief Describes a band. * * @since 1.0 + * @version 1.0 */ -struct Ieee80211SupportedBand { - struct Ieee80211Channel *channels; /**< An array of supported channels */ - struct Ieee80211Rate *bitrates; /**< An array of supported bit rates */ - enum Ieee80211Band band; /**< Band matching this data structure description */ - int32_t nChannels; /**< Length of the array of supported channels */ - int32_t nBitrates; /**< Length of the array of supported bit rates */ - struct Ieee80211StaHtCap htCap; /**< HT capability */ +struct WlanBand { + uint16_t channelCount; /**< Number of channels */ + struct WlanChannel channels[0]; /**< WLAN channel structures */ }; -#define WIPHY_RSV_SIZE 2 -#define WIPHY_PRIV_SIZE 4 -/** - * @brief Describes a wiphy device. - * - * @since 1.0 - */ -struct Wiphy { - uint8_t permAddr[WLAN_MAC_ADDR_LEN]; /**< Permanent MAC address of the wiphy device. For its length, - * see {@link WLAN_MAC_ADDR_LEN}. - */ - uint8_t addrMask[WLAN_MAC_ADDR_LEN]; /**< MAC address mask of the wiphy device. If the device supports multiple - * virtual MAC addresses, the bit whose value is 1 in the mask - * represents a variable part of the MAC address. - */ - uint32_t flags; /**< Wiphy device attributes */ - uint8_t signalType; /**< Signal type */ - uint8_t maxScanSsids; /**< Maximum number of scanned service set identifiers (SSIDs) */ - uint16_t interfaceModes; /**< Bitmask of an API type that is valid for the wiphy device */ - uint16_t maxScanIeLen; /**< Maximum SSID length */ - uint8_t aucRsv[WIPHY_RSV_SIZE]; /**< Manual alignment of data structures */ - int32_t nCipherSuites; /**< Number of supported cipher suites */ - const uint32_t *cipherSuites; /**< Supported cipher suites */ - uint32_t fragThreshold; /**< Fragment threshold */ - uint32_t rtsThreshold; /**< Request To Send (RTS) threshold */ - struct Ieee80211SupportedBand *bands[IEEE80211_NUM_BANDS]; - /**< Supported bands */ - uint8_t priv[WIPHY_PRIV_SIZE]; /**< Reserved field */ -}; - -#define IEEE80211_MAX_SSID_LEN 32 /** * @brief Describes an SSID. * * @since 1.0 + * @version 1.0 */ -struct WifiSsid { - uint8_t ssid[IEEE80211_MAX_SSID_LEN]; /**< SSID content, which contains a maximum of 32 bytes */ - uint8_t ssidLen; /**< SSID length */ +struct WlanSSID { + uint8_t ssid[IEEE80211_MAX_SSID_LEN]; /**< SSID array */ + uint8_t ssidLen; /**< SSID length */ }; -/** - * @brief Enumerates channel types. - * - * @since 1.0 - */ -enum WifiChannelType { - WIFI_CHAN_NO_HT, /**< non-HT channel */ - WIFI_CHAN_HT20, /**< 20 MHz HT channel */ - WIFI_CHAN_HT40MINUS, /**< 40 MHz minus HT channel (The channel is formed by two 20 MHz HT channels, one as - * the main channel and the other as the auxiliary channel. The center frequency of the main - * channel is lower than that of the auxiliary channel.) - */ - WIFI_CHAN_HT40PLUS /**< 40 MHz plus HT channel (The channel is formed by two 20 MHz HT channels, one as - * the main channel and the other as the auxiliary channel. The center frequency of the main - * channel is higher than that of the auxiliary channel.) - */ -}; - -/** - * @brief Describes a communication channel. - * - * @since 1.0 - */ -struct ChannelDef { - struct Ieee80211Channel *chan; /**< Channel information */ - enum WifiChannelType width; /**< Bandwidth */ - int32_t centerFreq1; /**< Center frequency 1 */ - int32_t centerFreq2; /**< Center frequency 2 */ -}; - -#define WIRELESS_DEV_RESV_SIZE 3 -/** - * @brief Describes a wireless device. - * - * @since 1.0 - */ -struct WirelessDev { - struct NetDevice *netdev; /**< Network device */ - struct Wiphy *wiphy; /**< Wiphy device */ - uint8_t iftype; /**< API type */ - uint8_t resv[WIRELESS_DEV_RESV_SIZE]; /**< Reserved field */ - struct ChannelDef presetChandef; /**< Channel information */ -}; - -#define MAX_SCAN_CHANNELS 14 -#define SCAN_REQUEST_RESV_SIZE 2 /** * @brief Describes scan request parameters. * * @since 1.0 + * @version 1.0 */ -struct WifiScanRequest { - struct WifiSsid *ssids; /**< SSIDs to scan for */ - uint32_t nSsids; /**< Number of SSIDs to scan for */ - uint32_t nChannels; /**< Number of channels to scan for */ - uint32_t ieLen; /**< IEEE 802.11 buffer length */ - struct Wiphy *wiphy; /**< A specified wiphy device to scan for */ - struct NetDevice *dev; /**< A specified network device to scan for */ - struct WirelessDev *wdev; /**< A specified wireless device to scan for */ - uint8_t aborted; /**< Whether to abort the scan */ - uint8_t prefixSsidScanFlag; /**< Reserved field */ - uint8_t resv[SCAN_REQUEST_RESV_SIZE]; /**< Reserved field */ - uint8_t *ie; /**< IEEE 802.11 buffer */ - struct Ieee80211Channel *channels[MAX_SCAN_CHANNELS]; /**< Channels to scan for. For details, - * see {@link MAX_SCAN_CHANNELS}. - */ +struct WlanScanRequest { + uint8_t ssidCount; /**< Number of SSIDs */ + uint8_t freqsCount; /**< Number of frequencies */ + uint8_t *bssid; /**< BSSID to scan for */ + struct WlanSSID *ssids; /**< SSIDs to scan for */ + uint16_t *freqs; /**< An array of frequencies */ + uint32_t extraIEsLen; /**< Length of an extended information element (IE) */ + uint8_t *extraIEs; /**< Extended IEs */ }; -#define NL80211_MAX_NR_CIPHER_SUITES 5 -#define NL80211_MAX_NR_AKM_SUITES 2 /** * @brief Describes cryptography settings. * * @since 1.0 + * @version 1.0 */ struct CryptoSettings { - uint32_t wpaVersions; /**< WPA version */ - uint32_t cipherGroup; /**< Cipher group */ - int32_t n_ciphersPairwise; /**< Number of unicast ciphers supported by the access point (AP) */ - uint32_t ciphersPairwise[NL80211_MAX_NR_CIPHER_SUITES]; - /**< Unicast cipher suite. For details, see {@link NL80211_MAX_NR_CIPHER_SUITES}. */ - int32_t n_akmSuites; /**< Number of authentication and key management (AKM) suites */ - uint32_t akmSuites[NL80211_MAX_NR_AKM_SUITES]; - /**< AKM suite data. For details, see {@link NL80211_MAX_NR_AKM_SUITES}. */ + uint32_t wpaVersions; /**< WPA version */ + uint32_t cipherGroup; /**< Cipher group */ + int32_t n_ciphersPairwise; /**< Number of unicast ciphers supported by the AP */ + uint32_t ciphersPairwise[NL80211_MAX_NR_CIPHER_SUITES]; /**< Unicast cipher suites. The maximum number of + * unicast cipher suites is specified by + * {@link NL80211_MAX_NR_CIPHER_SUITES}. + */ + int32_t n_akmSuites; /**< Number of authentication and key management (AKM) suites */ + uint32_t akmSuites[NL80211_MAX_NR_AKM_SUITES]; /**< AKM suites. The maximum number of AKM suites is specified + * by {@link NL80211_MAX_NR_AKM_SUITES}. + */ uint16_t controlPortEthertype; /**< Data can be transmitted over an unauthenticated port. */ int8_t controlPort; /**< Whether the user space control port is authorized. The value true * indicates that the user space control port is unauthorized. */ - int8_t controlPortNoEncrypt; /**< Whether to encrypt frames transmitted over the control port. - * The value 1 indicates that the frames are not encrypted. - */ + int8_t controlPortNoEncrypt; /**< Whether to encrypt frames transmitted over the control port. + * The value 1 indicates that the frames are not encrypted. + */ }; -#define ETH_ADDR_LEN 6 -/** - * @brief Describes the device MAC address. - * - * @since 1.0 - */ -struct MacAddress { - uint8_t addr[ETH_ADDR_LEN]; /**< Device MAC address */ -}; - -#define WIFI_CONNECT_PARM_RESV_SIZE 3 /** * @brief Describes parameters for a connection request. * * @since 1.0 + * @version 1.0 */ -typedef struct WifiConnectParams { - struct Ieee80211Channel *channel; /**< Connection channel. If this parameter is not specified, the connection - * channel is automatically obtained from the scan result. - */ - uint8_t *bssid; /**< AP basic service set identifier (BSSID). If this parameter is not - * specified, the AP BSSID is automatically obtained from the scan result. - */ - uint8_t *ssid; /**< SSID */ - uint8_t *ie; /**< IEEE 802.11 information required for the connection */ - uint32_t ssidLen; /**< SSID length */ - uint32_t ieLen; /**< IEEE 802.11 length */ - struct CryptoSettings crypto; /**< Cryptography information */ - const uint8_t *key; /**< Wired Equivalent Privacy (WEP) key used for Shared Key - * Authentication (SKA) - */ - uint8_t authType; /**< Authorization type */ - uint8_t privacy; /**< Whether to use a privacy-enabled AP */ - uint8_t keyLen; /**< Key length */ - uint8_t keyIdx; /**< Index of the WEP key used for SKA */ - uint8_t mfp; /**< Whether to enable Management Frame Protection (MFP) */ - uint8_t aucResv[WIFI_CONNECT_PARM_RESV_SIZE]; - /**< Reserved field */ -} WifiConnectParams; - -/** - * @brief Describes virtual API parameters. - * - * @since 1.0 - */ -struct VifParams { - int32_t use4Addr; /**< Whether to use a frame containing four addresses */ - uint8_t *macAddr; /**< MAC address */ -}; +typedef struct WlanConnectParams { + uint32_t centerFreq; /**< Connection channel. If this parameter is not specified, the connection channel + * is automatically obtained from the scan result. + */ + uint8_t *bssid; /**< AP BSSID. If this parameter is not specified, the AP BSSID is automatically + * obtained from the scan result. + */ + uint8_t *ssid; /**< SSID */ + uint8_t *ie; /**< IE information required for the connection */ + uint32_t ssidLen; /**< SSID length */ + uint32_t ieLen; /**< IE length */ + struct CryptoSettings crypto; /**< Cryptography information */ + const uint8_t *key; /**< Wired Equivalent Privacy (WEP) key used for Shared Key + * Authentication (SKA) + */ + uint8_t authType; /**< Authorization type */ + uint8_t privacy; /**< Whether to use a privacy-enabled AP */ + uint8_t keyLen; /**< Key length */ + uint8_t keyIdx; /**< Index of the WEP key used for SKA */ + uint8_t mfp; /**< Whether to enable Management Frame Protection (MFP) */ + uint8_t aucResv[WIFI_CONNECT_PARM_RESV_SIZE]; /**< Reserved field */ +} WlanConnectParams; /** * @brief Describes parameters for canceling a connection. * * @since 1.0 + * @version 1.0 */ struct StationDelParameters { - const uint8_t *mac; /**< MAC address of the station to which the connection is to be canceled */ - uint8_t subtype; /**< Cancellation type */ - uint16_t reasonCode; /**< Cause of the cancellation */ + const uint8_t *mac; /**< MAC address of the station with which the connection is to be canceled */ + uint8_t subtype; /**< Cancellation type */ + uint16_t reasonCode; /**< Reason code for the cancellation */ }; /** * @brief Describes MAC configuration parameters. * * @since 1.0 + * @version 1.0 */ typedef struct MacConfigParam { - uint8_t mac[WLAN_MAC_ADDR_LEN]; /**< MAC address. For details about its length, see {@link WLAN_MAC_ADDR_LEN}. */ - uint8_t p2pMode; /**< Whether the peer-to-peer (P2P) mode is used. */ + uint8_t mac[IEEE80211_MAC_ADDR_LEN]; /**< MAC address. For details about its length, see {@link + * IEEE80211_MAC_ADDR_LEN}. + */ + uint8_t p2pMode; /**< Whether the peer-to-peer (P2P) mode is used. */ + uint8_t resv; /**< Reserved field */ } Mac80211SetMacParam; -#define OAL_IEEE80211_MAX_SSID_LEN 32 /** * @brief Describes disconnection parameters. * * @since 1.0 + * @version 1.0 */ typedef struct { - uint8_t macAddr[WLAN_MAC_ADDR_LEN]; /**< Device MAC address */ - uint16_t reasonCode; /**< Disconnection reason code */ + uint8_t macAddr[IEEE80211_MAC_ADDR_LEN]; /**< Device MAC address */ + uint16_t reasonCode; /**< Disconnection reason code */ } Mac80211DisconnectParam; -#define MAC80211_SSIDS_AUC_SIZE 3 /** - * @brief Describes SSIDs. + * @brief Describes the beacon configuration. * * @since 1.0 + * @version 1.0 */ -typedef struct { - uint8_t aucSsid[OAL_IEEE80211_MAX_SSID_LEN]; /**< SSID array */ - uint8_t ssidLen; /**< SSID length */ - uint8_t aucArry[MAC80211_SSIDS_AUC_SIZE]; /**< AuC data array */ -} Mac80211Ssids; - -#define WLAN_SCAN_REQ_MAX_BSS 2 -/** - * @brief Describes beacon parameters. - * - * @since 1.0 - */ -typedef struct { - int32_t interval; /**< Beacon interval */ - int32_t dtimPeriod; /**< Delivery Traffic Indication Message (DTIM) interval */ - WifiBeaconData *beaconData; /**< Beacon frame data */ - uint8_t hiddenSsid; /**< Whether to hide the SSID */ - uint8_t operationType; /**< Operation type */ -} Mac80211beaconParam; - -/** - * @brief Describes MAC-layer control APIs that need to be implemented by the driver. - * - * @since 1.0 - */ -struct WifiMac80211Ops { - int32_t (*changeVirtualIntf)(NetDevice *netDev, uint8_t iftype, uint32_t *flags, - struct VifParams *params); /**< Changing virtual APIs */ - int32_t (*setSsid)(NetDevice *netDev, const uint8_t *ssid, uint32_t ssidLen); /**< Setting the SSID */ - int32_t (*setMeshId)(NetDevice *netDev, const char *meshId, uint32_t meshIdLen); /**< Setting the mesh ID */ - int32_t (*setMacAddr)(NetDevice *netDev, Mac80211SetMacParam *param); /**< Setting the MAC address */ - int32_t (*changeBeacon)(NetDevice *netDev, Mac80211beaconParam *param); /**< Setting the beacon frame - * based on specified parameters - */ - int32_t (*setChannel)(NetDevice *netDev); /**< Setting the channel */ - int32_t (*addKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, - struct KeyParams *params); /**< Adding a key with specified - * parameters - */ - int32_t (*delKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr); - /**< Deleting a key based on a - * specified MAC address - */ - int32_t (*setDefaultKey)(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicas); - /**< Setting the default key */ - int32_t (*startAp)(NetDevice *netDev); /**< Starting an AP */ - int32_t (*stopAp)(NetDevice *netDev); /**< Stopping an AP */ - int32_t (*delStation)(NetDevice *netDev, const uint8_t *macAddr); /**< Deleting a station with a - * specified MAC address - */ - int32_t (*connect)(NetDevice *netDev, WifiConnectParams *param); /**< Starting a connection based - * on the specified parameters - */ - int32_t (*disconnect)(NetDevice *netDev, uint16_t reasonCode); /**< Canceling a connection */ - int32_t (*startScan)(NetDevice *netDev, struct WifiScanRequest *param); /**< Starting a scan based on the - * specified parameters - */ - int32_t (*abortScan)(NetDevice *netDev); /**< Stopping a scan */ +struct WlanBeaconConf { + uint32_t interval; /**< Beacon interval */ + uint32_t DTIMPeriod; /**< Delivery Traffic Indication Message (DTIM) interval for sending beacons */ + uint8_t *headIEs; /**< One or more IEs before the TIM IE */ + size_t headIEsLength; /**< Length of the IEs before the TIM IE */ + uint8_t *tailIEs; /**< One or more IEs after the TIM IE */ + size_t tailIEsLength; /**< Length of the IEs after the TIM IE */ + bool hiddenSSID; /**< Whether to hide the SSID */ }; /** - * @brief Registers a {@link WifiMac80211Ops} object. - * - * @param ops Indicates the pointer to the {@link WifiMac80211Ops} object to register. - * - * @return Returns 0 if the {@link WifiMac80211Ops} object is registered successfully; - * returns a non-zero value otherwise. + * @brief Describes the AP configuration. * * @since 1.0 * @version 1.0 */ -int32_t Mac80211RegisterOps(struct WifiMac80211Ops *ops) __attribute__((weak)); +struct WlanAPConf { + struct WlanSSID ssidConf; /**< SSID configuration */ + uint16_t channel; /**< Channel */ + uint16_t centerFreq1; /**< Center frequency 1 */ + uint16_t centerFreq2; /**< Center frequency 2 */ + uint8_t band; /**< Band, as enumerated in Ieee80211Band */ + uint8_t width; /**< Channel width, as enumerated in Ieee80211ChannelWidth */ +}; /** - * @brief Obtains the {@link WifiMac80211Ops} object that the driver needs to implement. - * - * @return Returns the pointer to the {@link WifiMac80211Ops} object. + * @brief Describes the hardware capability. * * @since 1.0 * @version 1.0 */ -struct WifiMac80211Ops *Mac80211GetOps(void); +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 */ +}; + +/** + * @brief Describes the MAC-layer APIs for basic operations that need to be implemented by the driver. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfMac80211BaseOps { + /** + * @brief Sets the WLAN mode. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param mode Indicates the WLAN mode to set. + * + * @return Returns 0 if the WLAN mode is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetMode)(NetDevice *netDev, enum WlanWorkMode mode); + + /** + * @brief Adds a key with specified parameters. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param keyIndex Indicates the key index. + * @param pairwise Specifies whether the key is a key pair. + * @param macAddr Indicates the pointer to the MAC address. + * @param params Indicates the pointer to the key parameters. + * + * @return Returns 0 if the key is added; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*AddKey)(struct NetDevice *netDev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, + struct KeyParams *params); + + /** + * @brief Deletes a key with a specified MAC address. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param keyIndex Indicates the key index. + * @param pairwise Specifies whether the key is a key pair. + * @param macAddr Indicates the pointer to the MAC address. + * + * @return Returns 0 if the key is deleted; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*DelKey)(struct NetDevice *netDev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr); + + /** + * @brief Sets the default key. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param keyIndex Indicates the key index. + * @param unicast Indicates the unicast. + * @param multicas Indicates the multicast. + * + * @return Returns 0 if the default key is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetDefaultKey)(struct NetDevice *netDev, uint8_t keyIndex, bool unicast, bool multicas); + + /** + * @brief Obtains the device MAC address. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param type Indicates the MAC address type of the device. + * @param mac Indicates the pointer to the MAC address. + * @param len Indicates the length of the MAC address. + * + * @return Returns 0 if the MAC address is obtained; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetDeviceMacAddr)(NetDevice *netDev, int32_t type, uint8_t *mac, uint8_t len); + + /** + * @brief Sets the MAC address. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param mac Indicates the pointer to the MAC address. + * @param len Indicates the length of the MAC address. + * + * @return Returns 0 if the MAC address is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetMacAddr)(NetDevice *netDev, uint8_t *mac, uint8_t len); + + /** + * @brief Sets the transmit power. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param power Indicates the transmit power to set. + * + * @return Returns 0 if the transmit power is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetTxPower)(NetDevice *netDev, int32_t power); + + /** + * @brief Obtains the frequencies supported by the 2.4 GHz or 5 GHz band. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param band Indicates the frequency band, either 2.4 GHz or 5 GHz. + * @param freqs Indicates the pointer to the supported frequencies. + * @param num Indicates the pointer to the number of supported frequencies. + * + * @return Returns 0 if the supported frequencies are obtained; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetValidFreqsWithBand)(NetDevice *netDev, int32_t band, int32_t *freqs, uint32_t *num); + + /** + * @brief Obtains the hardware capability supported by the device. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param capability Indicates the double pointer to the hardware capability. + * + * @return Returns 0 if the hardware capability is obtained; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetHwCapability)(NetDevice *netDev, struct WlanHwCapability **capability); +}; + +/** + * @brief Describes the MAC-layer APIs for station operations that need to be implemented by the driver. + * + * @since 1.0 + * @version 1.0 + */ +struct HdfMac80211STAOps { + /** + * @brief Starts a connection based on the specified parameters. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param param Indicates the pointer to the connection parameters. + * + * @return Returns 0 if the connection is started; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Connect)(NetDevice *netDev, WlanConnectParams *param); + + /** + * @brief Cancels a connection. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param reasonCode Indicates the reason code for connection cancellation. + * + * @return Returns 0 if the connection is canceled; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*Disconnect)(NetDevice *netDev, uint16_t reasonCode); + + /** + * @brief Starts a scan based on the specified parameters. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param param Indicates the pointer to the scan parameters. + * + * @return Returns 0 if the scan is started; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*StartScan)(NetDevice *netDev, struct WlanScanRequest *param); + + /** + * @brief Stops a scan. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the scan is stopped; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*AbortScan)(NetDevice *netDev); + + /** + * @brief Sets scanning for a single MAC address. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param mac Indicates the pointer to the MAC address. + * @param len Indicates the length of the MAC address. + * + * @return Returns 0 if the setting is successful; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetScanningMacAddress)(NetDevice *netDev, unsigned char *mac, uint32_t len); +}; + +/** + * @brief Describes the MAC-layer APIs for AP operations that need to be implemented by the driver. + * + * @since 1.0 + */ +struct HdfMac80211APOps { + /** + * @brief Sets an AP. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param apConf Indicates the pointer to the AP configuration. + * + * @return Returns 0 if the AP is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*ConfigAp)(NetDevice *netDev, struct WlanAPConf *apConf); + + /** + * @brief Starts an AP. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the AP is started; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*StartAp)(NetDevice *netDev); + + /** + * @brief Stops an AP. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the AP is stopped; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*StopAp)(NetDevice *netDev); + + /** + * @brief Sets a beacon. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param beaconConf Indicates the pointer to the beacon configuration. + * + * @return Returns 0 if the beacon is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*ConfigBeacon)(NetDevice *netDev, struct WlanBeaconConf *beaconConf); + + /** + * @brief Deletes a station with a specified MAC address. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param macAddr Indicates the pointer to the MAC address. + * + * @return Returns 0 if the station is deleted; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*DelStation)(NetDevice *netDev, const uint8_t *macAddr); + + /** + * @brief Sets the country/region code. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param code Indicates the pointer to the country/region code. + * @param len Indicates the length of the country/region code. + * + * @return Returns 0 if the country/region code is set; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*SetCountryCode)(NetDevice *netDev, const char *code, uint32_t len); + + /** + * @brief Obtains the number of associated stations. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param num Indicates the pointer to the number of associated stations. + * + * @return Returns 0 if the number of associated stations is obtained; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetAssociatedStasCount)(NetDevice *netDev, uint32_t *num); + + /** + * @brief Obtains information about the associated stations. + * + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * @param staInfo Indicates the pointer to the information about the associated stations. + * @param num Indicates the number of associated stations. + * + * @return Returns 0 if the information is obtained; returns a non-zero value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*GetAssociatedStasInfo)(NetDevice *netDev, WifiStaInfo *staInfo, uint32_t num); +}; #endif // _WIFI_MAC80211_OPS_H_ +/** @} */ diff --git a/include/wifi/wifi_module.h b/include/wifi/wifi_module.h old mode 100755 new mode 100644 index 2dad717f..f58b04dd --- a/include/wifi/wifi_module.h +++ b/include/wifi/wifi_module.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -46,8 +25,8 @@ * * @brief Provides features of the WLAN module and functions to create and delete modules. * - * The WifiModule object is a core abstraction of the WLAN driver. It contains a module that communicates with - * user-level processes and also contains features. + * The {@link WifiModule} object is a core abstraction of the WLAN driver. It contains a module that communicates + * with user-level processes and also contains features. * * @since 1.0 * @version 1.0 @@ -58,33 +37,102 @@ #include "wifi_inc.h" #include "wifi_module_config.h" +#include "net_device.h" #ifdef __cplusplus extern "C" { #endif -/*********************************************************************** -* -* WLAN MODULE -* -************************************************************************/ + +/** + * @brief Defines a WLAN feature. + * + * @since 1.0 + * @version 1.0 + */ +struct WifiFeature { + char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Feature name, which contains a maximum of 10 characters */ + /** + * @brief Initializes a feature. + * + * @param feature Indicates the pointer to the feature. + * + * @return Returns 0 if the feature is initialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*init)(struct WifiFeature *feature); + + /** + * @brief Deinitializes a feature. + * + * @param feature Indicates the pointer to the feature. + * + * @return Returns 0 if the feature is deinitialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*deInit)(struct WifiFeature *feature); +}; + +/** + * @brief Defines the WLAN feature list. + * + * @since 1.0 + * @version 1.0 + */ +struct WifiFeatureList { + struct WifiFeature *fe[HDF_WIFI_FEATURE_NUM]; /**< An array of WLAN features */ +}; + /** * @brief Defines WLAN module APIs. * * The APIs can be used to obtain, initialize, update, and perform other operations on a WLAN module. * * @since 1.0 + * @version 1.0 */ struct WifiModuleIface { - struct WifiModule *(*getModule)(void); /**< Obtaining a WLAN module */ - int32_t (*updateModule)(struct WifiModule *module); /**< Updating a WLAN module based on a specified - * configuration. - */ - int32_t (*init)(struct WifiModule *module); /**< Initializing a WLAN module */ - int32_t (*deInit)(struct WifiModule *module); /**< Deinitializing a WLAN module */ + /** + * @brief Deinitializes a WLAN module. + * + * @param module Indicates the pointer to the WLAN module. + * + * @return Returns 0 if the WLAN module is deinitialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*deInit)(struct WifiModule *module); - int32_t (*addFeature)(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData); - /**< Adding a feature */ - int32_t (*delFeature)(struct WifiModule *module, uint16_t featureType); /**< Deleting a feature */ + /** + * @brief Adds a feature. + * + * @param module Indicates the pointer to the WLAN module. + * @param featureType Indicates the feature type. + * @param feature Indicates the pointer to the feature. + * + * @return Returns 0 if the feature is added; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*addFeature)(struct WifiModule *module, uint16_t featureType, struct WifiFeature *feature); + + /** + * @brief Deletes a feature. + * + * @param module Indicates the pointer to the WLAN module. + * @param featureType Indicates the feature type. + * + * @return Returns 0 if the feature is deleted; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*delFeature)(struct WifiModule *module, uint16_t featureType); }; /** @@ -94,119 +142,75 @@ struct WifiModuleIface { * processes, and WLAN features. * * @since 1.0 + * @version 1.0 */ struct WifiModule { - void *modulePrivate; /**< Private data */ - struct WifiModuleIface *iface; /**< APIs */ - struct WifiModuleConfig moduleConfig; /**< Module configurations */ - struct WifiFeatureList *feList; /**< WLAN features */ + void *modulePrivate; /**< Private data */ + struct WifiModuleIface iface; /**< APIs */ + struct WifiModuleConfig moduleConfig; /**< Module configurations */ + struct WifiFeatureList feList; /**< WLAN features */ }; /** - * @brief Creates a {@link WifiModule} object based on a specified configuration generated by the HCS. - * - * @param config Indicates the pointer to the configuration generated by the HCS. - * - * @return Returns the created {@link WifiModule} object. + * @brief Defines a WLAN chip driver. * * @since 1.0 * @version 1.0 */ -struct WifiModule *WifiModuleCreate(const struct HdfConfigWifiModuleConfig *config); +struct HdfChipDriver { + uint16_t type; /**< Chip type */ + char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Chip name */ + struct HdfMac80211BaseOps *ops; /**< MAC address for the basic feature */ + struct HdfMac80211STAOps *staOps; /**< MAC address for the STA feature */ + struct HdfMac80211APOps *apOps; /**< MAC address for the AP feature */ + void *priv; /**< Private data of the chip driver */ + /** + * @brief Initializes a chip driver. + * + * @param chipDriver Indicates the pointer to the chip driver. + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the chip is initialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*init)(struct HdfChipDriver *chipDriver, NetDevice *netDev); + + /** + * @brief Deinitializes a chip driver. + * + * @param chipDriver Indicates the pointer to the chip driver. + * @param netDev Indicates the pointer to the network device structure obtained during initialization. + * + * @return Returns 0 if the chip is deinitialized; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*deinit)(struct HdfChipDriver *chipDriver, NetDevice *netDev); +}; /** - * @brief Deletes a specified {@link WifiModule} object. + * @brief Initializes a WifiModule object. * - * @param module Indicates the pointer to the {@link WifiModule} object to delete. + * @param module Indicates the pointer to the WifiModule object to initialize. + * @param config Indicates the pointer to the configuration generated by the HDF Configuration Source (HCS). + * + * @return Returns 0 if the WifiModule object is initialized; returns a negative value otherwise. * * @since 1.0 * @version 1.0 */ -void WifiModuleDelete(struct WifiModule *module); +int16_t InitWifiModule(struct WifiModule *module, const struct HdfConfigWlanModuleConfig *config); -/*********************************************************************** -* -* WLAN MODULE FEATURE -* -************************************************************************/ -/** - * @brief Defines a WLAN feature. - * - * @since 1.0 - */ -struct WifiFeature { - char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Feature name, which can contain a maximum of 10 characters */ - struct HdfWifiChipData *chip; /**< Chip */ - int32_t (*init)(struct WifiFeature *feature); /**< Function for initializing the feature */ - int32_t (*deInit)(struct WifiFeature *feature); /**< Function for deinitializing the feature */ -}; - -/** - * @brief Defines the WLAN feature list. - * - * @since 1.0 - */ -struct WifiFeatureList { - struct WifiFeature *fe[HDF_WIFI_FEATURE_NUM]; /**< An array of WLAN features */ -}; - -/** - * @brief Deletes a specified feature from a specified module. - * - * @param module Indicates the pointer to the module. - * @param featureType Indicates the type of the feature to delete. - * - * @return Returns 0 if the feature is deleted successfully; returns -1 otherwise. - * - * @since 1.0 - * @version 1.0 - */ -int32_t DelFeature(struct WifiModule *module, uint16_t featureType); - -/** - * @brief Adds a specified feature to a specified module. - * - * @param module Indicates the pointer to the module. - * @param featureType Indicates the type of the feature to add. - * @param featureData Indicates the pointer to the feature to add. - * - * @return Returns 0 if the feature is added successfully; returns a negative value otherwise. - * - * @since 1.0 - * @version 1.0 - */ -int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData); - -/*********************************************************************** -* -* WLAN MODULE CHIP -* -************************************************************************/ -/** - * @brief Defines a WLAN chip. - * - * @since 1.0 - */ -struct HdfWifiChipData { - uint16_t type; /**< Chip type */ - char name[MAX_WIFI_COMPONENT_NAME_LEN]; /**< Chip name */ - struct WifiMac80211Ops *ops; /**< Chip MAC address */ - int32_t (*init)(struct HdfWifiChipData *chipData, const struct HdfConfigWifiChip *chipConfig); - /**< Function for initializing the chip */ - int32_t (*deinit)(struct HdfWifiChipData *chipData); /**< Function for deinitializing the chip */ -}; - -#define HDF_WIFI_CHIP_DECLARE(chipName) \ - extern struct HdfWifiChipData g_hdf##chipName##ChipDriver __attribute__((weak)) - -#define HDF_WIFI_CHIP(chipName) &g_hdf##chipName##ChipDriver - -#define HDF_WIFI_CHIP_DRIVER(chipName, initFunc, deInitFunc) \ - struct HdfWifiChipData g_hdf##chipName##ChipDriver = { \ - .name = #chipName, \ - .init = initFunc, \ - .deinit = deInitFunc, \ - } +#define RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipOps, opsName) \ + do { \ + if ((chipOps) == NULL ||(chipOps)->opsName == NULL) { \ + HDF_LOGE("macOps" #opsName "not implement"); \ + return HDF_ERR_INVALID_OBJECT; \ + } \ + } while (0) #ifdef __cplusplus @@ -214,4 +218,4 @@ struct HdfWifiChipData { #endif #endif // HDFLITE_WIFI_MODULE_H - +/** @} */ diff --git a/include/wifi/wifi_module_config.h b/include/wifi/wifi_module_config.h old mode 100755 new mode 100644 index ff20de42..c528a224 --- a/include/wifi/wifi_module_config.h +++ b/include/wifi/wifi_module_config.h @@ -1,41 +1,20 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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. */ /** * @addtogroup WLAN * @{ * - * @brief Defines a WLAN module that supports cross-OS migration, component adaptation, and modular assembly and - * compilation. Driver developers of WLAN vendors can adapt their driver code based on the unified APIs provided - * by the WLAN module. + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. * * @since 1.0 * @version 1.0 @@ -54,7 +33,7 @@ #define HDFLITE_WIFI_MODULE_CONFIG_H #include "osal.h" -#include "hdf_wifi_config.h" +#include "hdf_wlan_config.h" #ifdef __cplusplus extern "C" { @@ -64,12 +43,15 @@ extern "C" { * @brief Defines the WLAN module configuration. * * @since 1.0 + * @version 1.0 */ struct WifiModuleConfig { - const struct HdfConfigWifiModuleConfig *hslConfig; /**< Configuration of each feature of the WLAN module */ + /**< Configuration of each feature of the WLAN module */ + const struct HdfConfigWlanModuleConfig *hslConfig; }; #ifdef __cplusplus } #endif #endif // HDFLITE_WIFI_MODULE_CONFIG_H +/** @} */ diff --git a/model/display/driver/hdf_disp.c b/model/display/driver/hdf_disp.c new file mode 100644 index 00000000..910d5ffe --- /dev/null +++ b/model/display/driver/hdf_disp.c @@ -0,0 +1,270 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "hdf_disp.h" + +#define OFFSET_TWO_BYTE 16 + +struct DispOperations *g_dispOps = NULL; + +int32_t DispRegister(struct DispOperations *ops) +{ + if (g_dispOps == NULL) { + g_dispOps = ops; + HDF_LOGI("%s: disp ops register success", __func__); + return HDF_SUCCESS; + } + HDF_LOGD("%s: disp ops registered", __func__); + return HDF_FAILURE; +} + +struct DispOperations *GetDispOps(void) +{ + return g_dispOps; +} + +static int32_t DispOn(uint32_t devId) +{ + int32_t ret; + struct DispOperations *ops = NULL; + + ops = GetDispOps(); + if (ops == NULL) { + HDF_LOGE("%s: ops is null", __func__); + return HDF_FAILURE; + } + if (ops->on != NULL) { + ret = ops->on(devId); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: ops on failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t DispOff(uint32_t devId) +{ + int32_t ret; + struct DispOperations *ops = NULL; + + ops = GetDispOps(); + if (ops == NULL) { + HDF_LOGE("%s: ops is null", __func__); + return HDF_FAILURE; + } + if (ops->off != NULL) { + ret = ops->off(devId); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: ops off failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t DispInit(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)device; + (void)rspData; + int32_t ret; + uint32_t devId = 0; + + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(reqData, &devId)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + return HDF_FAILURE; + } + + struct DispOperations *ops = NULL; + ops = GetDispOps(); + 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)) { + 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) +{ + uint32_t para = 0; + + (void)device; + (void)rspData; + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(reqData, ¶)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + return HDF_FAILURE; + } + uint32_t devId = (para >> OFFSET_TWO_BYTE) & 0xffff; + uint32_t mode = para & 0xffff; + if (mode == DISP_ON) { + return DispOn(devId); + } + if (mode == DISP_OFF) { + return DispOff(devId); + } + HDF_LOGE("not support mode:%u", mode); + return HDF_FAILURE; +} + +static int32_t SetBacklight(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + (void)device; + (void)rspData; + if (reqData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + uint32_t para = 0; + if (!HdfSbufReadUint32(reqData, ¶)) { + HDF_LOGE("%s: HdfSbufReadBuffer failed", __func__); + return HDF_FAILURE; + } + 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__); + 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__); + 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; + } + } + HDF_LOGI("%s:level = %u", __func__, level); + return HDF_SUCCESS; +} + +DispCmdHandle g_dispCmdHandle[] = { + DispInit, + GetDispInfo, + SetPowerMode, + SetBacklight, +}; + +static int32_t DispCmdProcess(struct HdfDeviceObject *device, int32_t cmd, struct HdfSBuf *reqData, + struct HdfSBuf *rspData) +{ + int32_t cmdNum = sizeof(g_dispCmdHandle) / sizeof(g_dispCmdHandle[0]); + if (device == NULL || reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (cmd >= cmdNum || cmd < 0) { + HDF_LOGE("%s: invalid cmd = %d", __func__, cmd); + return HDF_FAILURE; + } + HDF_LOGD("%s: cmd = %d", __func__, cmd); + if (g_dispCmdHandle[cmd] == NULL) { + return HDF_FAILURE; + } + + return g_dispCmdHandle[cmd](device, reqData, rspData); +} + +static int32_t HdfDispDispatch(struct HdfDeviceIoClient *client, int id, struct HdfSBuf *data, + struct HdfSBuf *reply) +{ + if (client == NULL) { + return HDF_ERR_INVALID_PARAM; + } + return DispCmdProcess(client->device, id, data, reply); +} + +static int HdfDispBind(struct HdfDeviceObject *dev) +{ + if (dev == NULL) { + return HDF_FAILURE; + } + static struct IDeviceIoService dispService = { + .object.objectId = 1, + .Dispatch = HdfDispDispatch, + }; + dev->service = &dispService; + return HDF_SUCCESS; +} + +static int32_t HdfDispEntryInit(struct HdfDeviceObject *object) +{ + if (object == NULL) { + HDF_LOGE("%s: object is null!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_dispDevEntry = { + .moduleVersion = 1, + .moduleName = "HDF_DISP", + .Init = HdfDispEntryInit, + .Bind = HdfDispBind, +}; + +HDF_INIT(g_dispDevEntry); diff --git a/model/display/driver/hdf_disp.h b/model/display/driver/hdf_disp.h new file mode 100644 index 00000000..c2acd9a4 --- /dev/null +++ b/model/display/driver/hdf_disp.h @@ -0,0 +1,55 @@ +/* + * 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_DISP_H +#define HDF_DISP_H +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_sbuf.h" +#include "lcd_abs_if.h" + +#ifdef HDF_LOG_TAG +#undef HDF_LOG_TAG +#endif +#define HDF_LOG_TAG HDF_DISP + +typedef int32_t (*DispCmdHandle)(struct HdfDeviceObject *device, struct HdfSBuf *reqData, struct HdfSBuf *rspData); + +struct DispInfo { + uint32_t width; + uint32_t hbp; + uint32_t hfp; + uint32_t hsw; + uint32_t height; + uint32_t vbp; + uint32_t vfp; + uint32_t vsw; + uint32_t frameRate; + uint32_t intfType; + enum IntfSync intfSync; + uint32_t minLevel; + uint32_t maxLevel; + uint32_t defLevel; +}; + +struct DispOperations { + 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); +struct PanelInfo *GetPanelInfo(int32_t index); +#endif /* HDF_DISP_H */ diff --git a/model/display/driver/hi35xx_disp.c b/model/display/driver/hi35xx_disp.c new file mode 100644 index 00000000..18a31425 --- /dev/null +++ b/model/display/driver/hi35xx_disp.c @@ -0,0 +1,451 @@ +/* + * 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_base.h" +#include "hdf_device_desc.h" +#include "hdf_disp.h" +#include "hdf_log.h" +#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 + +static void MipiMuxCfg(unsigned long ioCfgBase) +{ + /* config dsi data lane0 */ + OSAL_WRITEL(0x670, ioCfgBase + 0x0088); + OSAL_WRITEL(0x670, ioCfgBase + 0x0084); + /* config dsi data lane1 */ + OSAL_WRITEL(0x470, ioCfgBase + 0x007C); + OSAL_WRITEL(0x470, ioCfgBase + 0x0080); + /* config dsi data lane2 */ + OSAL_WRITEL(0x470, ioCfgBase + 0x006C); + OSAL_WRITEL(0x470, ioCfgBase + 0x0070); + /* config dsi data lane3 */ + OSAL_WRITEL(0x670, ioCfgBase + 0x0068); + OSAL_WRITEL(0x670, ioCfgBase + 0x0064); + /* config dsi clock lane */ + OSAL_WRITEL(0x460, ioCfgBase + 0x0074); + OSAL_WRITEL(0x460, ioCfgBase + 0x0078); +} + +static void Lcd6BitMuxCfg(unsigned long ioCfgBase) +{ + OSAL_WRITEL(0x4f4, ioCfgBase + 0x0068); + OSAL_WRITEL(0x454, ioCfgBase + 0x0084); + OSAL_WRITEL(0x474, ioCfgBase + 0x007c); + OSAL_WRITEL(0x674, ioCfgBase + 0x0088); + OSAL_WRITEL(0x474, ioCfgBase + 0x0080); + OSAL_WRITEL(0x474, ioCfgBase + 0x0074); + OSAL_WRITEL(0x474, ioCfgBase + 0x0078); + OSAL_WRITEL(0x474, ioCfgBase + 0x006C); + OSAL_WRITEL(0x474, ioCfgBase + 0x0070); + OSAL_WRITEL(0x674, ioCfgBase + 0x0064); +} + +static void Lcd8BitMuxCfg(unsigned long ioCfgBase) +{ + OSAL_WRITEL(0x422, ioCfgBase + 0x0034); + OSAL_WRITEL(0x462, ioCfgBase + 0x0058); + OSAL_WRITEL(0x462, ioCfgBase + 0x004c); + OSAL_WRITEL(0x462, ioCfgBase + 0x0054); + OSAL_WRITEL(0x422, ioCfgBase + 0x0048); + OSAL_WRITEL(0x622, ioCfgBase + 0x0040); + OSAL_WRITEL(0x622, ioCfgBase + 0x0044); + OSAL_WRITEL(0x622, ioCfgBase + 0x005C); + OSAL_WRITEL(0x622, ioCfgBase + 0x003c); + OSAL_WRITEL(0x422, ioCfgBase + 0x0038); + OSAL_WRITEL(0x622, ioCfgBase + 0x0050); + OSAL_WRITEL(0x462, ioCfgBase + 0x0060); +} + +void Lcd24BitMuxCfg(unsigned long ioCfgBase) +{ + OSAL_WRITEL(0x462, ioCfgBase + 0x0034); + OSAL_WRITEL(0x432, ioCfgBase + 0x0058); + OSAL_WRITEL(0x462, ioCfgBase + 0x004C); + OSAL_WRITEL(0x432, ioCfgBase + 0x0054); + OSAL_WRITEL(0x432, ioCfgBase + 0x0048); + OSAL_WRITEL(0x632, ioCfgBase + 0x0040); + OSAL_WRITEL(0x632, ioCfgBase + 0x0044); + OSAL_WRITEL(0x632, ioCfgBase + 0x005C); + OSAL_WRITEL(0x632, ioCfgBase + 0x003C); + OSAL_WRITEL(0x432, ioCfgBase + 0x0038); + OSAL_WRITEL(0x632, ioCfgBase + 0x0050); + OSAL_WRITEL(0x462, ioCfgBase + 0x0060); + OSAL_WRITEL(0x672, ioCfgBase + 0x0084); + OSAL_WRITEL(0x672, ioCfgBase + 0x0088); + OSAL_WRITEL(0x472, ioCfgBase + 0x007C); + OSAL_WRITEL(0x472, ioCfgBase + 0x0080); + OSAL_WRITEL(0x472, ioCfgBase + 0x0074); + OSAL_WRITEL(0x472, ioCfgBase + 0x0078); + OSAL_WRITEL(0x472, ioCfgBase + 0x006C); + OSAL_WRITEL(0x462, ioCfgBase + 0x0070); + OSAL_WRITEL(0x672, ioCfgBase + 0x0064); + OSAL_WRITEL(0x672, ioCfgBase + 0x0068); + OSAL_WRITEL(0x532, ioCfgBase + 0x0094); + OSAL_WRITEL(0x532, ioCfgBase + 0x0090); + OSAL_WRITEL(0x532, ioCfgBase + 0x008C); + OSAL_WRITEL(0x632, ioCfgBase + 0x0098); + OSAL_WRITEL(0x632, ioCfgBase + 0x009C); + OSAL_WRITEL(0x532, ioCfgBase + 0x0030); +} + +static void LcdPinMuxCfg(uint32_t intf) +{ + unsigned long ioCfgBase; + + ioCfgBase = (unsigned long)OsalIoRemap(IO_CFG2_BASE, IO_CFG_SIZE); + if (intf == MIPI_DSI) { + MipiMuxCfg(ioCfgBase); + } else if (intf == LCD_6BIT) { + Lcd6BitMuxCfg(ioCfgBase); + } else if (intf == LCD_8BIT) { + Lcd8BitMuxCfg(ioCfgBase); + } else if (intf == LCD_24BIT) { + Lcd24BitMuxCfg(ioCfgBase); + } else { + HDF_LOGE("%s: not support intf: %d", __func__, intf); + } +} + +static void PwmPinMuxCfg(uint32_t dev) +{ + /* pwm pin config */ + unsigned long ioCfgBase; + ioCfgBase = (unsigned long)OsalIoRemap(IO_CFG1_BASE, IO_CFG_SIZE); + switch (dev) { + case PWM_DEV0: + OSAL_WRITEL(0x601, ioCfgBase + 0x0024); + break; + case PWM_DEV1: + OSAL_WRITEL(0x601, ioCfgBase + 0x0028); + break; + default: + HDF_LOGE("%s: not support pwm dev: %d", __func__, dev); + break; + } +} + +static int32_t GetBitsPerPixel(enum DsiOutFormat format) +{ + int32_t bpp; + + switch (format) { + case FORMAT_RGB_16_BIT: + bpp = 16; // 16 bits per pixel + break; + case FORMAT_RGB_18_BIT: + bpp = 18; // 18 bits per pixel + break; + case FORMAT_RGB_24_BIT: + bpp = 24; // 24 bits per pixel + break; + default: + bpp = 24; // 24 bits per pixel + break; + } + return bpp; +} + +static uint32_t CalcPixelClk(struct PanelInfo *info) +{ + uint16_t hpixel; + uint16_t vline; + + hpixel = info->width + info->hbp + info->hfp + info->hsw; + vline = info->height + info->vbp + info->vfp + info->vsw; + uint32_t pixNum = hpixel * vline * info->frameRate; + if ((pixNum % TRANSFORM_KILO) == 0) { + return pixNum / TRANSFORM_KILO; + } + return (pixNum / TRANSFORM_KILO + 1); +} + +static uint32_t CalcDataRate(struct PanelInfo *info) +{ + uint16_t hpixel; + uint16_t vline; + uint32_t bitClk; + + hpixel = info->width + info->hbp + info->hfp + info->hsw; + vline = info->height + info->vbp + info->vfp + info->vsw; + int32_t bpp = GetBitsPerPixel(info->mipi.format); + uint32_t bitNum = hpixel * vline * info->frameRate * bpp; + if ((bitNum % TRANSFORM_MILL) == 0) { + bitClk = bitNum / TRANSFORM_MILL; + } else { + bitClk = bitNum / TRANSFORM_MILL + 1; + } + if ((bitClk % info->mipi.lane) == 0) { + return bitClk / info->mipi.lane; + } + return bitClk / info->mipi.lane + 1; +} + +static int32_t MipiDsiInit(struct PanelInfo *info) +{ + int32_t ret; + struct DevHandle *mipiHandle = NULL; + struct MipiCfg cfg; + + mipiHandle = MipiDsiOpen(0); + if (mipiHandle == NULL) { + HDF_LOGE("%s: MipiDsiOpen failed", __func__); + return HDF_FAILURE; + } + cfg.lane = info->mipi.lane; + cfg.mode = info->mipi.mode; + cfg.format = info->mipi.format; + cfg.burstMode = info->mipi.burstMode; + cfg.timing.xPixels = info->width; + cfg.timing.hsaPixels = info->hsw; + cfg.timing.hbpPixels = info->hbp; + cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; + cfg.timing.vsaLines = info->vsw; + cfg.timing.vbpLines = info->vbp; + cfg.timing.vfpLines = info->vfp; + cfg.timing.ylines = info->height; + /* 0 : no care */ + cfg.timing.edpiCmdSize = 0; + cfg.pixelClk = CalcPixelClk(info); + cfg.phyDataRate = CalcDataRate(info); + /* config mipi device */ + ret = MipiDsiSetCfg(mipiHandle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiSetCfg failed", __func__); + } + MipiDsiClose(mipiHandle); + HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d", __func__, cfg.pixelClk, cfg.phyDataRate); + return ret; +} + +static int32_t PwmInit(struct PanelInfo *info) +{ + int32_t ret; + + /* pwm pin config */ + PwmPinMuxCfg(info->pwm.dev); + /* pwm config */ + struct DevHandle *pwmHandle = PwmOpen(info->pwm.dev); + if (pwmHandle == NULL) { + HDF_LOGE("%s: PwmOpen failed", __func__); + return HDF_FAILURE; + } + struct PwmConfig config; + (void)memset_s(&config, sizeof(struct PwmConfig), 0, sizeof(struct PwmConfig)); + config.duty = 1; + config.period = info->pwm.period; + config.status = 0; + ret = PwmSetConfig(pwmHandle, &config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: PwmSetConfig err, ret %d", __func__, ret); + PwmClose(pwmHandle); + return HDF_FAILURE; + } + PwmClose(pwmHandle); + return HDF_SUCCESS; +} + +static int32_t Hi35xxInit(uint32_t devId) +{ + int32_t ret; + struct PanelInfo *info = GetPanelInfo(devId); + if (info == NULL) { + HDF_LOGE("%s:GetPanelInfo failed", __func__); + return HDF_FAILURE; + } + if (info->blk.type == BLK_PWM) { + ret = PwmInit(info); + if (ret) { + HDF_LOGE("%s:PwmInit failed", __func__); + return HDF_FAILURE; + } + } + /* lcd pin mux config */ + LcdPinMuxCfg(info->intfType); + if (info->intfType == MIPI_DSI) { + /* mipi dsi init */ + ret = MipiDsiInit(info); + if (ret) { + HDF_LOGE("%s:MipiDsiInit failed", __func__); + return HDF_FAILURE; + } + } + struct PanelData *panelData = GetPanelData(devId); + if (panelData == NULL) { + HDF_LOGE("%s: panel data is null", __func__); + return HDF_FAILURE; + } + if (panelData->init != NULL) { + /* panel driver init */ + ret = panelData->init(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: panelData->init failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t GetLcdIntfType(enum LcdIntfType type, uint32_t *out) +{ + int32_t ret = HDF_SUCCESS; + + switch (type) { + case MIPI_DSI: + *out = INTF_MIPI; + break; + case LCD_6BIT: + *out = INTF_LCD_6BIT; + break; + case LCD_8BIT: + *out = INTF_LCD_8BIT; + break; + case LCD_16BIT: + *out = INTF_LCD_16BIT; + break; + case LCD_18BIT: + *out = INTF_LCD_18BIT; + break; + case LCD_24BIT: + *out = INTF_LCD_24BIT; + break; + default: + HDF_LOGE("%s: not support intf: %d", __func__, type); + ret = HDF_FAILURE; + break; + } + return ret; +} + +static int32_t Hi35xxGetDispInfo(uint32_t devId, struct DispInfo *info) +{ + struct PanelInfo *panelInfo = GetPanelInfo(devId); + if (panelInfo == NULL) { + HDF_LOGE("%s:GetPanelInfo failed", __func__); + return HDF_FAILURE; + } + if (info == NULL) { + HDF_LOGE("%s:info is null", __func__); + return HDF_FAILURE; + } + info->width = panelInfo->width; + info->height = panelInfo->height; + info->hbp = panelInfo->hbp; + info->hfp = panelInfo->hfp; + info->hsw = panelInfo->hsw; + info->vbp = panelInfo->vbp; + info->vfp = panelInfo->vfp; + info->vsw = panelInfo->vsw; + if (GetLcdIntfType(panelInfo->intfType, &info->intfType) != HDF_SUCCESS) { + HDF_LOGE("%s:GetLcdIntfType failed", __func__); + return HDF_FAILURE; + } + info->intfSync = panelInfo->intfSync; + info->frameRate = panelInfo->frameRate; + info->minLevel = panelInfo->blk.minLevel; + info->maxLevel = panelInfo->blk.maxLevel; + info->defLevel = panelInfo->blk.defLevel; + HDF_LOGI("info->width = %d, info->height = %d", info->width, info->height); + HDF_LOGI("info->hbp = %d, info->hfp = %d", info->hbp, info->hfp); + HDF_LOGI("info->frameRate = %d, info->intfSync = %d", info->frameRate, info->intfSync); + return HDF_SUCCESS; +} + +static int32_t Hi35xxOn(uint32_t devId) +{ + int32_t ret; + struct PanelData *panelData = NULL; + + panelData = GetPanelData(devId); + if (panelData == NULL) { + HDF_LOGE("%s: panel data is null", __func__); + return HDF_FAILURE; + } + if (panelData->on != NULL) { + /* panel driver on */ + ret = panelData->on(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: panelData->on failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t Hi35xxOff(uint32_t devId) +{ + int32_t ret; + struct PanelData *panelData = NULL; + + panelData = GetPanelData(devId); + if (panelData == NULL) { + HDF_LOGE("%s: panel data is null", __func__); + return HDF_FAILURE; + } + if (panelData->off != NULL) { + /* panel driver off */ + ret = panelData->off(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: panelData->off failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t Hi35xxSetBacklight(uint32_t devId, uint32_t level) +{ + int32_t ret; + struct PanelData *panelData = NULL; + + panelData = GetPanelData(devId); + if (panelData == NULL) { + HDF_LOGE("%s: panel data is null", __func__); + return HDF_FAILURE; + } + if (panelData->setBacklight != NULL) { + /* panel driver set backlight */ + ret = panelData->setBacklight(level); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: setBacklight failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +struct DispOperations g_hi35xxOps = { + .init = Hi35xxInit, + .on = Hi35xxOn, + .off = Hi35xxOff, + .setBacklight = Hi35xxSetBacklight, + .getDispInfo = Hi35xxGetDispInfo, +}; + +static int32_t Hi35xxEntryInit(struct HdfDeviceObject *object) +{ + if (object == NULL) { + HDF_LOGE("%s: param is null!", __func__); + return HDF_FAILURE; + } + return DispRegister(&g_hi35xxOps); +} + +struct HdfDriverEntry g_hi35xxDevEntry = { + .moduleVersion = 1, + .moduleName = "HI351XX_DISP", + .Init = Hi35xxEntryInit, +}; + +HDF_INIT(g_hi35xxDevEntry); diff --git a/model/display/driver/hi35xx_disp.h b/model/display/driver/hi35xx_disp.h new file mode 100644 index 00000000..4f5427e6 --- /dev/null +++ b/model/display/driver/hi35xx_disp.h @@ -0,0 +1,31 @@ +/* + * 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 HI35XX_DISP_H +#define HI35XX_DISP_H +#include "hdf_base.h" +#include "lcd_abs_if.h" + +/* output interface type */ +#define INTF_LCD_6BIT (0x01L << 9) +#define INTF_LCD_8BIT (0x01L << 10) +#define INTF_LCD_16BIT (0x01L << 11) +#define INTF_LCD_18BIT (0x01L << 12) +#define INTF_LCD_24BIT (0x01L << 13) +#define INTF_MIPI (0x01L << 14) + +#define IO_CFG1_BASE 0x111F0000 +#define IO_CFG2_BASE 0x112F0000 +#define IO_CFG_SIZE 0x10000 + +#define PWM_DEV0 0 +#define PWM_DEV1 1 + +struct PanelData *GetPanelData(int32_t index); +struct PanelInfo *GetPanelInfo(int32_t index); +#endif /* HI35XX_DISP_H */ diff --git a/model/display/driver/lcd_abs_if.c b/model/display/driver/lcd_abs_if.c new file mode 100644 index 00000000..d414c216 --- /dev/null +++ b/model/display/driver/lcd_abs_if.c @@ -0,0 +1,62 @@ +/* + * 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.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 PanelDataRegister(struct PanelData *data) +{ + int32_t i; + + if (data == NULL) { + HDF_LOGE("%s: panel data is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (numRegisteredPanel == PANEL_MAX) { + return HDF_FAILURE; + } + numRegisteredPanel++; + for (i = 0; i < PANEL_MAX; i++) { + if (g_panelData[i] == NULL) { + break; + } + } + if (i >= PANEL_MAX) { + return HDF_FAILURE; + } + g_panelData[i] = data; + HDF_LOGI("%s: panel data register success", __func__); + return HDF_SUCCESS; +} + +struct PanelData *GetPanelData(int32_t index) +{ + if ((index >= PANEL_MAX) || index < 0) { + return NULL; + } + return g_panelData[index]; +} + +struct PanelInfo *GetPanelInfo(int32_t index) +{ + if ((index >= PANEL_MAX) || index < 0) { + return NULL; + } + if (g_panelData[index] == NULL) { + return NULL; + } + return g_panelData[index]->info; +} + diff --git a/model/display/driver/lcd_abs_if.h b/model/display/driver/lcd_abs_if.h new file mode 100644 index 00000000..e35ce204 --- /dev/null +++ b/model/display/driver/lcd_abs_if.h @@ -0,0 +1,127 @@ +/* + * 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 LCD_ABS_IF_H +#define LCD_ABS_IF_H +#include "hdf_base.h" +#include "hdf_log.h" +#include "mipi_dsi_if.h" + +enum LcdIntfType { + MIPI_DSI, + LCD_6BIT, + LCD_8BIT, + LCD_16BIT, + LCD_18BIT, + LCD_24BIT, +}; + +enum BacklightType { + BLK_PWM, + BLK_MIPI, +}; + +/* output timming */ +enum IntfSync { + OUTPUT_USER = 0, /* User timing */ + OUTPUT_PAL, /* PAL standard */ + OUTPUT_NTSC, /* NTSC standard */ + OUTPUT_1080P24, /* 1920 x 1080 at 24 Hz. */ + OUTPUT_1080P25, /* 1920 x 1080 at 25 Hz. */ + OUTPUT_1080P30, /* 1920 x 1080 at 30 Hz. */ + OUTPUT_720P50, /* 1280 x 720 at 50 Hz. */ + OUTPUT_720P60, /* 1280 x 720 at 60 Hz. */ + OUTPUT_1080I50, /* 1920 x 1080 at 50 Hz, interlace. */ + OUTPUT_1080I60, /* 1920 x 1080 at 60 Hz, interlace. */ + OUTPUT_1080P50, /* 1920 x 1080 at 50 Hz. */ + OUTPUT_1080P60, /* 1920 x 1080 at 60 Hz. */ + OUTPUT_576P50, /* 720 x 576 at 50 Hz. */ + OUTPUT_480P60, /* 720 x 480 at 60 Hz. */ + OUTPUT_800X600_60, /* VESA 800 x 600 at 60 Hz (non-interlaced) */ + OUTPUT_1024X768_60, /* VESA 1024 x 768 at 60 Hz (non-interlaced) */ + OUTPUT_1280X1024_60, /* VESA 1280 x 1024 at 60 Hz (non-interlaced) */ + OUTPUT_1366X768_60, /* VESA 1366 x 768 at 60 Hz (non-interlaced) */ + OUTPUT_1440X900_60, /* VESA 1440 x 900 at 60 Hz (non-interlaced) CVT Compliant */ + OUTPUT_1280X800_60, /* 1280*800@60Hz VGA@60Hz */ + OUTPUT_1600X1200_60, /* VESA 1600 x 1200 at 60 Hz (non-interlaced) */ + OUTPUT_1680X1050_60, /* VESA 1680 x 1050 at 60 Hz (non-interlaced) */ + OUTPUT_1920X1200_60, /* VESA 1920 x 1600 at 60 Hz (non-interlaced) CVT (Reduced Blanking) */ + OUTPUT_640X480_60, /* VESA 640 x 480 at 60 Hz (non-interlaced) CVT */ + OUTPUT_960H_PAL, /* ITU-R BT.1302 960 x 576 at 50 Hz (interlaced) */ + OUTPUT_960H_NTSC, /* ITU-R BT.1302 960 x 480 at 60 Hz (interlaced) */ + OUTPUT_1920X2160_30, /* 1920x2160_30 */ + OUTPUT_2560X1440_30, /* 2560x1440_30 */ + OUTPUT_2560X1440_60, /* 2560x1440_60 */ + OUTPUT_2560X1600_60, /* 2560x1600_60 */ + OUTPUT_3840X2160_24, /* 3840x2160_24 */ + OUTPUT_3840X2160_25, /* 3840x2160_25 */ + OUTPUT_3840X2160_30, /* 3840x2160_30 */ + OUTPUT_3840X2160_50, /* 3840x2160_50 */ + OUTPUT_3840X2160_60, /* 3840x2160_60 */ + OUTPUT_4096X2160_24, /* 4096x2160_24 */ + OUTPUT_4096X2160_25, /* 4096x2160_25 */ + OUTPUT_4096X2160_30, /* 4096x2160_30 */ + OUTPUT_4096X2160_50, /* 4096x2160_50 */ + OUTPUT_4096X2160_60, /* 4096x2160_60 */ + OUTPUT_320X240_60, /* For ota5182 at 60 Hz (8bit) */ + OUTPUT_320X240_50, /* For ili9342 at 50 Hz (6bit) */ + OUTPUT_240X320_50, /* Hi3559AV100: For ili9341 at 50 Hz (6bit) */ + OUTPUT_240X320_60, /* For ili9341 at 60 Hz (16bit) */ + OUTPUT_800X600_50, /* For LCD at 50 Hz (24bit) */ + OUTPUT_720X1280_60, /* For MIPI DSI Tx 720 x1280 at 60 Hz */ + OUTPUT_1080X1920_60, /* For MIPI DSI Tx 1080x1920 at 60 Hz */ + OUTPUT_7680X4320_30, /* For HDMI2.1 at 30 Hz */ +}; + +struct MipiDsiDesc { + enum DsiLane lane; + enum DsiMode mode; /* output mode: DSI_VIDEO/DSI_CMD */ + enum DsiBurstMode burstMode; + enum DsiOutFormat format; +}; + +struct BlkDesc { + uint32_t type; + uint32_t minLevel; + uint32_t maxLevel; + uint32_t defLevel; +}; + +struct PwmCfg { + uint32_t dev; + uint32_t period; +}; + +struct PanelInfo { + uint32_t width; + uint32_t height; + uint32_t hbp; + uint32_t hfp; + uint32_t hsw; + uint32_t vbp; + uint32_t vfp; + uint32_t vsw; + uint32_t frameRate; + enum LcdIntfType intfType; + enum IntfSync intfSync; + struct MipiDsiDesc mipi; + struct BlkDesc blk; + struct PwmCfg pwm; +}; + +struct PanelData { + struct PanelInfo *info; + int32_t (*init)(void); + int32_t (*on)(void); + int32_t (*off)(void); + int32_t (*setBacklight)(uint32_t level); +}; + +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 new file mode 100644 index 00000000..89a66d49 --- /dev/null +++ b/model/display/driver/lcdkit/lcdkit_parse_config.c @@ -0,0 +1,276 @@ +/* + * 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 "lite_lcdkit.h" +#include "hdf_log.h" + +#define PARSE_PANEL_SYMBOL(node, ops, symbol, out) do { \ + if ((ops)->GetUint32((node), (symbol), (out), 0)) { \ + HDF_LOGE("%s: get symbol:%s failed", __func__, (symbol)); \ + return HDF_FAILURE; \ + } \ +} while (0) + +static int32_t GetDsiCmdCount(uint8_t *array, int32_t len, uint32_t *count) +{ + int32_t cnt = 0; + uint8_t dlen; + + while (len > 0) { + dlen = array[DATA_LEN]; + array = array + DSI_CMD_HEAD + dlen; + len = len - (dlen + DSI_CMD_HEAD); + cnt++; + } + if (len != 0) { + HDF_LOGE("%s: dsi cmd count error", __func__); + return HDF_FAILURE; + } + *count = cnt; + return HDF_SUCCESS; +} + +static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, int32_t len) +{ + struct DsiCmdDesc *dsiCmd = (struct DsiCmdDesc *)OsalMemCalloc(count * sizeof(struct DsiCmdDesc)); + if (dsiCmd == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + int32_t ret; + cmd->count = count; + cmd->dsiCmd = dsiCmd; + uint8_t *tmpArray = array; + struct DsiCmdDesc *tmpCmd = dsiCmd; + while (count > 0 && len > 0) { + tmpCmd->dataType = tmpArray[DATA_TYPE]; + tmpCmd->delay = tmpArray[CMD_DELAY]; + tmpCmd->dataLen = tmpArray[DATA_LEN]; + tmpCmd->payload = (uint8_t *)OsalMemCalloc(tmpCmd->dataLen * sizeof(uint8_t)); + if (tmpCmd->payload == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + OsalMemFree(array); + OsalMemFree(dsiCmd); + cmd->dsiCmd = NULL; + cmd->count = 0; + return HDF_FAILURE; + } + + ret = memcpy_s(tmpCmd->payload, tmpCmd->dataLen, &tmpArray[DSI_CMD_HEAD], tmpCmd->dataLen); + if (ret != EOK) { + HDF_LOGE("%s: memcpy_s failed, ret %d", __func__, ret); + OsalMemFree(array); + OsalMemFree(dsiCmd); + cmd->dsiCmd = NULL; + cmd->count = 0; + return ret; + } + + tmpArray += DSI_CMD_HEAD + tmpCmd->dataLen; + tmpCmd++; + count--; + len -= DSI_CMD_HEAD + tmpCmd->dataLen; + } + OsalMemFree(array); + return HDF_SUCCESS; +} + +static int32_t ParseCmdConfig(const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps, + const char *name, struct PanelCmd *cmd) +{ + int32_t len = drsOps->GetElemNum(node, name); + uint8_t *array = (uint8_t *)OsalMemCalloc(len * sizeof(uint8_t)); + if (array == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint8Array(node, name, array, len, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: GetUint8Array failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + uint32_t count = 0; + if (GetDsiCmdCount(array, len, &count) != HDF_SUCCESS) { + HDF_LOGE("%s: GetDsiCmdCount failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + return ParseDsiCmd(cmd, count, array, len); +} + +static int32_t ParsePanelInfo(const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps, + struct PanelInfo *info) +{ + /* panel setting */ + PARSE_PANEL_SYMBOL(node, drsOps, "width", &info->width); + PARSE_PANEL_SYMBOL(node, drsOps, "height", &info->height); + PARSE_PANEL_SYMBOL(node, drsOps, "hbp", &info->hbp); + PARSE_PANEL_SYMBOL(node, drsOps, "hfp", &info->hfp); + PARSE_PANEL_SYMBOL(node, drsOps, "hsw", &info->hsw); + PARSE_PANEL_SYMBOL(node, drsOps, "vbp", &info->vbp); + PARSE_PANEL_SYMBOL(node, drsOps, "vfp", &info->vfp); + PARSE_PANEL_SYMBOL(node, drsOps, "vsw", &info->vsw); + PARSE_PANEL_SYMBOL(node, drsOps, "frameRate", &info->frameRate); + PARSE_PANEL_SYMBOL(node, drsOps, "intfType", &info->intfType); + PARSE_PANEL_SYMBOL(node, drsOps, "intfSync", &info->intfSync); + /* mipi setting */ + PARSE_PANEL_SYMBOL(node, drsOps, "dsiLane", &info->mipi.lane); + PARSE_PANEL_SYMBOL(node, drsOps, "mode", &info->mipi.mode); + PARSE_PANEL_SYMBOL(node, drsOps, "burstMode", &info->mipi.burstMode); + PARSE_PANEL_SYMBOL(node, drsOps, "pixelFmt", &info->mipi.format); + /* backlight setting */ + PARSE_PANEL_SYMBOL(node, drsOps, "blkType", &info->blk.type); + PARSE_PANEL_SYMBOL(node, drsOps, "minLevel", &info->blk.minLevel); + PARSE_PANEL_SYMBOL(node, drsOps, "maxLevel", &info->blk.maxLevel); + PARSE_PANEL_SYMBOL(node, drsOps, "defLevel", &info->blk.defLevel); + /* pwm setting */ + if (info->blk.type == BLK_PWM) { + PARSE_PANEL_SYMBOL(node, drsOps, "pwmDev", &info->pwm.dev); + PARSE_PANEL_SYMBOL(node, drsOps, "pwmPeriod", &info->pwm.period); + } + return HDF_SUCCESS; +} + +static int32_t ParsePowerSetting(const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps, + struct PowerSetting *setting) +{ + int32_t count = drsOps->GetElemNum(node, "powerSetting"); + if ((count % POWER_SETTING_SIZE) != 0) { + HDF_LOGE("%s: count invalid", __func__); + return HDF_FAILURE; + } + uint32_t *array = (uint32_t *)OsalMemCalloc(count * sizeof(uint32_t)); + if (array == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint32Array(node, "powerSetting", array, count, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: GetUint32Array failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + uint32_t *tmp = array; + setting->power = (struct PowerDesc *)OsalMemCalloc((count / POWER_SETTING_SIZE) * sizeof(struct PowerDesc)); + if (setting->power == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + int32_t i; + for (i = 0; i < (count / POWER_SETTING_SIZE); i++) { + setting->power[i].type = tmp[i]; // get power type + setting->power[i].num = tmp[i + 1]; // 1-get power num + setting->power[i].vol = tmp[i + 2]; // 2-get power vol + tmp += POWER_SETTING_SIZE; // next power setting + } + setting->count = count / POWER_SETTING_SIZE; + OsalMemFree(array); + return HDF_SUCCESS; +} + +static int32_t ParsePowerSequeue(const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps, + const char *name, struct PowerSequeue *seq) +{ + int32_t count = drsOps->GetElemNum(node, name); + if ((count % POWER_SEQUEUE_SIZE) != 0) { + HDF_LOGE("%s: count invalid", __func__); + return HDF_FAILURE; + } + uint32_t *array = (uint32_t *)OsalMemCalloc(count * sizeof(uint32_t)); + if (array == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint32Array(node, name, array, count, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: GetUint32Array failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + uint32_t *tmp = array; + seq->pwCtrl = (struct PowerCtrl *)OsalMemCalloc((count / POWER_SEQUEUE_SIZE) * sizeof(struct PowerCtrl)); + if (seq->pwCtrl == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed", __func__); + OsalMemFree(array); + return HDF_FAILURE; + } + int32_t i; + for (i = 0; i < (count / POWER_SEQUEUE_SIZE); i++) { + seq->pwCtrl[i].num = tmp[i]; // get power num + seq->pwCtrl[i].opt = tmp[i + 1]; // 1-get power operate + seq->pwCtrl[i].delay = tmp[i + 2]; // 2-get power delay + tmp += POWER_SEQUEUE_SIZE; // next power setting + } + seq->count = count / POWER_SEQUEUE_SIZE; + OsalMemFree(array); + return HDF_SUCCESS; +} + +static int32_t ParsePanelConfig(const struct DeviceResourceNode *node, struct PanelConfig *cfg) +{ + struct DeviceResourceIface *drsOps = NULL; + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetUint32Array == NULL || + drsOps->GetElemNum == NULL || drsOps->GetUint8Array == NULL) { + HDF_LOGE("%s: invalid drs ops", __func__); + return HDF_FAILURE; + } + if (ParsePanelInfo(node, drsOps, &cfg->info)) { + HDF_LOGE("%s: ParsePanelInfo failed", __func__); + return HDF_FAILURE; + } + PARSE_PANEL_SYMBOL(node, drsOps, "dsiDev", &cfg->dsiDev); + if (ParsePowerSetting(node, drsOps, &cfg->setting)) { + HDF_LOGE("%s: Parse power setting failed", __func__); + return HDF_FAILURE; + } + if (ParseCmdConfig(node, drsOps, "panelOnCmd", &cfg->onCmd)) { + HDF_LOGE("%s: Parse panel on command failed", __func__); + return HDF_FAILURE; + } + if (ParseCmdConfig(node, drsOps, "panelOffCmd", &cfg->offCmd)) { + HDF_LOGE("%s: Parse panel off command failed", __func__); + return HDF_FAILURE; + } + if (ParsePowerSequeue(node, drsOps, "powerOnSeq", &cfg->onSeq)) { + HDF_LOGE("%s: Parse power on seq failed", __func__); + return HDF_FAILURE; + } + if (ParsePowerSequeue(node, drsOps, "powerOffSeq", &cfg->offSeq)) { + HDF_LOGE("%s: Parse power off seq failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t ParseLcdConfig(const struct DeviceResourceNode *node, struct PanelConfig *cfg) +{ + if (node == NULL || cfg == NULL) { + HDF_LOGE("%s: node or cfg is null", __func__); + return HDF_FAILURE; + } + struct DeviceResourceIface *drsOps = NULL; + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetChildNode == NULL || drsOps->GetString == NULL) { + HDF_LOGE("%s: invalid drs ops", __func__); + return HDF_FAILURE; + } + if (drsOps->GetString(node, "active_panel", &cfg->actPanel, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s: get active panel failed", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: actPanel = %s", __func__, cfg->actPanel); + const struct DeviceResourceNode *panelConfigNode = drsOps->GetChildNode(node, cfg->actPanel); + if (panelConfigNode == NULL) { + HDF_LOGE("%s: panelConfigNode is null", __func__); + return HDF_FAILURE; + } + return ParsePanelConfig(panelConfigNode, cfg); +} + diff --git a/model/display/driver/lcdkit/lite_lcdkit.c b/model/display/driver/lcdkit/lite_lcdkit.c new file mode 100644 index 00000000..219543a6 --- /dev/null +++ b/model/display/driver/lcdkit/lite_lcdkit.c @@ -0,0 +1,290 @@ +/* + * 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 "gpio_if.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "lcd_abs_if.h" +#include "mipi_dsi_if.h" +#include "osal.h" +#include "pwm_if.h" +#include "lite_lcdkit.h" + +static struct PanelConfig *GetPanelCfg(void) +{ + static struct PanelConfig panelCfg; + return &panelCfg; +} + +static int32_t PowerInit(void) +{ + int32_t ret; + int32_t count; + int32_t i; + struct PanelConfig *panelCfg = GetPanelCfg(); + + count = panelCfg->setting.count; + for (i = 0; i < count; i++) { + if (panelCfg->setting.power[i].type == GPIO_POWER) { + ret = GpioSetDir(panelCfg->setting.power[i].num, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:GpioSetDir failed", __func__); + return HDF_FAILURE; + } + } + } + return HDF_SUCCESS; +} + +static int32_t LcdkitInit(void) +{ + int32_t ret; + struct PanelConfig *panelCfg = GetPanelCfg(); + + if (panelCfg->info.intfType != MIPI_DSI) { + HDF_LOGE("%s:not support intf: %d", __func__, panelCfg->info.intfType); + return HDF_FAILURE; + } + ret = PowerInit(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:PowerInit failed", __func__); + return HDF_FAILURE; + } + + panelCfg->dsiHandle = MipiDsiOpen(panelCfg->dsiDev); + if (panelCfg->dsiHandle == NULL) { + HDF_LOGE("%s:MipiDsiOpen failed", __func__); + return HDF_FAILURE; + } + if (panelCfg->info.blk.type == BLK_PWM) { + panelCfg->pwmHandle = PwmOpen(panelCfg->info.pwm.dev); + if (panelCfg->pwmHandle == NULL) { + HDF_LOGE("%s: PwmOpen failed", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t MipiDsiOn(void) +{ + int32_t ret; + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t i; + + if (panelCfg->dsiHandle == NULL) { + HDF_LOGE("%s:dsiHandle is null", __func__); + return HDF_FAILURE; + } + /* send mipi init code */ + int32_t count = panelCfg->onCmd.count; + for (i = 0; i < count; i++) { + ret = MipiDsiTx(panelCfg->dsiHandle, &(panelCfg->onCmd.dsiCmd[i])); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiTx failed", __func__); + return ret; + } + } + /* set mipi to hs mode */ + MipiDsiSetHsMode(panelCfg->dsiHandle); + return HDF_SUCCESS; +} + +static int32_t MipiDsiOff(void) +{ + int32_t ret; + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t i; + + if (panelCfg->dsiHandle == NULL) { + HDF_LOGE("%s:dsiHandle is null", __func__); + return HDF_FAILURE; + } + /* send mipi panel off code */ + int32_t count = panelCfg->offCmd.count; + for (i = 0; i < count; i++) { + ret = MipiDsiTx(panelCfg->dsiHandle, &(panelCfg->offCmd.dsiCmd[i])); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiTx failed", __func__); + return ret; + } + } + /* set mipi to lp mode */ + MipiDsiSetLpMode(panelCfg->dsiHandle); + return HDF_SUCCESS; +} + +static int32_t PowerOn(void) +{ + int32_t ret; + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t i; + + for (i = 0; i < panelCfg->onSeq.count; i++) { + if (panelCfg->onSeq.pwCtrl[i].type == GPIO_POWER) { + ret = GpioWrite(panelCfg->onSeq.pwCtrl[i].num, panelCfg->onSeq.pwCtrl[i].opt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:GpioWrite failed", __func__); + return HDF_FAILURE; + } + OsalMSleep(panelCfg->onSeq.pwCtrl[i].delay); + } + } + return HDF_SUCCESS; +} + +static int32_t PowerOff(void) +{ + int32_t ret; + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t i; + + for (i = 0; i < panelCfg->offSeq.count; i++) { + if (panelCfg->offSeq.pwCtrl[i].type == GPIO_POWER) { + ret = GpioWrite(panelCfg->offSeq.pwCtrl[i].num, panelCfg->offSeq.pwCtrl[i].opt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:GpioWrite failed", __func__); + return HDF_FAILURE; + } + OsalMSleep(panelCfg->offSeq.pwCtrl[i].delay); + } + } + return HDF_SUCCESS; +} + +static int32_t LcdkitOn(void) +{ + int32_t ret; + + ret = PowerOn(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiPowerOn failed", __func__); + return HDF_FAILURE; + } + ret = MipiDsiOn(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiOn failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t LcdkitOff(void) +{ + int32_t ret; + + ret = MipiDsiOff(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiOff failed", __func__); + return HDF_FAILURE; + } + ret = PowerOff(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:PanelPowerOff failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t SetBacklightByPwm(uint32_t level) +{ + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t ret; + uint32_t duty; + + if (panelCfg->pwmHandle == NULL) { + HDF_LOGE("%s:pwmHandle is null", __func__); + return HDF_FAILURE; + } + duty = (level * panelCfg->info.pwm.period) / panelCfg->info.blk.maxLevel; + ret = PwmSetDutyCycle(panelCfg->pwmHandle, duty); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: PwmSetDutyCycle failed", __func__); + return HDF_FAILURE; + } + static uint32_t lastLevel = 0; + if (level != 0 && lastLevel == 0) { + ret = PwmEnable(panelCfg->pwmHandle); + } else if (level == 0 && lastLevel != 0) { + ret = PwmDisable(panelCfg->pwmHandle); + } + lastLevel = level; + return ret; +} + +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 }; + + if (panelCfg->dsiHandle == NULL) { + HDF_LOGE("%s: dsiHandle is null", __func__); + return HDF_FAILURE; + } + payLoad[1] = level; + ret = MipiDsiTx(panelCfg->dsiHandle, &bklCmd); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: MipiDsiTx failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t LcdkitSetBkl(uint32_t level) +{ + struct PanelConfig *panelCfg = GetPanelCfg(); + int32_t ret = HDF_SUCCESS; + if (panelCfg->info.blk.type == BLK_PWM) { + ret = SetBacklightByPwm(level); + } else if (panelCfg->info.blk.type == BLK_MIPI) { + ret = SetBacklightByMipi(level); + } else { + HDF_LOGE("%s: not support backlight type:%d", __func__, panelCfg->info.blk.type); + return HDF_FAILURE; + } + return ret; +} + +static struct PanelData g_panelData = { + .init = LcdkitInit, + .on = LcdkitOn, + .off = LcdkitOff, + .setBacklight = LcdkitSetBkl, +}; + +static int32_t LcdkitEntryInit(struct HdfDeviceObject *object) +{ + struct PanelConfig *panelCfg = GetPanelCfg(); + + if (object == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + if (ParseLcdConfig(object->property, panelCfg)) { + HDF_LOGE("%s: ParseLcdConfig failed", __func__); + return HDF_FAILURE; + } + g_panelData.info = &panelCfg->info; + if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { + HDF_LOGE("%s: PanelDataRegister failed", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: exit succ", __func__); + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_lcdkitDevEntry = { + .moduleVersion = 1, + .moduleName = "LITE_LCDKIT", + .Init = LcdkitEntryInit, +}; + +HDF_INIT(g_lcdkitDevEntry); diff --git a/model/display/driver/lcdkit/lite_lcdkit.h b/model/display/driver/lcdkit/lite_lcdkit.h new file mode 100644 index 00000000..b8e8f36b --- /dev/null +++ b/model/display/driver/lcdkit/lite_lcdkit.h @@ -0,0 +1,75 @@ +/* + * 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 LITE_LCDKIT_H +#define LITE_LCDKIT_H +#include "hdf_base.h" +#include "device_resource_if.h" +#include "lcd_abs_if.h" +#include "osal_mem.h" +#ifdef HDF_LOG_TAG +#undef HDF_LOG_TAG +#endif +#define HDF_LOG_TAG HDF_DISP + +#define DSI_CMD_HEAD 3 +#define DATA_LEN 2 +#define CMD_DELAY 1 +#define DATA_TYPE 0 +#define POWER_SETTING_SIZE 3 +#define POWER_SEQUEUE_SIZE 4 +#define MAX_PANEL_CFG 50 + +enum PowerType { + GPIO_POWER, + REGULATOR_POWER, +}; + +struct PanelCmd { + struct DsiCmdDesc *dsiCmd; + uint32_t count; +}; + +struct PowerDesc { + uint32_t type; + uint32_t num; + uint32_t vol; +}; + +struct PowerCtrl { + uint32_t type; + uint32_t num; + uint32_t opt; + uint32_t delay; +}; + +struct PowerSequeue { + struct PowerCtrl *pwCtrl; + uint32_t count; +}; + +struct PowerSetting { + struct PowerDesc *power; + uint32_t count; +}; + +struct PanelConfig { + const char *actPanel; + uint32_t dsiDev; + DevHandle pwmHandle; + DevHandle dsiHandle; + struct PanelInfo info; + struct PanelCmd onCmd; + struct PanelCmd offCmd; + struct PowerSetting setting; + struct PowerSequeue onSeq; + struct PowerSequeue offSeq; +}; + +int32_t ParseLcdConfig(const struct DeviceResourceNode *node, struct PanelConfig *cfg); +#endif /* LITE_LCDKIT_H */ diff --git a/model/display/driver/panel/mipi_icn9700.c b/model/display/driver/panel/mipi_icn9700.c new file mode 100644 index 00000000..d63f207f --- /dev/null +++ b/model/display/driver/panel/mipi_icn9700.c @@ -0,0 +1,301 @@ +/* + * 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 "gpio_if.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "lcd_abs_if.h" +#include "mipi_dsi_if.h" +#include "osal.h" +#include "pwm_if.h" + +#define RESET_GPIO 5 +#define MIPI_DSI0 0 +#define BLK_PWM1 1 +#define PWM_MAX_PERIOD 100000 +/* backlight setting */ +#define MIN_LEVEL 0 +#define MAX_LEVEL 255 +#define DEFAULT_LEVEL 100 + +#define WIDTH 480 +#define HEIGHT 960 +#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 FRAME_RATE 60 + +/* panel on commond 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 }; +static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A }; +static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C }; +static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C }; +static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; +static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; +static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; +static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; +static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; +static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; +static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; +static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; +static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; +static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; +static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; +static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; +static uint8_t g_payLoad18[] = { + 0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, + 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, + 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 +}; +static uint8_t g_payLoad19[] = { 0x11 }; +static uint8_t g_payLoad20[] = { 0x29 }; + +struct DsiCmdDesc g_OnCmd[] = { + { 0x29, 0, sizeof(g_payLoad0), g_payLoad0 }, + { 0x29, 0, sizeof(g_payLoad1), g_payLoad1 }, + { 0x29, 0, sizeof(g_payLoad2), g_payLoad2 }, + { 0x29, 0, sizeof(g_payLoad3), g_payLoad3 }, + { 0x29, 0, sizeof(g_payLoad4), g_payLoad4 }, + { 0x29, 0, sizeof(g_payLoad5), g_payLoad5 }, + { 0x29, 0, sizeof(g_payLoad6), g_payLoad6 }, + { 0x29, 0, sizeof(g_payLoad7), g_payLoad7 }, + { 0x29, 0, sizeof(g_payLoad8), g_payLoad8 }, + { 0x29, 0, sizeof(g_payLoad9), g_payLoad9 }, + { 0x23, 0, sizeof(g_payLoad10), g_payLoad10 }, + { 0x29, 0, sizeof(g_payLoad11), g_payLoad11 }, + { 0x29, 0, sizeof(g_payLoad12), g_payLoad12 }, + { 0x29, 0, sizeof(g_payLoad13), g_payLoad13 }, + { 0x29, 0, sizeof(g_payLoad14), g_payLoad14 }, + { 0x29, 0, sizeof(g_payLoad15), g_payLoad15 }, + { 0x29, 0, sizeof(g_payLoad16), g_payLoad16 }, + { 0x23, 0, sizeof(g_payLoad17), g_payLoad17 }, + { 0x29, 1, sizeof(g_payLoad18), g_payLoad18 }, + { 0x05, 120, sizeof(g_payLoad19), g_payLoad19 }, + { 0x05, 120, sizeof(g_payLoad20), g_payLoad20 }, +}; + +/* panel off commond payload */ +static uint8_t g_offPayLoad0[] = { 0x28 }; +static uint8_t g_offPayLoad1[] = { 0x10 }; +struct DsiCmdDesc g_offCmd[] = { + { 0x05, 20, sizeof(g_offPayLoad0), g_offPayLoad0 }, + { 0x05, 120, sizeof(g_offPayLoad1), g_offPayLoad1 }, +}; + +static DevHandle g_mipiHandle = NULL; +static DevHandle g_pwmHandle = NULL; + +static int32_t LcdResetOn(void) +{ + int32_t ret; + + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir 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); + return HDF_FAILURE; + } + /* delay 20ms */ + OsalMSleep(20); + return HDF_SUCCESS; +} + +static int32_t LcdResetOff(void) +{ + int32_t ret; + + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir 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); + return HDF_FAILURE; + } + /* delay 20ms */ + OsalMSleep(20); + return HDF_SUCCESS; +} + +static int32_t PwmCfg(void) +{ + g_pwmHandle = PwmOpen(BLK_PWM1); + if (g_pwmHandle == NULL) { + HDF_LOGE("%s: PwmOpen failed", __func__); + return HDF_FAILURE; + } + /* pwm config */ + int32_t ret; + struct PwmConfig config; + ret = PwmGetConfig(g_pwmHandle, &config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: PwmGetConfig fail, ret %d", __func__, ret); + return HDF_FAILURE; + } + config.duty = 1; + config.period = PWM_MAX_PERIOD; + config.status = 1; + ret = PwmSetConfig(g_pwmHandle, &config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: PwmSetConfig fail, ret %d", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t Icn9700Init(void) +{ + g_mipiHandle = MipiDsiOpen(MIPI_DSI0); + if (g_mipiHandle == NULL) { + HDF_LOGE("%s: MipiDsiOpen failed", __func__); + return HDF_FAILURE; + } + if (PwmCfg() != HDF_SUCCESS) { + HDF_LOGE("%s: PwmCfg failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t Icn9700On(void) +{ + int32_t ret; + + /* lcd reset power on */ + ret = LcdResetOn(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: LcdResetOn failed", __func__); + return HDF_FAILURE; + } + if (g_mipiHandle == NULL) { + HDF_LOGE("%s: g_mipiHandle is null", __func__); + return HDF_FAILURE; + } + /* send mipi init code */ + int32_t count = sizeof(g_OnCmd) / sizeof(g_OnCmd[0]); + int32_t i; + for (i = 0; i < count; i++) { + ret = MipiDsiTx(g_mipiHandle, &(g_OnCmd[i])); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: MipiDsiTx failed", __func__); + return HDF_FAILURE; + } + } + /* set mipi to hs mode */ + MipiDsiSetHsMode(g_mipiHandle); + return HDF_SUCCESS; +} + +static int32_t Icn9700Off(void) +{ + int32_t ret; + + if (g_mipiHandle == NULL) { + HDF_LOGE("%s: g_mipiHandle is null", __func__); + return HDF_FAILURE; + } + /* send mipi init code */ + int32_t count = sizeof(g_offCmd) / sizeof(g_offCmd[0]); + int32_t i; + for (i = 0; i < count; i++) { + ret = MipiDsiTx(g_mipiHandle, &(g_offCmd[i])); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: MipiDsiTx failed", __func__); + return HDF_FAILURE; + } + } + /* set mipi to lp mode */ + MipiDsiSetLpMode(g_mipiHandle); + /* lcd reset power off */ + ret = LcdResetOff(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: LcdResetOff failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t Icn9700SetBacklight(uint32_t level) +{ + int32_t ret; + uint32_t duty; + duty = (level * PWM_MAX_PERIOD) / MAX_LEVEL; + ret = PwmSetDuty(g_pwmHandle, duty); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: PwmSetDutyCycle failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + static uint32_t lastLevel = 0; + if (level != 0 && lastLevel == 0) { + ret = PwmEnable(g_pwmHandle); + } else if (level == 0 && lastLevel != 0) { + ret = PwmDisable(g_pwmHandle); + } + lastLevel = level; + return ret; +} + +static struct PanelInfo g_panelInfo = { + .width = WIDTH, /* width */ + .height = HEIGHT, /* height */ + .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 */ + .frameRate = FRAME_RATE, /* frame rate */ + .intfType = MIPI_DSI, /* panel interface type */ + .intfSync = OUTPUT_USER, /* output timming type */ + /* mipi config info */ + .mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT }, + /* backlight config info */ + .blk = { BLK_PWM, MIN_LEVEL, MAX_LEVEL, DEFAULT_LEVEL }, + .pwm = { BLK_PWM1, PWM_MAX_PERIOD }, +}; + +static struct PanelData g_panelData = { + .info = &g_panelInfo, + .init = Icn9700Init, + .on = Icn9700On, + .off = Icn9700Off, + .setBacklight = Icn9700SetBacklight, +}; + +int32_t Icn9700EntryInit(struct HdfDeviceObject *object) +{ + if (object == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { + HDF_LOGE("%s: PanelDataRegister failed", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: exit succ", __func__); + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_icn9700DevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_ICN9700", + .Init = Icn9700EntryInit, +}; + +HDF_INIT(g_icn9700DevEntry); diff --git a/model/display/driver/panel/ssp_st7789.c b/model/display/driver/panel/ssp_st7789.c new file mode 100644 index 00000000..e19a625b --- /dev/null +++ b/model/display/driver/panel/ssp_st7789.c @@ -0,0 +1,283 @@ +/* + * 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 "gpio_if.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "lcd_abs_if.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "spi_if.h" +#include "ssp_st7789.h" + +#define WIDTH 240 +#define HEIGHT 320 +#define FRAME_RATE 50 + +static struct LcdCmd g_onCmd[] = { + { LCD_CMD, 0x11, 120 }, + { LCD_CMD, 0x36, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_CMD, 0xb2, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_DATA, 0x33, 0 }, + { LCD_DATA, 0x33, 0 }, + { LCD_CMD, 0xb7, 0 }, + { LCD_DATA, 0x35, 0 }, + { LCD_CMD, 0xb8, 0 }, + { LCD_DATA, 0x2f, 0 }, + { LCD_DATA, 0x2b, 0 }, + { LCD_DATA, 0x2f, 0 }, + { LCD_CMD, 0xbb, 0 }, + { LCD_DATA, 0x24, 0 }, + { LCD_CMD, 0xc0, 0 }, + { LCD_DATA, 0x2c, 0 }, + { LCD_CMD, 0xc3, 0 }, + { LCD_DATA, 0x20, 0 }, + { LCD_CMD, 0xc4, 0 }, + { LCD_DATA, 0x03, 0 }, + { LCD_CMD, 0xc6, 0 }, + { LCD_DATA, 0x11, 0 }, + { LCD_CMD, 0xd0, 0 }, + { LCD_DATA, 0xa4, 0 }, + { LCD_DATA, 0xa1, 0 }, + { LCD_CMD, 0xe8, 0 }, + { LCD_DATA, 0x03, 0 }, + { LCD_CMD, 0xe9, 0 }, + { LCD_DATA, 0x0d, 0 }, + { LCD_DATA, 0x12, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_CMD, 0x21, 0 }, + { LCD_CMD, 0xb0, 0 }, + { LCD_DATA, 0x11, 0 }, + { LCD_DATA, 0x04, 0 }, + { LCD_DATA, 0x00, 0 }, + { LCD_CMD, 0xb1, 0 }, + { LCD_DATA, 0xc0, 0 }, + { LCD_DATA, 0x02, 0 }, + { LCD_DATA, 0x14, 0 }, + { LCD_CMD, 0x3a, 0 }, + { LCD_DATA, 0x66, 0 }, + { LCD_CMD, 0x11, 0 }, + { LCD_CMD, 0x29, 0 }, + { LCD_CMD, 0x2c, 0 }, +}; + +static struct LcdCmd g_offCmd[] = { + { LCD_CMD, 0x28, 20 }, + { LCD_CMD, 0x10, 120 }, +}; + +static DevHandle g_spiHdl = NULL; + +static int32_t SpiWrite9Bits(DevHandle *spiHandle, uint8_t cmd, uint8_t data) +{ + int32_t ret; + uint16_t wbuff[1] = {0}; + + wbuff[0] = ((cmd << BITS_PER_BYTE) | data); + ret = SpiWrite(spiHandle, (uint8_t *)wbuff, SPI_MSG_SIZE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SpiWrite failed, ret:%d", ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static DevHandle *GetSpiHandle(void) +{ + int32_t ret; + DevHandle *spiHandle = NULL; + struct SpiDevInfo spiDevinfo; + struct SpiCfg cfg; + + spiDevinfo.busNum = 1; + spiDevinfo.csNum = 0; + spiHandle = SpiOpen(&spiDevinfo); + if (spiHandle == NULL) { + HDF_LOGE("SpiOpen failed"); + return NULL; + } + cfg.mode = SPI_CLK_PHASE | SPI_CLK_POLARITY; + cfg.bitsPerWord = BITS_PER_WORD; + cfg.maxSpeedHz = SPI_MAX_SPEED; + ret = SpiSetCfg(spiHandle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SpiSetCfg failed, ret:%d", ret); + SpiClose(spiHandle); + return NULL; + } + HDF_LOGI("Spi init success!"); + return spiHandle; +} + +static int32_t LcdResetOn(void) +{ + int32_t ret; + + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir 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); + return HDF_FAILURE; + } + ret = GpioWrite(RESET_GPIO, GPIO_VAL_LOW); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioWrite 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); + return HDF_FAILURE; + } + /* delay 120ms */ + OsalMSleep(120); + return HDF_SUCCESS; +} + +static int32_t LcdResetOff(void) +{ + int32_t ret; + + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir 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); + return HDF_FAILURE; + } + /* delay 20ms */ + OsalMSleep(20); + return HDF_SUCCESS; +} + +static int32_t St7789Init(void) +{ + g_spiHdl = GetSpiHandle(); + if (g_spiHdl == NULL) { + HDF_LOGE("GetSpiHandle failed"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t St7789On(void) +{ + int32_t ret; + int i; + + /* lcd reset power on */ + ret = LcdResetOn(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: LcdResetOn failed", __func__); + return HDF_FAILURE; + } + if (g_spiHdl == NULL) { + HDF_LOGE("%s: g_spiHdl is null", __func__); + return HDF_FAILURE; + } + int32_t count = sizeof(g_onCmd) / sizeof(g_onCmd[0]); + for (i = 0; i < count; i++) { + ret = SpiWrite9Bits(g_spiHdl, g_onCmd[i].cmd, g_onCmd[i].data); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SpiWrite failed"); + return HDF_FAILURE; + } + if (g_onCmd[i].delay > 0) { + OsalMSleep(g_onCmd[i].delay); + } + } + return HDF_SUCCESS; +} + +static int32_t St7789Off(void) +{ + int32_t ret; + int i; + + if (g_spiHdl == NULL) { + HDF_LOGE("%s: g_spiHdl is null", __func__); + return HDF_FAILURE; + } + /* send mipi init code */ + int32_t count = sizeof(g_offCmd) / sizeof(g_offCmd[0]); + + for (i = 0; i < count; i++) { + ret = SpiWrite9Bits(g_spiHdl, g_offCmd[i].cmd, g_offCmd[i].data); + if (ret != HDF_SUCCESS) { + HDF_LOGE("SpiWrite9Bits failed"); + return HDF_FAILURE; + } + if (g_offCmd[i].delay > 0) { + OsalMSleep(g_offCmd[i].delay); + } + } + /* lcd reset power off */ + ret = LcdResetOff(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: LcdResetOff failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t St7789SetBacklight(uint32_t level) +{ + (void)level; + return HDF_SUCCESS; +} + +static struct PanelInfo g_panelInfo = { + .width = WIDTH, /* width */ + .height = HEIGHT, /* height */ + .frameRate = FRAME_RATE, /* frame rate */ + .intfType = LCD_6BIT, /* panel interface type */ + .intfSync = OUTPUT_240X320_50, /* output timming type */ +}; + +static struct PanelData g_panelData = { + .info = &g_panelInfo, + .init = St7789Init, + .on = St7789On, + .off = St7789Off, + .setBacklight = St7789SetBacklight, +}; + +int32_t SspSt7789EntryInit(struct HdfDeviceObject *object) +{ + if (object == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { + HDF_LOGE("%s: PanelDataRegister failed", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: exit succ", __func__); + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_st7789DevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_ST7789", + .Init = SspSt7789EntryInit, +}; + +HDF_INIT(g_st7789DevEntry); diff --git a/model/display/driver/panel/ssp_st7789.h b/model/display/driver/panel/ssp_st7789.h new file mode 100644 index 00000000..22f2356e --- /dev/null +++ b/model/display/driver/panel/ssp_st7789.h @@ -0,0 +1,26 @@ +/* + * 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 SSP_ST7789_H +#define SSP_ST7789_H +#include "hdf_base.h" +#define RESET_GPIO 5 +#define LCD_CMD 0 +#define LCD_DATA 1 +#define SPI_MSG_SIZE 2 +#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; + uint8_t data; + uint8_t delay; +}; +#endif /* SSP_ST7789_H */ diff --git a/model/input/driver/event_hub.c b/model/input/driver/event_hub.c new file mode 100644 index 00000000..3c11bc4c --- /dev/null +++ b/model/input/driver/event_hub.c @@ -0,0 +1,62 @@ +/* + * 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_time.h" +#include "hdf_log.h" +#include "event_hub.h" + +#define SEC_TO_USEC 1000000 + +static void SendFramePackages(InputDevice *inputDev) +{ + struct HdfDeviceObject *hdfDev = inputDev->hdfDevObj; + if (hdfDev == NULL || inputDev->pkgBuf == NULL) { + HDF_LOGE("%s: hdf dev is null", __func__); + return; + } + HdfDeviceSendEvent(hdfDev, 0, inputDev->pkgBuf); +} + +void PushOnePackage(InputDevice *inputDev, uint32_t type, uint32_t code, int32_t value) +{ + OsalTimespec time; + EventPackage package = {0}; + package.type = type; + package.code = code; + package.value = value; + OsalGetTime(&time); + package.time = time.sec * SEC_TO_USEC + time.usec; + + if (!HdfSbufWriteBuffer(inputDev->pkgBuf, &package, sizeof(EventPackage))) { + HDF_LOGE("%s: sbuf write pkg failed, clear sbuf", __func__); + HdfSbufFlush(inputDev->pkgBuf); + inputDev->errFrameFlag = true; + } + inputDev->pkgCount++; + + if (inputDev->pkgCount >= inputDev->pkgNum) { + HDF_LOGE("%s: current pkgs num beyond the sbuf limit", __func__); + inputDev->errFrameFlag = true; + } + + if (type == EV_SYN && code == SYN_REPORT) { + if (!HdfSbufWriteBuffer(inputDev->pkgBuf, NULL, 0)) { + HDF_LOGE("%s: sbuf write null pkg failed, clear sbuf", __func__); + HdfSbufFlush(inputDev->pkgBuf); + inputDev->errFrameFlag = true; + } + + if (!inputDev->errFrameFlag) { + SendFramePackages(inputDev); + } + + inputDev->pkgCount = 0; + HdfSbufFlush(inputDev->pkgBuf); + inputDev->errFrameFlag = false; + } +} \ No newline at end of file diff --git a/model/input/driver/event_hub.h b/model/input/driver/event_hub.h new file mode 100644 index 00000000..97dec781 --- /dev/null +++ b/model/input/driver/event_hub.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 EVENT_HUB_H +#define EVENT_HUB_H + +#include "input-event-codes.h" +#include "hdf_input_device_manager.h" +#include "osal_time.h" + +#define input_report_abs ReportAbs +#define input_report_key ReportKey +#define input_report_rel ReportRel +#define input_sync ReportSync +#define input_mt_sync ReportMtSync + +typedef struct { + uint32_t type; + uint32_t code; + int32_t value; + uint64_t time; +} EventPackage; + +void PushOnePackage(InputDevice *inputDev, uint32_t type, uint32_t code, int32_t value); + +static inline void ReportAbs(InputDevice *inputDev, uint32_t code, int32_t value) +{ + PushOnePackage(inputDev, EV_ABS, code, value); +} + +static inline void ReportKey(InputDevice *inputDev, uint32_t code, int32_t value) +{ + PushOnePackage(inputDev, EV_KEY, code, !!value); +} + +static inline void ReportRel(InputDevice *inputDev, uint32_t code, int32_t value) +{ + PushOnePackage(inputDev, EV_REL, code, value); +} + +static inline void ReportSync(InputDevice *inputDev) +{ + PushOnePackage(inputDev, EV_SYN, SYN_REPORT, 0); +} + +static inline void ReportMtSync(InputDevice *inputDev) +{ + PushOnePackage(inputDev, EV_SYN, SYN_MT_REPORT, 0); +} + +#endif diff --git a/model/input/driver/hdf_hid.c b/model/input/driver/hdf_hid.c new file mode 100755 index 00000000..5cd3ee27 --- /dev/null +++ b/model/input/driver/hdf_hid.c @@ -0,0 +1,48 @@ +/* + * 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_input_device_manager.c b/model/input/driver/hdf_input_device_manager.c new file mode 100644 index 00000000..00bdbb28 --- /dev/null +++ b/model/input/driver/hdf_input_device_manager.c @@ -0,0 +1,489 @@ +/* + * 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 "osal_cdev.h" +#include "osal_mem.h" +#include "devsvc_manager_clnt.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "event_hub.h" +#include "hdf_input_device_manager.h" + +#define NODE_MODE 0660 +#define SERVICE_NAME_LEN 16 +#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 + +InputManager *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; + InputDevice *inputdev = (InputDevice *)filep->f_inode->i_private; + if (inputdev == NULL) { + return HDF_FAILURE; + } + + switch (inputdev->devType) { + case INDEV_TYPE_TOUCH: + ret = TouchIoctl(inputdev, cmd, arg); + break; + default: + ret = 0; + HDF_LOGE("%s: devType unknown, devType = %d", __func__, inputdev->devType); + break; + } + return ret; +} + +static int32_t InputDevOpen(struct file *filep) +{ + InputDevice *inputdev = (InputDevice *)filep->f_inode->i_private; + if (inputdev == NULL) { + HDF_LOGE("%s: filep is null", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t InputDevClose(struct file *filep) +{ + InputDevice *inputdev = (InputDevice *)filep->f_inode->i_private; + if (inputdev == NULL) { + HDF_LOGE("%s: inputdev is null", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +#ifndef CONFIG_DISABLE_POLL +static int32_t InputDevPoll(struct file *filep, poll_table *wait) +{ + uint32_t pollMask = 0; + InputDevice *inputdev = (InputDevice *)filep->f_inode->i_private; + switch (inputdev->devType) { + case INDEV_TYPE_TOUCH: + pollMask = TouchPoll(filep, inputdev, wait); + break; + default: + HDF_LOGE("%s: devType unknown, devType = %d", __func__, inputdev->devType); + break; + } + return pollMask; +} +#endif + +static const struct file_operations_vfs inputDevOps = { + .open = InputDevOpen, + .close = InputDevClose, + .ioctl = InputDevIoctl, +#ifndef CONFIG_DISABLE_POLL + .poll = InputDevPoll, +#endif +}; + +#endif + +static bool IsHidDevice(uint32_t devType) +{ + if (devType == INDEV_TYPE_MOUSE) { + return true; + } + return false; +} + +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); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed", __func__); + return NULL; + } + + hdfDev = HdfRegisterDevice(moduleName, svcName); + if (hdfDev == NULL) { + HDF_LOGE("%s: HdfRegisterDevice failed", __func__); + } + HDF_LOGI("%s: svcName is %s, devName = %s", __func__, svcName, inputDev->devName); + return hdfDev; +} + +static int32_t CreateDeviceNode(InputDevice *inputDev) +{ + if (IsHidDevice(inputDev->devType)) { + HDF_LOGI("%s: prepare to register hdf device", __func__); + inputDev->hdfDevObj = HidRegisterHdfDevice(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); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed", __func__); + return HDF_FAILURE; + } + inputDev->devNode = devNode; + ret = register_driver(inputDev->devNode, &inputDevOps, NODE_MODE, inputDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: register %s devnode failed, ret = %d", __func__, devNode, ret); + inputDev->devNode = NULL; + return ret; + } +#endif + + HDF_LOGI("%s: create node succ, devId is %d ", __func__, inputDev->devId); + return HDF_SUCCESS; +} + +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); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed", __func__); + return; + } + HDF_LOGI("%s: svcName is %s, devName = %s", __func__, svcName, inputDev->devName); + HdfUnregisterDevice(moduleName, svcName); + } + +#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); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: delete dev node failed, ret %d", __func__, ret); + } +#endif + HDF_LOGI("%s: delete node succ, devId is %d", __func__, inputDev->devId); +} + +static void AddInputDevice(InputDevice *inputDev) +{ + InputDevice *tmpDev = NULL; + if (g_inputManager->inputDevList == NULL) { + g_inputManager->inputDevList = inputDev; + (g_inputManager->inputDevList)->next = NULL; + } else { + tmpDev = g_inputManager->inputDevList; + while (tmpDev != NULL) { + if (tmpDev->next == NULL) { + tmpDev->next = inputDev; + inputDev->next = NULL; + break; + } + tmpDev = tmpDev->next; + } + } + g_inputManager->devCount++; +} + +static int32_t CheckInputDevice(InputDevice *inputDev) +{ + InputDevice *tmpDev = NULL; + if (g_inputManager->inputDevList == NULL) { + return HDF_SUCCESS; + } else { + tmpDev = g_inputManager->inputDevList; + while (tmpDev != NULL) { + if (tmpDev->devId == inputDev->devId) { + HDF_LOGE("%s: device%d registered", __func__, inputDev->devId); + return INPUT_DEV_EXIST; + } + tmpDev = tmpDev->next; + } + } + return INPUT_DEV_NOT_EXIST; +} + +static int32_t DeleteInputDevice(InputDevice *inputDev) +{ + if (g_inputManager->inputDevList == NULL) { + return HDF_FAILURE; + } else { + if ((g_inputManager->inputDevList)->devId == inputDev->devId) { + g_inputManager->inputDevList = g_inputManager->inputDevList->next; + goto EXIT; + } + + InputDevice *preNode = g_inputManager->inputDevList; + InputDevice *tmpDev = preNode->next; + while (tmpDev != NULL) { + if (tmpDev->devId == inputDev->devId) { + preNode->next = tmpDev->next; + goto EXIT; + } + preNode = tmpDev; + tmpDev = tmpDev->next; + } + HDF_LOGE("%s: device%d not exist", __func__, inputDev->devId); + return HDF_FAILURE; + } + +EXIT: + g_inputManager->devCount--; + 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_CROWN_BUF_PKG_NUM 20 +#define DEFAULT_ENCODER_BUF_PKG_NUM 20 + +static int32_t AllocPackageBuffer(InputDevice *inputDev) +{ + uint16_t pkgNum; + switch (inputDev->devType) { + case INDEV_TYPE_TOUCH: + pkgNum = DEFAULT_TOUCH_BUF_PKG_NUM; + break; + case INDEV_TYPE_KEY: + pkgNum = DEFAULT_KEY_BUF_PKG_NUM; + break; + case INDEV_TYPE_MOUSE: + pkgNum = DEFAULT_MOUSE_BUF_PKG_NUM; + break; + case INDEV_TYPE_CROWN: + pkgNum = DEFAULT_CROWN_BUF_PKG_NUM; + break; + case INDEV_TYPE_ENCODER: + pkgNum = DEFAULT_ENCODER_BUF_PKG_NUM; + break; + default: + HDF_LOGE("%s: devType not exist", __func__); + return HDF_FAILURE; + } + inputDev->pkgBuf = HdfSBufObtain(sizeof(EventPackage) * pkgNum); + if (inputDev->pkgBuf == NULL) { + HDF_LOGE("%s: malloc sbuf failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + inputDev->pkgNum = pkgNum; + return HDF_SUCCESS; +} + +static uint32_t AllocDeviceID(InputDevice *inputDev) +{ + InputDevice *tmpDev = g_inputManager->inputDevList; + uint32_t idList[MAX_INPUT_DEV_NUM + 1]; + uint32_t id; + (void)memset_s(idList, (MAX_INPUT_DEV_NUM + 1) * sizeof(uint32_t), 0, + (MAX_INPUT_DEV_NUM + 1) * sizeof(uint32_t)); + while (tmpDev != NULL) { + if (idList[tmpDev->devId] == 0) { + idList[tmpDev->devId] = FILLER_FLAG; + } + 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; + } + } + return HDF_FAILURE; +} + +int32_t RegisterInputDevice(InputDevice *inputDev) +{ + int32_t ret; + + HDF_LOGI("%s: enter", __func__); + if (inputDev == NULL) { + HDF_LOGE("%s: inputdev is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (g_inputManager == NULL || g_inputManager->initialized == false) { + HDF_LOGE("%s: dev manager is null or initialized failed", __func__); + return HDF_FAILURE; + } + + OsalMutexLock(&g_inputManager->mutex); + ret = AllocDeviceID(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT; + } + ret = CreateDeviceNode(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT1; + } + + ret = AllocPackageBuffer(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT1; + } + + AddInputDevice(inputDev); + OsalMutexUnlock(&g_inputManager->mutex); + HDF_LOGI("%s: exit succ, devCount is %d", __func__, g_inputManager->devCount); + return HDF_SUCCESS; + +EXIT1: + DeleteDeviceNode(inputDev); +EXIT: + OsalMutexUnlock(&g_inputManager->mutex); + return ret; +} + +int32_t UnregisterInputDevice(InputDevice *inputDev) +{ + int ret = HDF_FAILURE; + HDF_LOGI("%s: enter", __func__); + if (inputDev == NULL) { + HDF_LOGE("%s: inputdev is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (g_inputManager == NULL || g_inputManager->initialized == false) { + HDF_LOGE("%s: dev manager is null or initialized failed", __func__); + return HDF_FAILURE; + } + + OsalMutexLock(&g_inputManager->mutex); + if (CheckInputDevice(inputDev) == INPUT_DEV_NOT_EXIST) { + HDF_LOGE("%s: dev%d not exist", __func__, inputDev->devId); + goto EXIT; + } + + DeleteDeviceNode(inputDev); + OsalMemFree(inputDev->pkgBuf); + inputDev->pkgBuf = NULL; + ret = DeleteInputDevice(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT; + } + + OsalMutexUnlock(&g_inputManager->mutex); + HDF_LOGI("%s: exit succ, devCount is %d", __func__, g_inputManager->devCount); + return HDF_SUCCESS; + +EXIT: + OsalMutexUnlock(&g_inputManager->mutex); + return ret; +} + +static uint32_t GetDeviceCount(void) +{ + HDF_LOGI("%s: devCount = %d", __func__, g_inputManager->devCount); + return g_inputManager->devCount; +} + +static int32_t HdfInputManagerBind(struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%s: device is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + static IInputManagerService managerService = { + .getDeviceCount = GetDeviceCount, + }; + + device->service = &managerService.ioService; + return HDF_SUCCESS; +} + +static InputManager *InputManagerInstance(void) +{ + InputManager *manager = (InputManager *)OsalMemAlloc(sizeof(InputManager)); + if (manager == NULL) { + HDF_LOGE("%s: instance input manager failed", __func__); + return NULL; + } + (void)memset_s(manager, sizeof(InputManager), 0, sizeof(InputManager)); + return manager; +} + +static int32_t HdfInputManagerInit(struct HdfDeviceObject *device) +{ + HDF_LOGI("%s: enter", __func__); + int32_t ret; + if (device == NULL) { + HDF_LOGE("%s: device is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + +#ifndef __KERNEL__ + ret = mkdir("/dev/input", DEFAULT_DIR_MODE); + if ((ret < 0) && (errno != EEXIST)) { + HDF_LOGE("%s: mkdir fail, ret %d, error = %d\n", __func__, ret, errno); + return HDF_FAILURE; + } +#endif + + g_inputManager = InputManagerInstance(); + if (g_inputManager == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + if (OsalMutexInit(&g_inputManager->mutex) != HDF_SUCCESS) { + HDF_LOGE("%s: mutex init failed", __func__); + OsalMemFree(g_inputManager); + g_inputManager = NULL; + return HDF_FAILURE; + } + g_inputManager->initialized = true; + g_inputManager->hdfDevObj = device; + HDF_LOGI("%s: exit succ", __func__); + return HDF_SUCCESS; +} + +static void HdfInputManagerRelease(struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%s: device is null", __func__); + return; + } + if (g_inputManager != NULL) { + OsalMutexDestroy(&g_inputManager->mutex); + OsalMemFree(g_inputManager); + g_inputManager = NULL; + } +} + +struct HdfDriverEntry g_hdfInputEntry = { + .moduleVersion = 1, + .moduleName = "HDF_INPUT_MANAGER", + .Bind = HdfInputManagerBind, + .Init = HdfInputManagerInit, + .Release = HdfInputManagerRelease, +}; + +HDF_INIT(g_hdfInputEntry); diff --git a/model/input/driver/hdf_input_device_manager.h b/model/input/driver/hdf_input_device_manager.h new file mode 100644 index 00000000..93c54049 --- /dev/null +++ b/model/input/driver/hdf_input_device_manager.h @@ -0,0 +1,96 @@ +/* + * 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_INPUT_DEVICE_MANAGER_H +#define HDF_INPUT_DEVICE_MANAGER_H + +#include "input-event-codes.h" +#include "osal_mutex.h" +#include "hdf_types.h" +#include "hdf_device_desc.h" + +#ifdef HDF_LOG_TAG +#undef HDF_LOG_TAG +#endif +#define HDF_LOG_TAG HDF_INPUT_DRV +#define INPUT_DEV_PATH_LEN 64 +#define DEV_NAME_LEN 16 + +#define CHECK_RETURN_VALUE(ret) do { \ + if ((ret) != HDF_SUCCESS) { \ + return ret; \ + } \ +} while (0) + +typedef struct { + struct IDeviceIoService ioService; + uint32_t (*getDeviceCount)(void); +} IInputManagerService; + +typedef struct InputDeviceInfo { + struct HdfDeviceObject *hdfDevObj; + uint32_t devId; + uint32_t devType; + const char *devNode; + const char *devName; + uint16_t pkgNum; + uint16_t pkgCount; + bool errFrameFlag; + struct HdfSBuf *pkgBuf; + void *pvtData; + struct InputDeviceInfo *next; +} InputDevice; + +typedef struct { + struct HdfDeviceObject *hdfDevObj; + uint32_t devCount; + struct OsalMutex mutex; + bool initialized; + InputDevice *inputDevList; +} 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 */ +}; + +enum InputIOsvcCmdId { + GET_DEV_TYPE, + SET_PWR_STATUS, + GET_PWR_STATUS, + GET_CHIP_INFO, + GET_VENDOR_NAME, + GET_CHIP_NAME, + SET_GESTURE_MODE, + RUN_CAPAC_TEST, + RUN_EXTRA_CMD, +}; + +enum TouchIoctlCmd { + INPUT_IOCTL_GET_EVENT_DATA, + INPUT_IOCTL_SET_POWER_STATUS, + INPUT_IOCTL_GET_POWER_STATUS, + INPUT_IOCTL_GET_DEVICE_TYPE, + INPUT_IOCTL_GET_CHIP_INFO, + INPUT_IOCTL_GET_VENDOR_NAME, + INPUT_IOCTL_GET_CHIP_NAME, + INPUT_IOCTL_SET_GESTURE_MODE, + INPUT_IOCTL_RUN_CAPACITANCE_TEST, + INPUT_IOCTL_RUN_EXTRA_CMD, +}; + +int32_t RegisterInputDevice(InputDevice *device); +int32_t 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 new file mode 100644 index 00000000..8b07dacd --- /dev/null +++ b/model/input/driver/hdf_key.c @@ -0,0 +1,268 @@ +/* + * 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_device_desc.h" +#include "osal_mem.h" +#include "gpio_if.h" +#include "hdf_log.h" +#include "hdf_input_device_manager.h" +#include "event_hub.h" +#include "hdf_key.h" + +#define CHECK_PARSER_RET(ret, str) do { \ + if (ret != HDF_SUCCESS) { \ + HDF_LOGE("%s: %s failed, ret = %d!", __func__, str, ret); \ + return HDF_FAILURE; \ + } \ +} while (0) + +static int32_t IoctlReadKeyEvent(KeyDriver *driver, unsigned long arg) +{ + KeyEventData *eventData = (KeyEventData *)(uintptr_t)arg; + + if (eventData == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } +#ifndef __KERNEL__ + if (LOS_ArchCopyToUser(eventData, &driver->eventData, sizeof(driver->eventData)) != 0) { + HDF_LOGE("%s:copy chipInfo failed", __func__); + return HDF_FAILURE; + } +#endif + return HDF_SUCCESS; +} + +int32_t KeyIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg) +{ + int32_t ret; + KeyDriver *driver = (KeyDriver *)inputdev->pvtData; + switch (cmd) { + case INPUT_IOCTL_GET_EVENT_DATA: + ret = IoctlReadKeyEvent(driver, arg); + break; + default: + ret = 0; + HDF_LOGE("%s: cmd unknown, cmd = 0x%x", __func__, cmd); + break; + } + return ret; +} + +int32_t KeyIrqHandle(uint16_t intGpioNum, void *data) +{ + uint16_t gpioValue; + KeyDriver *driver = (KeyDriver *)data; + KeyEventData *event = &driver->eventData; + int32_t ret = GpioDisableIrq(intGpioNum); + + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: disable irq failed, ret %d", __func__, ret); + } + + ret = GpioRead(intGpioNum, &gpioValue); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: gpio read failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + uint64_t curTime = OsalGetSysTimeMs(); + driver->preStatus = gpioValue; + driver->timeStamp = curTime; + + if (gpioValue == GPIO_VAL_LOW) { + event->definedEvent = INPUT_KEY_DOWN; + input_report_key(driver->inputdev, KEY_POWER, 1); + } else if (gpioValue == GPIO_VAL_HIGH) { + event->definedEvent = INPUT_KEY_UP; + input_report_key(driver->inputdev, KEY_POWER, 0); + } + input_sync(driver->inputdev); + + driver->dataHandledFlag = true; + GpioEnableIrq(intGpioNum); + return HDF_SUCCESS; +} + +static int32_t SetupKeyIrq(KeyDriver *keyDrv) +{ + uint16_t intGpioNum = keyDrv->keyCfg->gpioNum; + uint16_t irqFlag = keyDrv->keyCfg->irqFlag; + int32_t ret = GpioSetDir(intGpioNum, GPIO_DIR_IN); + + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: gpio set dir failed, ret %d", __func__, ret); + return ret; + } + ret = GpioSetIrq(intGpioNum, irqFlag | GPIO_IRQ_USING_THREAD, KeyIrqHandle, keyDrv); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: register irq failed, ret %d", __func__, ret); + return ret; + } + ret = GpioEnableIrq(intGpioNum); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: enable irq failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t KeyInit(KeyDriver *keyDrv) +{ + int32_t ret = SetupKeyIrq(keyDrv); + CHECK_RETURN_VALUE(ret); + return HDF_SUCCESS; +} + +static KeyChipCfg *KeyConfigInstance(struct HdfDeviceObject *device) +{ + KeyChipCfg *keyCfg = (KeyChipCfg *)OsalMemAlloc(sizeof(KeyChipCfg)); + if (keyCfg == NULL) { + HDF_LOGE("%s: malloc key config failed", __func__); + return NULL; + } + (void)memset_s(keyCfg, sizeof(KeyChipCfg), 0, sizeof(KeyChipCfg)); + keyCfg->hdfKeyDev = device; + + if (ParseKeyConfig(device->property, keyCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: parse key config failed", __func__); + OsalMemFree(keyCfg); + keyCfg = NULL; + } + return keyCfg; +} + +static KeyDriver *KeyDriverInstance(KeyChipCfg *keyCfg) +{ + KeyDriver *keyDrv = (KeyDriver *)OsalMemAlloc(sizeof(KeyDriver)); + if (keyDrv == NULL) { + HDF_LOGE("%s: malloc key driver failed", __func__); + return NULL; + } + (void)memset_s(keyDrv, sizeof(KeyDriver), 0, sizeof(KeyDriver)); + + keyDrv->devType = keyCfg->devType; + keyDrv->keyCfg = keyCfg; + + return keyDrv; +} + +static InputDevice *InputDeviceInstance(KeyDriver *keyDrv) +{ + InputDevice *inputDev = (InputDevice *)OsalMemAlloc(sizeof(InputDevice)); + if (inputDev == NULL) { + HDF_LOGE("%s: malloc input device failed", __func__); + return NULL; + } + (void)memset_s(inputDev, sizeof(InputDevice), 0, sizeof(InputDevice)); + + inputDev->pvtData = (void *)keyDrv; + inputDev->devType = keyDrv->devType; + inputDev->devName = keyDrv->keyCfg->keyName; + inputDev->hdfDevObj = keyDrv->keyCfg->hdfKeyDev; + keyDrv->inputdev = inputDev; + + return inputDev; +} + +static int32_t RegisterKeyDevice(KeyChipCfg *keyCfg) +{ + KeyDriver *keyDrv = KeyDriverInstance(keyCfg); + if (keyDrv == NULL) { + HDF_LOGE("%s: instance key config failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + +#ifdef __KERNEL__ + init_waitqueue_head(&keyDrv->pollWait); +#else + __init_waitqueue_head(&keyDrv->pollWait); +#endif + + int32_t ret = KeyInit(keyDrv); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: key driver init failed, ret %d", __func__, ret); + goto EXIT; + } + + InputDevice *inputDev = InputDeviceInstance(keyDrv); + if (inputDev == NULL) { + HDF_LOGE("%s: instance input device failed", __func__); + goto EXIT; + } + + ret = RegisterInputDevice(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT1; + } + return HDF_SUCCESS; + +EXIT1: + OsalMemFree(inputDev->pkgBuf); + OsalMemFree(inputDev); +EXIT: + OsalMemFree(keyDrv); + HDF_LOGE("%s: exit failed", __func__); + return HDF_FAILURE; +} + +static int32_t HdfKeyDriverInit(struct HdfDeviceObject *device) +{ + HDF_LOGI("%s: enter", __func__); + if (device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + KeyChipCfg *keyCfg = KeyConfigInstance(device); + if (keyCfg == NULL) { + HDF_LOGE("%s: instance key config failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + int32_t ret = RegisterKeyDevice(keyCfg); + if (ret != HDF_SUCCESS) { + goto EXIT; + } + HDF_LOGI("%s: exit succ!", __func__); + return HDF_SUCCESS; + +EXIT: + OsalMemFree(keyCfg); + return HDF_FAILURE; +} + +static int32_t HdfKeyDispatch(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 HdfKeyDriverBind(struct HdfDeviceObject *device) +{ + if (device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + static struct IDeviceIoService keyService = { + .object.objectId = 1, + .Dispatch = HdfKeyDispatch, + }; + device->service = &keyService; + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_hdfKeyEntry = { + .moduleVersion = 1, + .moduleName = "HDF_KEY", + .Bind = HdfKeyDriverBind, + .Init = HdfKeyDriverInit, +}; + +HDF_INIT(g_hdfKeyEntry); diff --git a/model/input/driver/hdf_key.h b/model/input/driver/hdf_key.h new file mode 100644 index 00000000..200eb636 --- /dev/null +++ b/model/input/driver/hdf_key.h @@ -0,0 +1,37 @@ +/* + * 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_KEY_H +#define HDF_KEY_H + +#include +#include "osal_cdev.h" +#include "osal_time.h" +#include "input_config.h" + +typedef struct { + uint32_t definedEvent; +} KeyEventData; + +typedef struct KeyDriverInfo { + struct HdfDeviceObject *hdfKeyDev; + KeyEventData eventData; + uint8_t devType; + KeyChipCfg *keyCfg; + InputDevice *inputdev; + wait_queue_head_t pollWait; + bool dataHandledFlag; + uint16_t preStatus; + uint64_t timeStamp; +} KeyDriver; + +enum KeyStatusInfo { + INPUT_KEY_UP, + INPUT_KEY_DOWN, + INPUT_KEY_INVALID +}; +#endif \ No newline at end of file diff --git a/model/input/driver/hdf_touch.c b/model/input/driver/hdf_touch.c new file mode 100644 index 00000000..04daecad --- /dev/null +++ b/model/input/driver/hdf_touch.c @@ -0,0 +1,832 @@ +/* + * 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 "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 +#define MAX_TOUCH_DEVICE 5 +#define REGISTER_BYTE_SIZE 4 +#define TOUCH_CHIP_NAME_LEN 10 + +static TouchDriver *g_touchDriverList[MAX_TOUCH_DEVICE]; +static void InputFrameReport(TouchDriver *driver); + +#ifndef __KERNEL__ +static int32_t IoctlReadInputEvent(TouchDriver *driver, unsigned long arg) +{ + FrameData *frame = (FrameData *)(uintptr_t)arg; + if (frame == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + int32_t ret = LOS_ArchCopyToUser(frame, &driver->frameData, sizeof(driver->frameData)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:copy frame data failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t IoctlGetDeviceType(TouchDriver *driver, unsigned long arg) +{ + int32_t ret; + uint8_t *devType = (uint8_t *)(uintptr_t)arg; + if (devType == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = LOS_ArchCopyToUser(devType, &driver->devType, sizeof(driver->devType)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:copy devType failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + + HDF_LOGI("%s: devType is %u", __func__, driver->devType); + return HDF_SUCCESS; +} + +static int32_t IoctlGetChipName(TouchDriver *driver, unsigned long arg) +{ + char *chipInfo = (char *)(uintptr_t)arg; + if (chipInfo == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + int32_t ret = LOS_ArchCopyToUser(chipInfo, driver->device->chipName, TOUCH_CHIP_NAME_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:copy chipInfo failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + + HDF_LOGI("%s: chipName is %s", __func__, driver->device->chipName); + return HDF_SUCCESS; +} + +int32_t TouchIoctl(InputDevice *inputdev, int32_t cmd, unsigned long arg) +{ + int32_t ret; + ChipDevice *device = (ChipDevice *)inputdev->pvtData; + TouchDriver *driver = device->driver; + switch (cmd) { + case INPUT_IOCTL_GET_EVENT_DATA: + ret = IoctlReadInputEvent(driver, arg); + break; + case INPUT_IOCTL_GET_DEVICE_TYPE: + ret = IoctlGetDeviceType(driver, arg); + break; + case INPUT_IOCTL_GET_CHIP_INFO: + ret = IoctlGetChipName(driver, arg); + break; + default: + ret = 0; + HDF_LOGE("%s: cmd unknown, cmd = 0x%x", __func__, cmd); + break; + } + return ret; +} + +#ifndef CONFIG_DISABLE_POLL +uint32_t TouchPoll(FAR struct file *filep, InputDevice *inputDev, poll_table *wait) +{ + uint32_t pollMask = 0; + InputDevice *inputdev = (InputDevice *)filep->f_inode->i_private; + if (inputdev == NULL) { + HDF_LOGE("%s: inputdev is null", __func__); + return pollMask; + } + ChipDevice *device = (ChipDevice *)inputdev->pvtData; + + poll_wait(filep, &device->driver->pollWait, wait); + if (device->driver->dataHandledFlag == true) { + pollMask |= POLLIN; + } + device->driver->dataHandledFlag = false; + return pollMask; +} +#endif +#endif + +static int32_t SetGpioDirAndLevel(int gpio, int dir, int level) +{ + int32_t ret; + 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); + return HDF_FAILURE; + } + } + + 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); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +static int32_t SetVccPower(uint32_t status) +{ + (void)status; + return HDF_SUCCESS; +} + +static int32_t SetVciPower(uint32_t status) +{ + (void)status; + return HDF_SUCCESS; +} + +static int32_t SetGpio(uint16_t gpio, uint32_t dir, uint32_t status) +{ + int32_t ret = SetGpioDirAndLevel(gpio, dir, status); + CHECK_RETURN_VALUE(ret); + return HDF_SUCCESS; +} + +int32_t HandlePowerEvent(ChipDevice *chipDev, uint32_t *timing) +{ + int32_t ret = 0; + uint16_t gpio; + 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); + + switch (type) { + case TYPE_VCC: + ret = SetVccPower(status); + break; + case TYPE_VCI: + ret = SetVciPower(status); + break; + case TYPE_RESET: + gpio = chipDev->boardCfg->pins.rstGpio; + ret = SetGpio(gpio, dir, status); + break; + case TYPE_INT: + gpio = chipDev->boardCfg->pins.intGpio; + ret = SetGpio(gpio, dir, status); + break; + default: + HDF_LOGE("%s: unknown power type", __func__); + break; + } + if (delay > 0) { + OsalMSleep(delay); + } + return ret; +} + +static int32_t InputPinMuxCfg(uint32_t regAddr, int32_t regSize, uint32_t regValue) +{ + uint8_t *base = NULL; + if (regAddr == 0) { + HDF_LOGE("%s: regAddr invalid", __func__); + return HDF_FAILURE; + } + + base = OsalIoRemap(regAddr, regSize); + if (base == NULL) { + HDF_LOGE("%s: ioremap failed", __func__); + return HDF_FAILURE; + } + + OSAL_WRITEL(regValue, base); + OsalIoUnmap((void *)base); + return HDF_SUCCESS; +} + +static int32_t SetPowerOnTiming(ChipDevice *chipDev) +{ + int32_t i; + int32_t ret; + uint32_t rstPinAddr; + uint32_t rstPinValue; + uint32_t intPinAddr; + uint32_t intPinValue; + SeqArray pwrOnTiming = {0}; + TouchDriver *driver = chipDev->driver; + + rstPinAddr = driver->boardCfg->pins.rstPinReg[0]; + rstPinValue = driver->boardCfg->pins.rstPinReg[1]; + intPinAddr = driver->boardCfg->pins.intPinReg[0]; + intPinValue = driver->boardCfg->pins.intPinReg[1]; + + if (InputPinMuxCfg(rstPinAddr, REGISTER_BYTE_SIZE, rstPinValue) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + if (InputPinMuxCfg(intPinAddr, REGISTER_BYTE_SIZE, intPinValue) != HDF_SUCCESS) { + return HDF_FAILURE; + } + HDF_LOGD("%s: rstPinAddr = 0x%x, rstPinValue = 0x%x, intPinAddr = 0x%x, intPinValue = 0x%x", + __func__, rstPinAddr, rstPinValue, intPinAddr, intPinValue); + + ret = memcpy_s(&pwrOnTiming, sizeof(SeqArray), &chipDev->chipCfg->pwrSeq.pwrOn, sizeof(SeqArray)); + if (ret != EOK) { + HDF_LOGE("%s: memcpy_s failed", __func__); + return HDF_FAILURE; + } + + if ((pwrOnTiming.buf == NULL) || (pwrOnTiming.count == 0)) { + HDF_LOGE("%s: pwrOnTiming config is invalid", __func__); + return HDF_FAILURE; + } + + for (i = 0; i < pwrOnTiming.count / PWR_CELL_LEN; i++) { + ret = HandlePowerEvent(chipDev, pwrOnTiming.buf); + CHECK_RETURN_VALUE(ret); + pwrOnTiming.buf = pwrOnTiming.buf + PWR_CELL_LEN; + } + return HDF_SUCCESS; +} + +static void EventHandle(TouchDriver *driver, ChipDevice *chipDev) +{ + int32_t ret; + if ((chipDev->ops == NULL) || (chipDev->ops->DataHandle == NULL)) { + return; + } + + ret = chipDev->ops->DataHandle(chipDev); + if (ret == HDF_SUCCESS) { + InputFrameReport(driver); + } +} + +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); + } + + EventHandle(driver, driver->device); + + ret = GpioEnableIrq(intGpioNum); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: enable irq failed, ret %d", __func__, ret); + } + return HDF_SUCCESS; +} + +static void InputFrameReport(TouchDriver *driver) +{ + InputDevice *dev = driver->inputDev; + FrameData *frame = &driver->frameData; + int32_t i; + + OsalMutexLock(&driver->mutex); + for (i = 0; i < MAX_FINGERS_NUM; i++) { + if (frame->fingers[i].valid) { + 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); + } + } + + if ((frame->definedEvent == TOUCH_DOWN) || (frame->definedEvent == TOUCH_CONTACT)) { + input_report_key(dev, BTN_TOUCH, 1); // BTN_TOUCH DOWN + } else { + input_report_key(dev, BTN_TOUCH, 0); // BTN_TOUCH UP + } + OsalMutexUnlock(&driver->mutex); + input_sync(dev); +} + +static int32_t SetupChipIrq(ChipDevice *chipDev) +{ + int32_t ret; + uint16_t intGpioNum = chipDev->boardCfg->pins.intGpio; + uint16_t irqFlag = chipDev->chipCfg->bus.chipI2c.irqFlag; + + irqFlag |= GPIO_IRQ_USING_THREAD; + HDF_LOGD("%s: gpioNum = %d, irqFlag = %d", __func__, intGpioNum, irqFlag); + ret = GpioSetIrq(intGpioNum, irqFlag, IrqHandle, chipDev->driver); + if (ret != 0) { + HDF_LOGE("%s: register irq failed, ret %d", __func__, ret); + return ret; + } + + ret = GpioEnableIrq(intGpioNum); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: enable irq failed, ret %d", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t ChipDriverInit(ChipDevice *chipDev) +{ + int32_t ret = SetPowerOnTiming(chipDev); + CHECK_RETURN_VALUE(ret); + + if ((chipDev->ops == NULL) || (chipDev->ops->Detect == NULL)) { + return HDF_FAILURE; + } + + ret = chipDev->ops->Detect(chipDev); + CHECK_RETURN_VALUE(ret); + HDF_LOGI("%s: chipDetect succ, ret = %d ", __func__, ret); + + ret = SetupChipIrq(chipDev); + CHECK_RETURN_VALUE(ret); + return HDF_SUCCESS; +} + +static InputDevice *InputDeviceInstance(ChipDevice *chipDev) +{ + 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->hdfDevObj = chipDev->driver->hdfTouchDev; + inputDev->pvtData = (void *)chipDev; + inputDev->devType = chipDev->driver->boardCfg->attr.devType; + inputDev->devName = chipDev->driver->devName; + + HDF_LOGI("%s: inputDev->devName = %s", __func__, inputDev->devName); + return inputDev; +} + +static int32_t ChipMatchCheck(const ChipDevice *chipDev, const TouchDriver *driver) +{ + const struct DeviceResourceNode *boardNode = driver->boardCfg->boardNode; + const struct DeviceResourceNode *chipNode = chipDev->chipCfg->chipNode; + + 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) { + HDF_LOGE("%s: chip node or upper node is null ", __func__); + return HDF_FAILURE; + } + + if (boardNode->parent == chipNode->parent->parent) { + HDF_LOGI("%s: boardNode's father name = %s, chipNode's grandpa name = %s", __func__, + boardNode->parent->name, chipNode->parent->parent->name); + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +static int32_t DeviceBindDriver(ChipDevice *chipDev) +{ + TouchDriver *driver = NULL; + int32_t ret = HDF_FAILURE; + int32_t i; + for (i = 0; i < MAX_TOUCH_DEVICE; i++) { + if ((g_touchDriverList[i] != NULL) && g_touchDriverList[i]->initedFlag) { + ret = ChipMatchCheck(chipDev, g_touchDriverList[i]); + if (ret == HDF_SUCCESS) { + driver = g_touchDriverList[i]; + break; + } + } + } + + if (ret == HDF_FAILURE || driver == NULL) { + return HDF_FAILURE; + } + + driver->i2cClient.i2cCfg.addr = chipDev->chipCfg->bus.chipI2c.commAddr; + driver->device = chipDev; + chipDev->driver = driver; + chipDev->boardCfg = driver->boardCfg; + return HDF_SUCCESS; +} + +int32_t RegisterChipDevice(ChipDevice *chipDev) +{ + int32_t ret; + InputDevice *inputDev = NULL; + if ((chipDev == NULL) || (chipDev->chipCfg == NULL)) { + return HDF_ERR_INVALID_PARAM; + } + + ret = DeviceBindDriver(chipDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: chip device match driver failed", __func__); + return HDF_FAILURE; + } + + ret = ChipDriverInit(chipDev); + if (ret != HDF_SUCCESS) { + goto EXIT; + } + + inputDev = InputDeviceInstance(chipDev); + if (inputDev == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + ret = RegisterInputDevice(inputDev); + if (ret != HDF_SUCCESS) { + goto EXIT1; + } + chipDev->driver->inputDev = inputDev; + return HDF_SUCCESS; + +EXIT1: + OsalMemFree(inputDev); +EXIT: + chipDev->driver->device = NULL; + return HDF_FAILURE; +} + +static int32_t TouchGetDevType(TouchDriver *driver, struct HdfSBuf *reply) +{ + uint32_t devType = driver->devType; + HDF_LOGI("%s: enter, devType is %d", __func__, devType); + bool ret = HdfSbufWriteUint32(reply, devType); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t TouchSetPowerStatus(TouchDriver *driver, struct HdfSBuf *data) +{ + uint32_t pwrStatus; + bool ret = HdfSbufReadUint32(data, &pwrStatus); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + driver->pwrStatus = pwrStatus; + HDF_LOGI("%s: set power status is %d", __func__, pwrStatus); + return HDF_SUCCESS; +} + +static int32_t TouchGetPowerStatus(TouchDriver *driver, struct HdfSBuf *reply) +{ + uint32_t pwrStatus = driver->pwrStatus; + bool ret = HdfSbufWriteUint32(reply, pwrStatus); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: get power status is %d", __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) { + HDF_LOGE("%s: parameter invalid", __func__); + return HDF_ERR_INVALID_PARAM; + } + + switch (cmd) { + case GET_CHIP_NAME: + info = driver->device->chipName; + break; + case GET_VENDOR_NAME: + info = driver->device->vendorName; + break; + case GET_CHIP_INFO: + info = driver->device->chipCfg->chipInfo; + break; + default: + info = NULL; + break; + } + + bool ret = HdfSbufWriteString(reply, info); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: cmd is %s, the info is ", __func__, info); + return HDF_SUCCESS; +} + +static int32_t TouchSetGestureMode(TouchDriver *driver, struct HdfSBuf *data) +{ + uint32_t gestureMode; + bool ret = HdfSbufReadUint32(data, &gestureMode); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + driver->gestureMode = gestureMode; + HDF_LOGD("%s: set gesture mode is %d", __func__, gestureMode); + return HDF_SUCCESS; +} + +static int32_t TouchSelfCapacitance(TouchDriver *driver, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + CapacitanceTestInfo capacTest = {0}; + bool ret = HdfSbufReadUint32(data, &capacTest.testType); + if (!ret) { + HDF_LOGE("%s: HdfSbufWriteUint32 failed", __func__); + return HDF_FAILURE; + } + + if (strncpy_s(capacTest.testResult, SELF_TEST_RESULT_LEN, "SUCCESS", sizeof("SUCCESS")) != EOK) { + HDF_LOGE("%s: strncpy_s fail", __func__); + return HDF_FAILURE; + } + + ret = HdfSbufWriteString(reply, (const char *)capacTest.testResult); + if (!ret) { + 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); + return HDF_SUCCESS; +} + +static int32_t TouchRunExtraCmd(TouchDriver *driver, struct HdfSBuf *data) +{ + InputExtraCmd cmd = {0}; + cmd.cmdCode = HdfSbufReadString(data); + if (cmd.cmdCode == NULL) { + HDF_LOGE("%s: HdfSbufReadString failed", __func__); + return HDF_FAILURE; + } + + cmd.cmdValue = HdfSbufReadString(data); + if (cmd.cmdValue == NULL) { + HDF_LOGE("%s: HdfSbufReadString failed", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: extra cmd code is %s, cmd value is %s", __func__, cmd.cmdCode, cmd.cmdValue); + return HDF_SUCCESS; +} + +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) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + + touchDriver = (TouchDriver *)client->device->private; + if (touchDriver == NULL) { + HDF_LOGE("%s: touchDriver is null", __func__); + return HDF_FAILURE; + } + + switch (cmd) { + case GET_DEV_TYPE: + ret = TouchGetDevType(touchDriver, reply); + break; + case SET_PWR_STATUS: + ret = TouchSetPowerStatus(touchDriver, data); + break; + case GET_PWR_STATUS: + ret = TouchGetPowerStatus(touchDriver, reply); + break; + case GET_CHIP_NAME: + case GET_VENDOR_NAME: + case GET_CHIP_INFO: + ret = TouchGetDeviceInfo(touchDriver, cmd, reply); + break; + case SET_GESTURE_MODE: + ret = TouchSetGestureMode(touchDriver, data); + break; + case RUN_CAPAC_TEST: + ret = TouchSelfCapacitance(touchDriver, data, reply); + break; + case RUN_EXTRA_CMD: + ret = TouchRunExtraCmd(touchDriver, data); + break; + default: + ret = HDF_SUCCESS; + HDF_LOGE("%s: cmd unknown, cmd = 0x%x", __func__, cmd); + break; + } + return ret; +} + +static int32_t TouchSetupBus(TouchDriver *driver, TouchBoardCfg *config) +{ + uint8_t busType = config->bus.busType; + uint8_t busNum = config->bus.i2c.busNum; + if (busType == I2C_TYPE) { + uint32_t i2cClkAddr = config->bus.i2c.i2cClkReg[0]; + uint32_t i2cClkValue = config->bus.i2c.i2cClkReg[1]; + uint32_t i2cDataAddr = config->bus.i2c.i2cDataReg[0]; + uint32_t i2cDataValue = config->bus.i2c.i2cDataReg[1]; + + if (InputPinMuxCfg(i2cClkAddr, REGISTER_BYTE_SIZE, i2cClkValue) != HDF_SUCCESS) { + return HDF_FAILURE; + } + if (InputPinMuxCfg(i2cDataAddr, REGISTER_BYTE_SIZE, i2cDataValue) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + /* get i2c handle */ + driver->i2cClient.i2cHandle = I2cOpen(busNum); + if (driver->i2cClient.i2cHandle == NULL) { + HDF_LOGE("%s: open i2c%u failed", __func__, busNum); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + if (busType == SPI_TYPE) { + HDF_LOGI("%s: setup spi bus succ", __func__); + return HDF_SUCCESS; + } + + return HDF_FAILURE; +} + +static int32_t TouchInitData(TouchDriver *driver, TouchBoardCfg *config) +{ + driver->devType = config->attr.devType; + driver->devName = config->attr.devName; + driver->i2cClient.i2cCfg.busNum = config->bus.i2c.busNum; + driver->irqStopFlag = false; + +#ifdef __KERNEL__ + init_waitqueue_head(&driver->pollWait); +#else + __init_waitqueue_head(&driver->pollWait); +#endif + return HDF_SUCCESS; +} + +static int32_t TouchDriverInit(TouchDriver *driver, TouchBoardCfg *config) +{ + int32_t ret = TouchInitData(driver, config); + CHECK_RETURN_VALUE(ret); + + ret = TouchSetupBus(driver, config); + CHECK_RETURN_VALUE(ret); + + ret = OsalMutexInit(&driver->mutex); + CHECK_RETURN_VALUE(ret); + + driver->initedFlag = true; + return HDF_SUCCESS; +} + +static TouchBoardCfg *BoardConfigInstance(struct HdfDeviceObject *device) +{ + TouchBoardCfg *boardCfg = (TouchBoardCfg *)OsalMemAlloc(sizeof(TouchBoardCfg)); + if (boardCfg == NULL) { + HDF_LOGE("%s: instance board config failed", __func__); + return NULL; + } + (void)memset_s(boardCfg, sizeof(TouchBoardCfg), 0, sizeof(TouchBoardCfg)); + + if (ParseTouchBoardConfig(device->property, boardCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: parse board config failed", __func__); + OsalMemFree(boardCfg); + boardCfg = NULL; + } + return boardCfg; +} + +static TouchDriver *TouchDriverInstance(void) +{ + TouchDriver *touchDrv = (TouchDriver *)OsalMemAlloc(sizeof(TouchDriver)); + if (touchDrv == NULL) { + HDF_LOGE("%s: instance touch driver failed", __func__); + return NULL; + } + (void)memset_s(touchDrv, sizeof(TouchDriver), 0, sizeof(TouchDriver)); + return touchDrv; +} + +static void AddTouchDriver(TouchDriver *driver) +{ + int32_t i; + for (i = 0; i < MAX_TOUCH_DEVICE; i++) { + if (g_touchDriverList[i] == NULL) { + g_touchDriverList[i] = driver; + return; + } + } +} + +static int32_t HdfTouchDriverBind(struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + static struct IDeviceIoService touchService = { + .Dispatch = HdfTouchDispatch, + }; + + device->service = &touchService; + return HDF_SUCCESS; +} + +static int32_t HdfTouchDriverProbe(struct HdfDeviceObject *device) +{ + int32_t ret; + TouchBoardCfg *boardCfg = NULL; + TouchDriver *touchDriver = NULL; + + HDF_LOGI("%s: enter", __func__); + if (device == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + boardCfg = BoardConfigInstance(device); + if (boardCfg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + touchDriver = TouchDriverInstance(); + if (touchDriver == NULL) { + goto EXIT; + } + + ret = TouchDriverInit(touchDriver, boardCfg); + if (ret == HDF_SUCCESS) { + touchDriver->hdfTouchDev = device; + touchDriver->boardCfg = boardCfg; + AddTouchDriver(touchDriver); + device->private = (void *)touchDriver; + HDF_LOGI("%s: %s exit succ", __func__, boardCfg->attr.devName); + return HDF_SUCCESS; + } + +EXIT: + OsalMemFree(boardCfg); + if (touchDriver != NULL) { + touchDriver->boardCfg = NULL; + OsalMemFree(touchDriver); + } + return HDF_FAILURE; +} + +static void HdfTouchDriverRelease(struct HdfDeviceObject *device) +{ + TouchDriver *driver = NULL; + InputDevice *inputDev = NULL; + int32_t i; + + if (device == NULL || device->private == NULL) { + HDF_LOGE("%s: param is null", __func__); + return; + } + driver = device->private; + + for (i = 0; i < MAX_TOUCH_DEVICE; i++) { + if (g_touchDriverList[i] == driver) { + inputDev = driver->inputDev; + break; + } + } + + if (inputDev != NULL) { + (void)UnregisterInputDevice(inputDev); + OsalMemFree(inputDev); + driver->inputDev = NULL; + } + + OsalMutexDestroy(&driver->mutex); + OsalMemFree(driver); + if (i < MAX_TOUCH_DEVICE) { + g_touchDriverList[i] = NULL; + } +} + +struct HdfDriverEntry g_hdfTouchEntry = { + .moduleVersion = 1, + .moduleName = "HDF_TOUCH", + .Bind = HdfTouchDriverBind, + .Init = HdfTouchDriverProbe, + .Release = HdfTouchDriverRelease, +}; + +HDF_INIT(g_hdfTouchEntry); diff --git a/model/input/driver/hdf_touch.h b/model/input/driver/hdf_touch.h new file mode 100644 index 00000000..18f31a0f --- /dev/null +++ b/model/input/driver/hdf_touch.h @@ -0,0 +1,113 @@ +/* + * 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_TOUCH_H +#define HDF_TOUCH_H + +#include +#include "osal_cdev.h" +#include "osal_time.h" +#include "hdf_input_device_manager.h" +#include "input_config.h" +#include "input_i2c_ops.h" + +#define CHIP_CHECK_RETURN(ret) do { \ + if ((ret) != HDF_SUCCESS) { \ + return ret; \ + } \ +} while (0) + +#define MAX_FINGERS_NUM 10 +#define SELF_TEST_RESULT_LEN 20 + +#define PWR_TYPE_INDEX 0 +#define PWR_STATUS_INDEX 1 +#define PWR_DIR_INDEX 2 +#define PWR_DELAY_INDEX 3 +#define PWR_CELL_LEN 4 + +typedef enum { + TOUCH_DOWN, // 0 + TOUCH_UP, // 1 + TOUCH_CONTACT, // 2 +} EventType; + +typedef enum { + TYPE_UNKNOWN, // 0 + TYPE_VCC, // 1 + TYPE_VCI, // 2 + TYPE_RESET, // 3 + TYPE_INT, // 4 +} TimingType; + +typedef struct { + int32_t x; /* x coordinate */ + int32_t y; /* y coordinate */ + int32_t pressure; + int32_t trackId; /* touch ID */ + int32_t status; /* record every point's status */ + bool valid; +} FingerData; + +typedef struct { + FingerData fingers[MAX_FINGERS_NUM]; + int32_t realPointNum; + int32_t definedEvent; /* touch event: 0-down; 1-up; 2-contact */ + OsalTimespec time; +} FrameData; + +struct TouchChipDevice; +typedef struct TouchPlatformDriver { + struct HdfDeviceObject *hdfTouchDev; + InputDevice *inputDev; + struct TouchChipDevice *device; + FrameData frameData; + uint32_t devType; + const char *devName; + TouchBoardCfg *boardCfg; + InputI2cClient i2cClient; + wait_queue_head_t pollWait; + struct OsalMutex mutex; + uint32_t pwrStatus; + uint32_t gestureMode; + bool initedFlag; + bool irqStopFlag; + bool dataHandledFlag; +} TouchDriver; + +struct TouchChipOps; +typedef struct TouchChipDevice { + TouchDriver *driver; + const char *chipName; + const char *vendorName; + struct TouchChipOps *ops; + TouchChipCfg *chipCfg; + TouchBoardCfg *boardCfg; +} ChipDevice; + +struct TouchChipOps { + int32_t (*Init)(ChipDevice *device); + int32_t (*Detect)(ChipDevice *device); + int32_t (*Resume)(ChipDevice *device); + int32_t (*Suspend)(ChipDevice *device); + int32_t (*DataHandle)(ChipDevice *device); +}; + +typedef struct { + uint32_t testType; + char testResult[SELF_TEST_RESULT_LEN]; +} CapacitanceTestInfo; + +typedef struct { + const char *cmdCode; + const char *cmdValue; +} InputExtraCmd; + +int32_t RegisterChipDevice(ChipDevice *chipDev); + +#endif diff --git a/model/input/driver/input_bus_ops/input_i2c_ops.c b/model/input/driver/input_bus_ops/input_i2c_ops.c new file mode 100644 index 00000000..3fb6640d --- /dev/null +++ b/model/input/driver/input_bus_ops/input_i2c_ops.c @@ -0,0 +1,54 @@ +/* + * 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_log.h" +#include "input_i2c_ops.h" + +#define I2C_READ_MSG_NUM 2 +#define I2C_WRITE_MSG_NUM 1 + +int32_t InputI2cRead(const InputI2cClient *client, uint8_t *writeBuf, uint32_t writeLen, uint8_t *readBuf, + uint32_t readLen) +{ + struct I2cMsg msg[I2C_READ_MSG_NUM]; + (void)memset_s(msg, sizeof(msg), 0, sizeof(msg)); + + msg[0].addr = client->i2cCfg.addr; + msg[0].flags = 0; + msg[0].len = writeLen; + msg[0].buf = writeBuf; + + msg[1].addr = client->i2cCfg.addr; + msg[1].flags = I2C_FLAG_READ; + msg[1].len = readLen; + msg[1].buf = readBuf; + + if (I2cTransfer(client->i2cHandle, msg, I2C_READ_MSG_NUM) != I2C_READ_MSG_NUM) { + HDF_LOGE("%s: i2c read err", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t InputI2cWrite(const InputI2cClient *client, uint8_t *writeBuf, uint32_t len) +{ + struct I2cMsg msg[I2C_WRITE_MSG_NUM]; + (void)memset_s(msg, sizeof(msg), 0, sizeof(msg)); + + msg[0].addr = client->i2cCfg.addr; + msg[0].flags = 0; + msg[0].len = len; + msg[0].buf = writeBuf; + + if (I2cTransfer(client->i2cHandle, msg, I2C_WRITE_MSG_NUM) != I2C_WRITE_MSG_NUM) { + HDF_LOGE("%s: i2c write err", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} diff --git a/model/input/driver/input_bus_ops/input_i2c_ops.h b/model/input/driver/input_bus_ops/input_i2c_ops.h new file mode 100644 index 00000000..f1ca3cb9 --- /dev/null +++ b/model/input/driver/input_bus_ops/input_i2c_ops.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 INPUT_I2C_OPS_H +#define INPUT_I2C_OPS_H + +#include "hdf_types.h" +#include "i2c_if.h" + +typedef struct { + uint16_t busNum; + uint16_t addr; +} I2cConfig; + +typedef struct { + struct DevHandle *i2cHandle; + I2cConfig i2cCfg; +} InputI2cClient; + +int InputI2cRead(const InputI2cClient *client, uint8_t *writeBuf, uint32_t writeLen, uint8_t *readBuf, + uint32_t readLen); +int InputI2cWrite(const InputI2cClient *client, uint8_t *writeBuf, uint32_t len); + +#endif diff --git a/model/input/driver/input_config.h b/model/input/driver/input_config.h new file mode 100644 index 00000000..e44d400c --- /dev/null +++ b/model/input/driver/input_config.h @@ -0,0 +1,147 @@ +/* + * 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 INPUT_GONFIG_H +#define INPUT_GONFIG_H + +#include "hdf_types.h" +#include "device_resource_if.h" + +#define REG_CONFIG_LEN 2 + +typedef struct { + uint8_t devType; + const char *devName; + uint32_t resolutionX; + uint32_t resolutionY; +} BoardAttrCfg; + +typedef struct { + uint8_t busNum; + uint16_t clkGpio; + uint16_t dataGpio; + uint32_t i2cClkReg[REG_CONFIG_LEN]; + uint32_t i2cDataReg[REG_CONFIG_LEN]; +} BoardI2cCfg; + +typedef struct { + uint8_t busNum; + uint16_t clkGpio; + uint16_t csGpio; + uint16_t misoGpio; + uint16_t mosiGpio; + uint32_t spiClkReg[REG_CONFIG_LEN]; + uint32_t spiCsReg[REG_CONFIG_LEN]; + uint32_t spiMisoReg[REG_CONFIG_LEN]; + uint32_t spiMosiReg[REG_CONFIG_LEN]; +} BoardSpiCfg; + +typedef struct { + uint8_t busType; + union { + BoardI2cCfg i2c; + BoardSpiCfg spi; + }; +} BoardBusCfg; + +typedef struct { + uint16_t rstGpio; + uint16_t intGpio; + uint32_t rstPinReg[REG_CONFIG_LEN]; + uint32_t intPinReg[REG_CONFIG_LEN]; +} BoardPinCfg; + +typedef struct { + uint16_t pwrType; + uint16_t pwrNum; + uint32_t pwrValue; +} PwrDesc; + +typedef struct { + PwrDesc vcc; + PwrDesc vci; +} BoardPwrCfg; + +typedef struct { + uint8_t capacitanceTest; + uint8_t gestureMode; + uint8_t gloverMOde; + uint8_t coverMode; + uint8_t chargeMode; + uint8_t knuckleMode; +} BoardFeatureCfg; + +typedef struct { + const struct DeviceResourceNode *boardNode; + BoardAttrCfg attr; + BoardBusCfg bus; + BoardPinCfg pins; + BoardPwrCfg power; + BoardFeatureCfg feature; +} TouchBoardCfg; + +typedef struct { + uint32_t *buf; + uint32_t count; +} SeqArray; + +typedef struct { + SeqArray pwrOn; + SeqArray pwrOff; + SeqArray resume; + SeqArray suspend; +} ChipPwrSeq; + +typedef struct { + uint16_t irqFlag; + uint8_t wordMode; // 0, 1 , 2, 3 polar & phase + uint8_t commMode; // 2:DMA 1:polling 0:interrupt + uint32_t maxSpeed; + uint32_t csSetupTime; + uint32_t csHoldTime; + uint32_t csRecoveryTime; +} ChipSpiCfg; + +typedef struct { + uint16_t irqFlag; + uint32_t commAddr; // i2c device addr + uint32_t maxSpeed; +} ChipI2cCfg; + +typedef struct { + uint8_t busType; + union { + ChipI2cCfg chipI2c; + ChipSpiCfg chipSpi; + }; +} ChipBusCfg; + +typedef struct { + const struct DeviceResourceNode *chipNode; + const char *chipName; + const char *vendorName; + const char *chipInfo; + uint16_t chipVersion; + ChipBusCfg bus; + ChipPwrSeq pwrSeq; +} TouchChipCfg; + +typedef struct { + struct HdfDeviceObject *hdfKeyDev; + const char *keyName; + uint8_t devType; + uint16_t gpioNum; + uint16_t irqFlag; + uint32_t debounceTime; +} KeyChipCfg; + +int32_t ParseTouchBoardConfig(const struct DeviceResourceNode *node, TouchBoardCfg *config); +int32_t ParseTouchChipConfig(const struct DeviceResourceNode *node, TouchChipCfg *config); +int32_t ParseKeyConfig(const struct DeviceResourceNode *node, KeyChipCfg *config); + +#endif \ No newline at end of file diff --git a/model/input/driver/input_config_parser.c b/model/input/driver/input_config_parser.c new file mode 100644 index 00000000..d6fb06e8 --- /dev/null +++ b/model/input/driver/input_config_parser.c @@ -0,0 +1,303 @@ +/* + * 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 "osal_mem.h" +#include "hdf_log.h" +#include "input_config.h" + +#define CHECK_PARSER_RET(ret, str) do { \ + if ((ret) != HDF_SUCCESS) { \ + HDF_LOGE("%s: %s failed, ret = %d", __func__, str, ret); \ + return HDF_FAILURE; \ + } \ +} while (0) + +#define DEFAULT_I2C_SPEED 400 +#define DEFAULT_SPI_SPEED 10000 + +int32_t ParseKeyConfig(const struct DeviceResourceNode *node, KeyChipCfg *config) +{ + if (node == NULL || config == NULL) { + HDF_LOGE("%s: param is null", __func__); + return HDF_FAILURE; + } + + struct DeviceResourceIface *parser = NULL; + parser = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (parser == NULL) { + HDF_LOGE("%s: instance parser failed", __func__); + return HDF_FAILURE; + } + + const struct DeviceResourceNode *keyNode = node; + int32_t ret = parser->GetString(keyNode, "keyName", &config->keyName, NULL); + CHECK_PARSER_RET(ret, "GetString"); + ret = parser->GetUint8(keyNode, "inputType", &config->devType, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint16(keyNode, "gpioNum", &config->gpioNum, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + ret = parser->GetUint16(keyNode, "irqFlag", &config->irqFlag, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint32(keyNode, "debounceTime", &config->debounceTime, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + + return HDF_SUCCESS; +} + +static int32_t ParseAttr(struct DeviceResourceIface *parser, const struct DeviceResourceNode *attrNode, + BoardAttrCfg *attr) +{ + int32_t ret; + ret = parser->GetUint8(attrNode, "inputType", &attr->devType, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetString(attrNode, "devName", &attr->devName, NULL); + CHECK_PARSER_RET(ret, "GetString"); + ret = parser->GetUint32(attrNode, "solutionX", &attr->resolutionX, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + ret = parser->GetUint32(attrNode, "solutionY", &attr->resolutionY, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + return HDF_SUCCESS; +} + +static int32_t ParseBus(struct DeviceResourceIface *parser, const struct DeviceResourceNode *busNode, BoardBusCfg *bus) +{ + int32_t ret; + ret = parser->GetUint8(busNode, "busType", &bus->busType, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + + if (bus->busType == 0) { + ret = parser->GetUint8(busNode, "busNum", &bus->i2c.busNum, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint16(busNode, "clkGpio", &bus->i2c.clkGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(busNode, "dataGpio", &bus->i2c.dataGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint32Array(busNode, "i2cClkIomux", bus->i2c.i2cClkReg, REG_CONFIG_LEN, 0); + 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) { + ret = parser->GetUint8(busNode, "busNum", &bus->spi.busNum, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint16(busNode, "clkGpio", &bus->spi.clkGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(busNode, "csGpio", &bus->spi.csGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(busNode, "misoGpio", &bus->spi.misoGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(busNode, "mosiGpio", &bus->spi.mosiGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + } else { + HDF_LOGE("%s: unknown bus type", __func__); + } + return HDF_SUCCESS; +} + +static int32_t ParsePins(struct DeviceResourceIface *parser, const struct DeviceResourceNode *pinsNode, + BoardPinCfg *pins) +{ + int32_t ret; + ret = parser->GetUint16(pinsNode, "rstGpio", &pins->rstGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(pinsNode, "intGpio", &pins->intGpio, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint32Array(pinsNode, "rstRegCfg", pins->rstPinReg, REG_CONFIG_LEN, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + ret = parser->GetUint32Array(pinsNode, "intRegCfg", pins->intPinReg, REG_CONFIG_LEN, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + return HDF_SUCCESS; +} + +static int32_t ParsePower(struct DeviceResourceIface *parser, const struct DeviceResourceNode *powerNode, + BoardPwrCfg *power) +{ + int32_t ret; + ret = parser->GetUint16(powerNode, "vccType", &power->vcc.pwrType, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(powerNode, "vccNum", &power->vcc.pwrNum, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint32(powerNode, "vccValue", &power->vcc.pwrValue, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + ret = parser->GetUint16(powerNode, "vciType", &power->vci.pwrType, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint16(powerNode, "vciNum", &power->vci.pwrNum, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint32(powerNode, "vciValue", &power->vci.pwrValue, 0); + CHECK_PARSER_RET(ret, "GetUint32"); + return HDF_SUCCESS; +} + +static int32_t ParseFeature(struct DeviceResourceIface *parser, const struct DeviceResourceNode *featureNode, + BoardFeatureCfg *feature) +{ + int32_t ret; + ret = parser->GetUint8(featureNode, "capacitanceTest", &feature->capacitanceTest, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(featureNode, "gestureMode", &feature->gestureMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(featureNode, "gloverMOde", &feature->gloverMOde, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(featureNode, "coverMode", &feature->coverMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(featureNode, "chargerMode", &feature->chargeMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(featureNode, "knuckleMode", &feature->knuckleMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + return HDF_SUCCESS; +} + +int32_t ParseTouchBoardConfig(const struct DeviceResourceNode *node, TouchBoardCfg *config) +{ + int32_t ret; + struct DeviceResourceIface *parser = NULL; + + if (node == NULL || config == NULL) { + HDF_LOGE("%s: input param is null", __func__); + return HDF_FAILURE; + } + parser = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (parser == NULL) { + HDF_LOGE("%s: invalid parser", __func__); + return HDF_FAILURE; + } + config->boardNode = node; + const struct DeviceResourceNode *attrNode = parser->GetChildNode(node, "inputAttr"); + const struct DeviceResourceNode *busNode = parser->GetChildNode(node, "busConfig"); + const struct DeviceResourceNode *pinsNode = parser->GetChildNode(node, "pinConfig"); + const struct DeviceResourceNode *powerNode = parser->GetChildNode(node, "powerConfig"); + const struct DeviceResourceNode *featureNode = parser->GetChildNode(node, "featureConfig"); + if (attrNode == NULL || busNode == NULL || pinsNode == NULL || powerNode == NULL || featureNode == NULL) { + HDF_LOGE("%s: get child node fail!", __func__); + return HDF_FAILURE; + } + + ret = ParseAttr(parser, attrNode, &config->attr); + CHECK_PARSER_RET(ret, "ParseAttr"); + ret = ParseBus(parser, busNode, &config->bus); + CHECK_PARSER_RET(ret, "ParseBus"); + ret = ParsePins(parser, pinsNode, &config->pins); + CHECK_PARSER_RET(ret, "ParsePins"); + ret = ParsePower(parser, powerNode, &config->power); + CHECK_PARSER_RET(ret, "ParsePower"); + ret = ParseFeature(parser, featureNode, &config->feature); + CHECK_PARSER_RET(ret, "ParseFeature"); + return HDF_SUCCESS; +} + +static int32_t ParsePowerSequence(struct DeviceResourceIface *parser, const struct DeviceResourceNode *seqNode, + ChipPwrSeq *pwrSeq) +{ + int32_t ret; + uint32_t num = parser->GetElemNum(seqNode, "powerOnSeq"); + pwrSeq->pwrOn.count = num; + pwrSeq->pwrOn.buf = (uint32_t *)OsalMemAlloc(sizeof(uint32_t) * num); + if (pwrSeq->pwrOn.buf == NULL) { + return HDF_FAILURE; + } + (void)memset_s(pwrSeq->pwrOn.buf, sizeof(uint32_t) * num, 0, sizeof(uint32_t) * num); + ret = parser->GetUint32Array(seqNode, "powerOnSeq", pwrSeq->pwrOn.buf, num, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + + pwrSeq->suspend.count = parser->GetElemNum(seqNode, "suspendSeq"); + num = pwrSeq->suspend.count; + pwrSeq->suspend.buf = (uint32_t *)OsalMemAlloc(sizeof(uint32_t) * num); + if (pwrSeq->suspend.buf == NULL) { + OsalMemFree(pwrSeq->pwrOn.buf); + pwrSeq->pwrOn.buf = NULL; + return HDF_FAILURE; + } + (void)memset_s(pwrSeq->suspend.buf, sizeof(uint32_t) * num, 0, sizeof(uint32_t) * num); + ret = parser->GetUint32Array(seqNode, "suspendSeq", pwrSeq->suspend.buf, num, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + + pwrSeq->resume.count = parser->GetElemNum(seqNode, "resumeSeq"); + num = pwrSeq->resume.count; + pwrSeq->resume.buf = (uint32_t *)OsalMemAlloc(sizeof(uint32_t) * num); + if (pwrSeq->resume.buf == NULL) { + OsalMemFree(pwrSeq->pwrOn.buf); + pwrSeq->pwrOn.buf = NULL; + OsalMemFree(pwrSeq->suspend.buf); + pwrSeq->suspend.buf = NULL; + return HDF_FAILURE; + } + (void)memset_s(pwrSeq->resume.buf, sizeof(uint32_t) * num, 0, sizeof(uint32_t) * num); + ret = parser->GetUint32Array(seqNode, "resumeSeq", pwrSeq->resume.buf, num, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + + pwrSeq->pwrOff.count = parser->GetElemNum(seqNode, "powerOffSeq"); + num = pwrSeq->pwrOff.count; + pwrSeq->pwrOff.buf = (uint32_t *)OsalMemAlloc(sizeof(uint32_t) * num); + if (pwrSeq->pwrOff.buf == NULL) { + OsalMemFree(pwrSeq->pwrOn.buf); + pwrSeq->pwrOn.buf = NULL; + OsalMemFree(pwrSeq->suspend.buf); + pwrSeq->suspend.buf = NULL; + OsalMemFree(pwrSeq->resume.buf); + pwrSeq->resume.buf = NULL; + return HDF_FAILURE; + } + (void)memset_s(pwrSeq->pwrOff.buf, sizeof(uint32_t) * num, 0, sizeof(uint32_t) * num); + ret = parser->GetUint32Array(seqNode, "powerOffSeq", pwrSeq->pwrOff.buf, num, 0); + CHECK_PARSER_RET(ret, "GetUint32Array"); + + return HDF_SUCCESS; +} + +int32_t ParseTouchChipConfig(const struct DeviceResourceNode *node, TouchChipCfg *config) +{ + int32_t ret; + struct DeviceResourceIface *parser = NULL; + if (node == NULL || config == NULL) { + HDF_LOGE("%s: point is null", __func__); + return HDF_FAILURE; + } + parser = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (parser == NULL) { + HDF_LOGE("%s: instance parser failed", __func__); + return HDF_FAILURE; + } + + config->chipNode = node; + ret = parser->GetString(node, "chipName", &config->chipName, NULL); + CHECK_PARSER_RET(ret, "GetString"); + ret = parser->GetString(node, "vendorName", &config->vendorName, NULL); + CHECK_PARSER_RET(ret, "GetString"); + ret = parser->GetString(node, "chipInfo", &config->chipInfo, NULL); + CHECK_PARSER_RET(ret, "GetString"); + ret = parser->GetUint16(node, "chipVersion", &config->chipVersion, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint8(node, "busType", &config->bus.busType, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + if (config->bus.busType == 0) { + 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); + CHECK_PARSER_RET(ret, "GetUint32"); + ret = parser->GetUint32(node, "maxSpeed", &config->bus.chipI2c.maxSpeed, DEFAULT_I2C_SPEED); + CHECK_PARSER_RET(ret, "GetUint32"); + } else { + ret = parser->GetUint16(node, "irqFlag", &config->bus.chipSpi.irqFlag, 0); + CHECK_PARSER_RET(ret, "GetUint16"); + ret = parser->GetUint8(node, "wordMode", &config->bus.chipSpi.wordMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint8(node, "commMode", &config->bus.chipSpi.commMode, 0); + CHECK_PARSER_RET(ret, "GetUint8"); + ret = parser->GetUint32(node, "maxSpeed", &config->bus.chipSpi.maxSpeed, DEFAULT_SPI_SPEED); + CHECK_PARSER_RET(ret, "GetUint32"); + } + const struct DeviceResourceNode *pwrSeqNode = parser->GetChildNode(node, "powerSequence"); + if (pwrSeqNode == NULL) { + HDF_LOGE("%s: get powerSequence child node failed", __func__); + return HDF_FAILURE; + } + if (ParsePowerSequence(parser, pwrSeqNode, &config->pwrSeq) != HDF_SUCCESS) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} \ No newline at end of file diff --git a/model/input/driver/touchscreen/touch_ft6336.c b/model/input/driver/touchscreen/touch_ft6336.c new file mode 100644 index 00000000..cf99b79b --- /dev/null +++ b/model/input/driver/touchscreen/touch_ft6336.c @@ -0,0 +1,218 @@ +/* + * 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 "osal_mem.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "hdf_touch.h" +#include "input_i2c_ops.h" +#include "touch_ft6336.h" + +static int32_t ChipInit(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipResume(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipSuspend(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipDetect(ChipDevice *device) +{ + uint8_t regAddr; + uint8_t regValue = 0; + int32_t ret; + InputI2cClient *i2cClient = &device->driver->i2cClient; + + regAddr = FTS_REG_POINT_RATE; + ret = InputI2cWrite(i2cClient, ®Addr, 1); + 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); + + regAddr = FTS_REG_FW_VER; + ret = InputI2cWrite(i2cClient, ®Addr, 1); + CHIP_CHECK_RETURN(ret); + ret = InputI2cRead(i2cClient, ®Addr, 1, ®Value, 1); + CHIP_CHECK_RETURN(ret); + HDF_LOGI("%s: Firmware version = 0x%x", __func__, regValue); + + regAddr = FTS_REG_CHIP_ID; + ret = InputI2cWrite(i2cClient, ®Addr, 1); + CHIP_CHECK_RETURN(ret); + ret = InputI2cRead(i2cClient, ®Addr, 1, ®Value, 1); + CHIP_CHECK_RETURN(ret); + HDF_LOGI("%s: Chip ID is %d", __func__, regValue); + + (void)ChipInit(device); + (void)ChipResume(device); + (void)ChipSuspend(device); + return HDF_SUCCESS; +} + +static int32_t ParsePointData(FrameData *frame, uint8_t *buf, uint8_t pointNum) +{ + int32_t i; + for (i = 0; i < pointNum; i++) { + frame->fingers[i].x = (unsigned int)((buf[FT_X_H_POS + FT_POINT_SIZE * i] & HALF_BYTE_MASK) + << ONE_BYTE_OFFSET) | (unsigned int)buf[FT_X_L_POS + FT_POINT_SIZE * i]; + frame->fingers[i].y = (unsigned int)((buf[FT_Y_H_POS + FT_POINT_SIZE * i] & HALF_BYTE_MASK) + << ONE_BYTE_OFFSET) | (unsigned int)buf[FT_Y_L_POS + FT_POINT_SIZE * i]; + frame->fingers[i].trackId = (int)(buf[FT_FINGER_POS + FT_POINT_SIZE * i]) >> HALF_BYTE_OFFSET; + frame->fingers[i].status = (int)buf[FT_EVENT_POS + FT_POINT_SIZE * i] >> SIX_BIT_OFFSET; + frame->fingers[i].valid = true; + frame->definedEvent = frame->fingers[i].status; + + if ((frame->fingers[i].status == TOUCH_DOWN || frame->fingers[i].status == TOUCH_CONTACT) && (pointNum == 0)) { + HDF_LOGE("%s: abnormal event data from driver chip", __func__); + return HDF_FAILURE; + } + } + if (pointNum == 0) { + frame->definedEvent = TOUCH_UP; + } + return HDF_SUCCESS; +} + +static int32_t ChipDataHandle(ChipDevice *device) +{ + uint8_t buf[POINT_BUFFER_LEN] = {0}; + uint8_t reg = 0x0; + uint8_t pointNum; + InputI2cClient *i2cClient = &device->driver->i2cClient; + FrameData *frame = &device->driver->frameData; + + int32_t ret = InputI2cRead(i2cClient, ®, 1, buf, POINT_BUFFER_LEN); + CHIP_CHECK_RETURN(ret); + + OsalMutexLock(&device->driver->mutex); + (void)memset_s(frame, sizeof(FrameData), 0, sizeof(FrameData)); + pointNum = buf[FT_POINT_NUM_POS] & HALF_BYTE_MASK; + if (pointNum > MAX_SUPPORT_POINT) { + pointNum = MAX_SUPPORT_POINT; + } + + frame->realPointNum = pointNum; + ret = ParsePointData(frame, buf, pointNum); + if (ret != HDF_SUCCESS) { + OsalMutexUnlock(&device->driver->mutex); + return ret; + } + OsalMutexUnlock(&device->driver->mutex); + return HDF_SUCCESS; +} + +static struct TouchChipOps g_ft6336ChipOps = { + .Init = ChipInit, + .Detect = ChipDetect, + .Resume = ChipResume, + .Suspend = ChipSuspend, + .DataHandle = ChipDataHandle, +}; + +static void FreeChipConfig(TouchChipCfg *config) +{ + if (config->pwrSeq.pwrOn.buf != NULL) { + OsalMemFree(config->pwrSeq.pwrOn.buf); + } + + if (config->pwrSeq.pwrOff.buf != NULL) { + OsalMemFree(config->pwrSeq.pwrOff.buf); + } + + if (config->pwrSeq.resume.buf != NULL) { + OsalMemFree(config->pwrSeq.resume.buf); + } + + if (config->pwrSeq.suspend.buf != NULL) { + OsalMemFree(config->pwrSeq.suspend.buf); + } + + OsalMemFree(config); +} + +static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device) +{ + TouchChipCfg *chipCfg = (TouchChipCfg *)OsalMemAlloc(sizeof(TouchChipCfg)); + if (chipCfg == NULL) { + HDF_LOGE("%s: instance chip config failed", __func__); + return NULL; + } + (void)memset_s(chipCfg, sizeof(TouchChipCfg), 0, sizeof(TouchChipCfg)); + + if (ParseTouchChipConfig(device->property, chipCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: parse chip config failed", __func__); + OsalMemFree(chipCfg); + chipCfg = NULL; + } + return chipCfg; +} + +static ChipDevice *ChipDeviceInstance(void) +{ + ChipDevice *chipDev = (ChipDevice *)OsalMemAlloc(sizeof(ChipDevice)); + if (chipDev == NULL) { + HDF_LOGE("%s: instance chip device failed", __func__); + return NULL; + } + (void)memset_s(chipDev, sizeof(ChipDevice), 0, sizeof(ChipDevice)); + return chipDev; +} + +static int32_t HdfFocalChipInit(struct HdfDeviceObject *device) +{ + TouchChipCfg *chipCfg = NULL; + ChipDevice *chipDev = NULL; + HDF_LOGE("%s: enter", __func__); + if (device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + chipCfg = ChipConfigInstance(device); + if (chipCfg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + chipDev = ChipDeviceInstance(); + if (chipDev == NULL) { + goto EXIT; + } + + chipDev->chipCfg = chipCfg; + chipDev->ops = &g_ft6336ChipOps; + chipDev->chipName = chipCfg->chipName; + chipDev->vendorName = chipCfg->vendorName; + + if (RegisterChipDevice(chipDev) != HDF_SUCCESS) { + goto EXIT1; + } + HDF_LOGI("%s: exit succ, chipName = %s", __func__, chipCfg->chipName); + return HDF_SUCCESS; + +EXIT1: + OsalMemFree(chipDev); +EXIT: + FreeChipConfig(chipCfg); + return HDF_FAILURE; +} + +struct HdfDriverEntry g_touchFocalChipEntry = { + .moduleVersion = 1, + .moduleName = "HDF_TOUCH_FT6336", + .Init = HdfFocalChipInit, +}; + +HDF_INIT(g_touchFocalChipEntry); \ No newline at end of file diff --git a/model/input/driver/touchscreen/touch_ft6336.h b/model/input/driver/touchscreen/touch_ft6336.h new file mode 100644 index 00000000..11f35547 --- /dev/null +++ b/model/input/driver/touchscreen/touch_ft6336.h @@ -0,0 +1,42 @@ +/* + * 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 TOUCH_FT6236_H +#define TOUCH_FT6236_H + +/* register address */ +#define FTS_REG_POINT_RATE 0x88 // report rate +#define FTS_REG_FW_VER 0xA6 // FW version +#define FTS_REG_CHIP_ID 0xA3 // Chip ID +#define FTS_REG_VENDOR_ID 0xA8 // TP vendor ID + +/* the config for parsing event buffer */ +#define HALF_BYTE_MASK 0x0F +#define HALF_BYTE_OFFSET 4 +#define SIX_BIT_OFFSET 6 +#define ONE_BYTE_OFFSET 8 + +/* read data buffer len */ +/* head info occupy 3byte (Mode Switch, reserved, TD_status--point num), + * each point info occupy 6 bytes. + */ +#define POINT_BUFFER_LEN (FT_POINT_SIZE * MAX_SUPPORT_POINT + 3) +/* the FT6236 driver ic can support 2 points */ +#define MAX_SUPPORT_POINT 2 +/* buffer size of one event */ +#define FT_POINT_SIZE 6 +/* point data position */ +#define FT_POINT_NUM_POS 2 +#define FT_EVENT_POS 3 +#define FT_X_H_POS 3 +#define FT_X_L_POS 4 +#define FT_Y_H_POS 5 +#define FT_FINGER_POS 5 +#define FT_Y_L_POS 6 + +#endif diff --git a/model/input/driver/touchscreen/touch_gt911.c b/model/input/driver/touchscreen/touch_gt911.c new file mode 100644 index 00000000..04edebf4 --- /dev/null +++ b/model/input/driver/touchscreen/touch_gt911.c @@ -0,0 +1,259 @@ +/* + * 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 "osal_mem.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "hdf_touch.h" +#include "input_i2c_ops.h" +#include "touch_gt911.h" + +static int32_t ChipInit(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipResume(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipSuspend(ChipDevice *device) +{ + return HDF_SUCCESS; +} + +static int32_t ChipDetect(ChipDevice *device) +{ + int32_t ret; + int32_t version; + int32_t xSolution; + int32_t ySolution; + InputI2cClient *i2cClient = &device->driver->i2cClient; + uint8_t buf[GT_CFG_INFO_LEN] = {0}; + uint8_t reg[GT_ADDR_LEN] = {0}; + reg[0] = (GT_CFG_INFO_ADDR >> ONE_BYTE_OFFSET) & ONE_BYTE_MASK; + reg[1] = GT_CFG_INFO_ADDR & ONE_BYTE_MASK; + + ret = InputI2cRead(i2cClient, reg, GT_ADDR_LEN, buf, GT_CFG_INFO_LEN); + if (ret < 0) { + HDF_LOGE("%s: read chip version failed", __func__); + return HDF_FAILURE; + } + + version = (buf[GT_FW_VER_HIGH] << ONE_BYTE_OFFSET) | buf[GT_FW_VER_LOW]; + xSolution = (buf[GT_SOLU_X_HIGH] << ONE_BYTE_OFFSET) | buf[GT_SOLU_X_LOW]; + ySolution = (buf[GT_SOLU_Y_HIGH] << ONE_BYTE_OFFSET) | buf[GT_SOLU_Y_LOW]; + + HDF_LOGI("%s: IC FW version is 0x%x", __func__, version); + if (buf[GT_FW_VER_HIGH] == 0x0) { + HDF_LOGI("Product ID : %c%c%c_%02x%02x, xSol = %d, ySol = %d", buf[GT_PROD_ID_1ST], buf[GT_PROD_ID_2ND], + buf[GT_PROD_ID_3RD], buf[GT_FW_VER_HIGH], buf[GT_FW_VER_LOW], xSolution, ySolution); + } else { + HDF_LOGI("Product_ID: %c%c%c%c_%02x%02x, x_sol = %d, y_sol = %d", buf[GT_PROD_ID_1ST], buf[GT_PROD_ID_2ND], + buf[GT_PROD_ID_3RD], buf[GT_PROD_ID_4TH], buf[GT_FW_VER_HIGH], buf[GT_FW_VER_LOW], xSolution, ySolution); + } + + (void)ChipInit(device); + (void)ChipResume(device); + (void)ChipSuspend(device); + return HDF_SUCCESS; +} + +static int ChipCleanBuffer(InputI2cClient *i2cClient) +{ + int32_t ret; + uint8_t writeBuf[GT_CLEAN_DATA_LEN]; + writeBuf[GT_REG_HIGH_POS] = (GT_BUF_STATE_ADDR >> ONE_BYTE_OFFSET) & ONE_BYTE_MASK; + writeBuf[GT_REG_LOW_POS] = GT_BUF_STATE_ADDR & ONE_BYTE_MASK; + writeBuf[GT_CLEAN_POS] = GT_CLEAN_FLAG; + ret = InputI2cWrite(i2cClient, writeBuf, GT_CLEAN_DATA_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: InputI2cWrite failed, ret = %d", __func__, ret); + } + return ret; +} + +static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum) +{ + int32_t chipVer = device->chipCfg->chipVersion; + int32_t resX = device->driver->boardCfg->attr.resolutionX; + int32_t resY = device->driver->boardCfg->attr.resolutionY; + int32_t i; + + for (i = 0; i < pointNum; i++) { + if (chipVer == 0) { // chipversion A:gt911_zsj5p5 + 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); + } 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)); + frame->fingers[i].y = resY - 1 - ((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)); + } else { // chipversion C:gt911_tg7p0 + frame->fingers[i].x = resX - 1 - ((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)); + frame->fingers[i].y = resY - 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)); + } + frame->fingers[i].valid = true; + } +} + +static int32_t ChipDataHandle(ChipDevice *device) +{ + int32_t ret; + uint8_t touchStatus = 0; + uint8_t pointNum; + uint8_t buf[GT_POINT_SIZE * MAX_SUPPORT_POINT] = {0}; + InputI2cClient *i2cClient = &device->driver->i2cClient; + uint8_t reg[GT_ADDR_LEN] = {0}; + FrameData *frame = &device->driver->frameData; + + reg[0] = (GT_BUF_STATE_ADDR >> ONE_BYTE_OFFSET) & ONE_BYTE_MASK; + reg[1] = GT_BUF_STATE_ADDR & ONE_BYTE_MASK; + ret = InputI2cRead(i2cClient, reg, GT_ADDR_LEN, &touchStatus, 1); + if (ret < 0 || touchStatus == GT_EVENT_INVALID) { + return HDF_FAILURE; + } + + OsalMutexLock(&device->driver->mutex); + (void)memset_s(frame, sizeof(FrameData), 0, sizeof(FrameData)); + if (touchStatus == GT_EVENT_UP) { + frame->realPointNum = 0; + frame->definedEvent = TOUCH_UP; + goto EXIT; + } + + reg[0] = (GT_X_LOW_BYTE_BASE >> ONE_BYTE_OFFSET) & ONE_BYTE_MASK; + 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); + (void)ChipCleanBuffer(i2cClient); + OsalMutexUnlock(&device->driver->mutex); + return HDF_FAILURE; + } + frame->realPointNum = pointNum; + frame->definedEvent = TOUCH_DOWN; + (void)InputI2cRead(i2cClient, reg, GT_ADDR_LEN, buf, GT_POINT_SIZE * pointNum); + ParsePointData(device, frame, buf, pointNum); + +EXIT: + OsalMutexUnlock(&device->driver->mutex); + if (ChipCleanBuffer(i2cClient) != HDF_SUCCESS) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static struct TouchChipOps g_gt911ChipOps = { + .Init = ChipInit, + .Detect = ChipDetect, + .Resume = ChipResume, + .Suspend = ChipSuspend, + .DataHandle = ChipDataHandle, +}; + +static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device) +{ + TouchChipCfg *chipCfg = (TouchChipCfg *)OsalMemAlloc(sizeof(TouchChipCfg)); + if (chipCfg == NULL) { + HDF_LOGE("%s: instance chip config failed", __func__); + return NULL; + } + (void)memset_s(chipCfg, sizeof(TouchChipCfg), 0, sizeof(TouchChipCfg)); + + if (ParseTouchChipConfig(device->property, chipCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: parse chip config failed", __func__); + OsalMemFree(chipCfg); + chipCfg = NULL; + } + return chipCfg; +} + +static ChipDevice *ChipDeviceInstance(void) +{ + ChipDevice *chipDev = (ChipDevice *)OsalMemAlloc(sizeof(ChipDevice)); + if (chipDev == NULL) { + HDF_LOGE("%s: instance chip device failed", __func__); + return NULL; + } + (void)memset_s(chipDev, sizeof(ChipDevice), 0, sizeof(ChipDevice)); + return chipDev; +} + +static void FreeChipConfig(TouchChipCfg *config) +{ + if (config->pwrSeq.pwrOn.buf != NULL) { + OsalMemFree(config->pwrSeq.pwrOn.buf); + } + + if (config->pwrSeq.pwrOff.buf != NULL) { + OsalMemFree(config->pwrSeq.pwrOff.buf); + } + + if (config->pwrSeq.resume.buf != NULL) { + OsalMemFree(config->pwrSeq.resume.buf); + } + + if (config->pwrSeq.suspend.buf != NULL) { + OsalMemFree(config->pwrSeq.suspend.buf); + } + + OsalMemFree(config); +} + +static int32_t HdfGoodixChipInit(struct HdfDeviceObject *device) +{ + TouchChipCfg *chipCfg = NULL; + ChipDevice *chipDev = NULL; + + HDF_LOGI("%s: enter", __func__); + if (device == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + chipCfg = ChipConfigInstance(device); + if (chipCfg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + chipDev = ChipDeviceInstance(); + if (chipDev == NULL) { + goto EXIT; + } + + chipDev->chipCfg = chipCfg; + chipDev->ops = &g_gt911ChipOps; + chipDev->chipName = chipCfg->chipName; + chipDev->vendorName = chipCfg->vendorName; + + if (RegisterChipDevice(chipDev) != HDF_SUCCESS) { + goto EXIT1; + } + HDF_LOGI("%s: exit succ, chipName = %s", __func__, chipCfg->chipName); + return HDF_SUCCESS; + +EXIT1: + OsalMemFree(chipDev); +EXIT: + FreeChipConfig(chipCfg); + return HDF_FAILURE; +} + +struct HdfDriverEntry g_touchGoodixChipEntry = { + .moduleVersion = 1, + .moduleName = "HDF_TOUCH_GT911", + .Init = HdfGoodixChipInit, +}; + +HDF_INIT(g_touchGoodixChipEntry); diff --git a/model/input/driver/touchscreen/touch_gt911.h b/model/input/driver/touchscreen/touch_gt911.h new file mode 100644 index 00000000..c89a344d --- /dev/null +++ b/model/input/driver/touchscreen/touch_gt911.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 TOUCH_GT911_H +#define TOUCH_GT911_H + +/* the macro defines of GT911 */ +#define MAX_SUPPORT_POINT 10 +#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_ADDR_LEN 2 +#define GT_BUF_STATE_ADDR 0x814E +#define GT_X_LOW_BYTE_BASE 0x8150 +#define GT_FINGER_NUM_MASK 0x0F +#define GT_CLEAN_DATA_LEN 3 +#define GT_REG_HIGH_POS 0 +#define GT_REG_LOW_POS 1 +#define GT_CLEAN_POS 2 +#define GT_CLEAN_FLAG 0x0 +/* Config info macro of GT911 */ +#define GT_CFG_INFO_ADDR 0x8140 +#define GT_CFG_INFO_LEN 10 +#define GT_PROD_ID_1ST 0 +#define GT_PROD_ID_2ND 1 +#define GT_PROD_ID_3RD 2 +#define GT_PROD_ID_4TH 3 +#define GT_FW_VER_LOW 4 +#define GT_FW_VER_HIGH 5 +#define GT_SOLU_X_LOW 6 +#define GT_SOLU_X_HIGH 7 +#define GT_SOLU_Y_LOW 8 +#define GT_SOLU_Y_HIGH 9 + +#endif \ No newline at end of file diff --git a/model/network/wifi/netdevice/net_device.c b/model/network/common/netdevice/net_device.c old mode 100755 new mode 100644 similarity index 79% rename from model/network/wifi/netdevice/net_device.c rename to model/network/common/netdevice/net_device.c index a72bf630..da504d16 --- a/model/network/wifi/netdevice/net_device.c +++ b/model/network/common/netdevice/net_device.c @@ -1,38 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "net_device.h" - -#include -#include #include "securec.h" #include "osal_mem.h" @@ -45,11 +19,13 @@ static struct NetDeviceImpl *g_netDeviceImplTable[MAX_NETDEVICE_COUNT] = {NULL}; static bool FindAvailableTable(int32_t *index) { + int32_t i; + if (index == NULL) { HDF_LOGE("Find Available table index error!"); return false; } - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] == NULL) { *index = i; return true; @@ -70,7 +46,9 @@ static bool AddNetDeviceImplToTable(int32_t index, struct NetDeviceImpl *netDevi static void DeleteNetDeviceImplFromTable(const struct NetDeviceImpl *netDeviceImpl) { - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + int32_t i; + + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] == netDeviceImpl) { g_netDeviceImplTable[i] = NULL; return; @@ -93,14 +71,8 @@ static struct NetDeviceImpl *InitNetDeviceImpl(NetDevice *nd, NetIfCategory ifCa (void)memset_s(ndImpl, sizeof(struct NetDeviceImpl), 0, sizeof(struct NetDeviceImpl)); ndImpl->netDevice = nd; - if (ifCategory == LITE_OS) { - if (RegisterLiteNetDeviceImpl(ndImpl) != HDF_SUCCESS) { - HDF_LOGE("%s fail: resiter lite impl fail!", __func__); - OsalMemFree(ndImpl); - ndImpl = NULL; - } - } else { - HDF_LOGE("%s fail: resister not support!", __func__); + if (RegisterNetDeviceImpl(ndImpl) != HDF_SUCCESS) { + HDF_LOGE("%s fail: resiter lite impl fail!", __func__); OsalMemFree(ndImpl); ndImpl = NULL; } @@ -121,11 +93,7 @@ static void DeInitNetDeviceImpl(struct NetDeviceImpl *netDeviceImpl) /* step 1 : release interFace. step 2 : release netdevice */ if (netDeviceImpl->netDevice != NULL) { - if (netDeviceImpl->netDevice->netifCateg == LITE_OS) { - UnRegisterLiteNetDeviceImpl(netDeviceImpl); - } else { - HDF_LOGE("%s fail: unregister not support!", __func__); - } + UnRegisterNetDeviceImpl(netDeviceImpl); OsalMemFree(netDeviceImpl->netDevice); netDeviceImpl->netDevice = NULL; } @@ -139,7 +107,9 @@ static void DeInitNetDeviceImpl(struct NetDeviceImpl *netDeviceImpl) static struct NetDeviceImpl *GetImplByNetDevice(const struct NetDevice *netDevice) { struct NetDeviceImpl *ndImpl = NULL; - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + int32_t i; + + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { if (netDevice == g_netDeviceImplTable[i]->netDevice) { ndImpl = g_netDeviceImplTable[i]; @@ -154,7 +124,10 @@ static struct NetDeviceImpl *GetImplByNetDevice(const struct NetDevice *netDevic struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory ifCategory) { NetDevice *netDevice = NULL; + struct NetDeviceImpl *ndImpl = NULL; int32_t index = 0; + int32_t ret; + if ((ifName == NULL) || (strlen(ifName) != len) || (strlen(ifName) > IFNAMSIZ - 1)) { HDF_LOGE("%s fail: ifName = null or len not right!", __func__); return NULL; @@ -171,7 +144,7 @@ struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory return NULL; } netDevice->netifCateg = ifCategory; - struct NetDeviceImpl *ndImpl = InitNetDeviceImpl(netDevice, ifCategory); + ndImpl = InitNetDeviceImpl(netDevice, ifCategory); if (ndImpl == NULL) { HDF_LOGE("%s fail: InitNetDeviceImpl fail!", __func__); OsalMemFree(netDevice); @@ -185,7 +158,7 @@ struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory return NULL; } /* INIT OSPrivate */ - int32_t ret = HDF_FAILURE; + ret = HDF_FAILURE; if (ndImpl->interFace != NULL && ndImpl->interFace->init != NULL) { ret = ndImpl->interFace->init(ndImpl); } @@ -195,17 +168,19 @@ struct NetDevice *NetDeviceInit(const char *ifName, uint32_t len, NetIfCategory DeInitNetDeviceImpl(ndImpl); return NULL; } - HDF_LOGI("Init Net Device suncess!"); + HDF_LOGI("Init Net Device success!"); return netDevice; } int32_t NetDeviceDeInit(struct NetDevice *netDevice) { + struct NetDeviceImpl *ndImpl = NULL; + if (netDevice == NULL) { HDF_LOGI("%s success: already deinit!", __func__); return HDF_SUCCESS; } - struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + ndImpl = GetImplByNetDevice(netDevice); if (ndImpl == NULL) { HDF_LOGI("%s success: already free.", __func__); OsalMemFree(netDevice); @@ -220,6 +195,7 @@ int32_t NetDeviceAdd(struct NetDevice *netDevice, Protocol80211IfType ifType) { struct NetDeviceImplOp *op = NULL; struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL) { HDF_LOGE("%s fail: netDevice not exist!", __func__); return HDF_ERR_INVALID_PARAM; @@ -236,6 +212,7 @@ int32_t NetDeviceDelete(struct NetDevice *netDevice) { struct NetDeviceImplOp *op = NULL; struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl == NULL) { HDF_LOGE("%s fail: netDevice not exist!", __func__); return HDF_ERR_INVALID_PARAM; @@ -250,25 +227,29 @@ int32_t NetDeviceDelete(struct NetDevice *netDevice) struct NetDevice *NetDeviceGetInstByName(const char *name) { + int32_t i; + if (name == NULL) { HDF_LOGE("%s fail: name = NULL.", __func__); return NULL; } - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { if (strcmp(g_netDeviceImplTable[i]->netDevice->name, name) == 0) { return g_netDeviceImplTable[i]->netDevice; } } } - HDF_LOGE("%s fail: name not exist.", __func__); + HDF_LOGE("%s fail: %s: name not exist.", __func__, name); return NULL; } bool NetDeviceIsAnyInstRunning(void) { struct NetDevice *netDev = NULL; - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + int32_t i; + + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { netDev = g_netDeviceImplTable[i]->netDevice; if ((GET_NET_DEV_FLAGS(netDev) & NET_DEVICE_IFF_RUNNING) != 0) { @@ -293,7 +274,9 @@ bool NetDeviceIsInstRunning(const struct NetDevice *netDevice) uint32_t NetDevGetRegisterCount(void) { uint32_t count = 0; - for (int32_t i = 0; i < MAX_NETDEVICE_COUNT; i++) { + int32_t i; + + for (i = 0; i < MAX_NETDEVICE_COUNT; i++) { if (g_netDeviceImplTable[i] != NULL && g_netDeviceImplTable[i]->netDevice != NULL) { count++; } @@ -329,24 +312,23 @@ int32_t NetIfSetAddr(const struct NetDevice *netDevice, const IpV4Addr *ipAddr, return HDF_ERR_INVALID_PARAM; } -static int32_t NetIfRxImpl(const struct NetDevice *netDevice, struct NetBuf *buff, ReceiveFlage flage) +static int32_t NetIfRxImpl(const struct NetDevice *netDevice, NetBuf *buff, ReceiveFlag flag) { struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); + ProcessingResult ret = PROCESSING_CONTINUE; + if (ndImpl == NULL || ndImpl->interFace == NULL || ndImpl->interFace->receive == NULL) { HDF_LOGE("NetIfRxImpl fail : netdevice not exist!"); return HDF_ERR_INVALID_PARAM; } - ProcessingResult ret = PROCESSING_CONTINUE; /* to do driver special process */ -#if LOSCFG_NET_LWIP_SACK if (netDevice->netDeviceIf != NULL && netDevice->netDeviceIf->specialEtherTypeProcess != NULL) { ret = netDevice->netDeviceIf->specialEtherTypeProcess(netDevice, buff); } -#endif /* Sent to TCP/IP Stack. */ if (ret == PROCESSING_CONTINUE) { - return ndImpl->interFace->receive(ndImpl, buff, flage); + return ndImpl->interFace->receive(ndImpl, buff, flag); } else if (ret == PROCESSING_COMPLETE) { HDF_LOGI("NetIfRxImpl specialEtherType Process not need TCP/IP stack!"); return HDF_SUCCESS; @@ -356,16 +338,34 @@ static int32_t NetIfRxImpl(const struct NetDevice *netDevice, struct NetBuf *buf } } -int32_t NetIfRx(const struct NetDevice *netDevice, struct NetBuf *buff) +int32_t NetIfSetMacAddr(struct NetDevice *netDevice, const unsigned char *macAddr, unsigned char length) { - return NetIfRxImpl(netDevice, buff, NO_IN_INTERRUPT); + struct NetDeviceImpl *ndImpl = NULL; + if (macAddr == NULL || length != MAC_ADDR_SIZE) { + HDF_LOGE("%s fail: input param error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (memcpy_s(netDevice->macAddr, MAC_ADDR_SIZE, macAddr, MAC_ADDR_SIZE) != EOK) { + HDF_LOGE("%s fail : memcpy_s fail!", __func__); + return HDF_FAILURE; + } + ndImpl = GetImplByNetDevice(netDevice); + if (ndImpl != NULL && ndImpl->interFace != NULL && ndImpl->interFace->changeMacAddr != NULL) { + return ndImpl->interFace->changeMacAddr(ndImpl); + } + return HDF_FAILURE; } -int32_t NetIfRxNi(const struct NetDevice *netDevice, struct NetBuf *buff) +int32_t NetIfRx(const struct NetDevice *netDevice, NetBuf *buff) { return NetIfRxImpl(netDevice, buff, IN_INTERRUPT); } +int32_t NetIfRxNi(const struct NetDevice *netDevice, NetBuf *buff) +{ + return NetIfRxImpl(netDevice, buff, NO_IN_INTERRUPT); +} + int32_t NetIfSetStatus(const struct NetDevice *netDevice, NetIfStatus status) { struct NetDeviceImpl *ndImpl = GetImplByNetDevice(netDevice); @@ -443,10 +443,10 @@ int32_t NetIfDhcpIsBound(const struct NetDevice *netDevice) * size The net buffer size * @return : A new net buffer on success or NULL on fail */ -struct NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size) +NetBuf *NetBufDevAlloc(const struct NetDevice *dev, uint32_t size) { uint32_t reserve = 0; - struct NetBuf *nb = NULL; + NetBuf *nb = NULL; if (dev != NULL) { reserve = dev->neededHeadRoom + dev->neededTailRoom; diff --git a/model/network/common/netdevice/net_device_impl.h b/model/network/common/netdevice/net_device_impl.h new file mode 100644 index 00000000..22a62703 --- /dev/null +++ b/model/network/common/netdevice/net_device_impl.h @@ -0,0 +1,45 @@ +/* + * 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_NET_DEVICE_IMPL_MODULE_H +#define HDF_NET_DEVICE_IMPL_MODULE_H + +#include "net_device.h" + +#define MAX_NETDEVICE_COUNT 20 + +struct NetDeviceImpl { + struct NetDevice *netDevice; + struct NetDeviceImplOp *interFace; + void *osPrivate; +}; +typedef enum { + NO_IN_INTERRUPT, + IN_INTERRUPT, + MAX_RECEIVE_FLAG +} ReceiveFlag; + +struct NetDeviceImplOp { + int32_t (*init)(struct NetDeviceImpl *netDevice); + int32_t (*deInit)(struct NetDeviceImpl *netDevice); + int32_t (*add)(struct NetDeviceImpl *netDevice, Protocol80211IfType ifType); + int32_t (*delete)(struct NetDeviceImpl *netDevice); + int32_t (*setStatus)(struct NetDeviceImpl *netDevice, NetIfStatus status); + int32_t (*setLinkStatus)(struct NetDeviceImpl *netDevice, NetIfLinkStatus status); + int32_t (*receive)(struct NetDeviceImpl *netDevice, NetBuf *buff, ReceiveFlag flag); + int32_t (*setIpAddr)(struct NetDeviceImpl *netDevice, const IpV4Addr *ipAddr, const IpV4Addr *netMask, + const IpV4Addr *gw); + int32_t (*dhcpsStart)(struct NetDeviceImpl *netDevice, char *ip, uint16_t ipNum); + int32_t (*dhcpsStop)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpStart)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpStop)(struct NetDeviceImpl *netDevice); + int32_t (*dhcpIsBound)(struct NetDeviceImpl *netDevice); + int32_t (*changeMacAddr)(struct NetDeviceImpl *netDevice); +}; + +#endif /* HDF_NET_DEVICE_IMPL_MODULE_H */ \ No newline at end of file diff --git a/model/network/wifi/compoments/eapol/eapol.h b/model/network/wifi/compoments/eapol/eapol.h deleted file mode 100755 index b4454d86..00000000 --- a/model/network/wifi/compoments/eapol/eapol.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef HDF_EAPOL_H -#define HDF_EAPOL_H - -#include -#include -#include -#include "hdf_netbuf.h" -#include "net_device.h" - -#define EAPOL_MAX_COUNT 10 -#define EAPOL_MAX_ENQUEUE_TIME 300 /* 300 Second */ - -struct EapolData { - bool regFlag; /* is already regstered */ - uint16_t count; /* eapol frame count in NetBuffQueue. */ - uint16_t maxCount; - int64_t enqueueTime; /* record eapol frame time for dfx. */ - void (*notify)(const char *name, void *context); /* notify eapol frame enqueue message */ - void *context; - struct NetBufQueue eapolQueue; -}; - -struct Eapol { - struct EapolInterface *eapolOp; -}; - -struct EapolEnable { - void (*notify)(const char *name, void *context); - void *context; -}; - -struct EapolRx { - uint8_t *buff; - uint32_t len; -}; - -struct EapolTx { - uint8_t *buff; - uint32_t len; -}; - -struct EapolInterface { - int32_t (*enableEapol)(const struct NetDevice *netDevice, struct EapolEnable *buff); - int32_t (*disableEapol)(const struct NetDevice *netDevice); - int32_t (*getEapol)(const struct NetDevice *netDevice, struct EapolRx *buff); - int32_t (*sendEapol)(struct NetDevice *netDevice, struct EapolTx *buff); - int32_t (*writeEapolToQueue)(const struct NetDevice *netDevice, struct NetBuf *buff); -}; - -/* API */ -const struct Eapol *EapolGetInstance(void); -void DestroyEapolData(struct NetDevice *netDevice); -int32_t CreateEapolData(struct NetDevice *netDevice); - -#endif /* HDF_EAPOL_H */ \ No newline at end of file diff --git a/model/network/wifi/compoments/softap/ap.c b/model/network/wifi/compoments/softap/ap.c deleted file mode 100755 index 160693dd..00000000 --- a/model/network/wifi/compoments/softap/ap.c +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include "hdf_wifi_product.h" -#include "wifi_mac80211_ops.h" -#include "ap.h" - -#if __cplusplus -extern "C" { -#endif - -struct WifiApFeature g_apFeature; - -static int32_t ApInit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -static int32_t ApDeinit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -static int32_t SetupWireLessDev(struct NetDevice *netDev, WifiApSetting *apSettings) -{ - if (netDev->ieee80211Ptr == NULL) { - netDev->ieee80211Ptr = (struct WirelessDev *)OsalMemCalloc(sizeof(struct WirelessDev)); - if (netDev->ieee80211Ptr == NULL) { - return HDF_ERR_INVALID_PARAM; - } - } - - if (netDev->ieee80211Ptr->presetChandef.chan == NULL) { - netDev->ieee80211Ptr->presetChandef.chan = - (struct Ieee80211Channel *)OsalMemCalloc(sizeof(struct Ieee80211Channel)); - if (netDev->ieee80211Ptr->presetChandef.chan == NULL) { - OsalMemFree(netDev->ieee80211Ptr); - netDev->ieee80211Ptr = NULL; - return HDF_ERR_INVALID_PARAM; - } - } - - netDev->ieee80211Ptr->presetChandef.width = (enum WifiChannelType)apSettings->freqParams.bandwidth; - netDev->ieee80211Ptr->presetChandef.centerFreq1 = apSettings->freqParams.centerFreq1; - netDev->ieee80211Ptr->presetChandef.chan->hwValue = (uint16_t)apSettings->freqParams.channel; - netDev->ieee80211Ptr->presetChandef.chan->band = IEEE80211_BAND_2GHZ; - return HDF_SUCCESS; -} - -static uint32_t StartAp(struct NetDevice *netDev, WifiApSetting *apSettings) -{ - int32_t ret = SetupWireLessDev(netDev, apSettings); - if (ret) { - HDF_LOGE("StartAp:failed to SetupWireLessDev, error[%d]", ret); - return ret; - } - - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - Mac80211beaconParam beaconParam = { 0 }; - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setChannel); - if (macOps->setChannel(netDev)) { - HDF_LOGE("StartAp:failed to setChannel, error[%d]", ret); - return HDF_FAILURE; - } - - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setSsid); - if (macOps->setSsid(netDev, (const uint8_t *)apSettings->ssid, apSettings->ssidLen)) { - HDF_LOGE("StartAp:failed to setSsid, error[%d]", ret); - return HDF_FAILURE; - } - - beaconParam.interval = apSettings->beaconInterval; - beaconParam.dtimPeriod = apSettings->dtimPeriod; - beaconParam.hiddenSsid = (apSettings->hiddenSsid == 1); - beaconParam.beaconData = &apSettings->beaconData; - beaconParam.operationType = MAC_BEACON_ADD; - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); - if (macOps->changeBeacon(netDev, &beaconParam)) { - return HDF_FAILURE; - } - - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, startAp); - ret = macOps->startAp(netDev); - if (ret) { - HDF_LOGE("StartAp:failed to start ap, error[%d]", ret); - return HDF_FAILURE; - } - return NetIfSetStatus(netDev, NETIF_UP); -} - -static uint32_t StopAp(struct NetDevice *netDev) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, stopAp); - uint32_t ret = macOps->stopAp(netDev); - if (ret) { - HDF_LOGE("StopAp:failed, error[%d]", ret); - return ret; - } - - return NetIfSetStatus(netDev, NETIF_DOWN); -} - -static uint32_t DelStation(struct NetDevice *netDev, struct StationDelParameters *params) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_apFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, delStation); - return macOps->delStation(netDev, params->mac); -} - -static uint32_t ChangeBeacon(struct NetDevice *netDev, WifiApSetting *apSettings) -{ - if (netDev == NULL || apSettings == NULL) { - HDF_LOGI("%s: parameter null", __func__); - return HDF_FAILURE; - } - - Mac80211beaconParam beaconParam = { 0 }; - struct WifiMac80211Ops *macOps = g_apFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); - beaconParam.interval = apSettings->beaconInterval; - beaconParam.dtimPeriod = apSettings->dtimPeriod; - beaconParam.hiddenSsid = (apSettings->hiddenSsid == 1); - beaconParam.beaconData = &apSettings->beaconData; - beaconParam.operationType = MAC_BEACON_SET; - - return macOps->changeBeacon(netDev, &beaconParam); -} - -struct WifiApFeature g_apFeature = { - .fe = { - .name = "ap", - .init = ApInit, - .deInit = ApDeinit, - }, - .ops = { - .startAp = StartAp, - .stopAp = StopAp, - .delStation = DelStation, - .changeBeacon = ChangeBeacon, - }, -}; - -struct WifiApFeature *WifiApGetFeature(const struct WifiModule *module) -{ - return (struct WifiApFeature *)GetFeature(module, HDF_WIFI_FEATURE_AP); -} - -struct WifiFeature *GetWifiApFeatureDelc(void) -{ - return (struct WifiFeature *)&g_apFeature; -} - -#if __cplusplus -extern "C" -} -#endif diff --git a/model/network/wifi/compoments/softap/ap.h b/model/network/wifi/compoments/softap/ap.h deleted file mode 100755 index 7d28e69b..00000000 --- a/model/network/wifi/compoments/softap/ap.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef HDFLITE_AP_H -#define HDFLITE_AP_H - -#include "wifi_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -enum WifiAPFeatureType { - HDF_WIFI_AP_NOT_SUPPORT, - HDF_WIFI_AP_SOFTAP, - HDF_WIFI_AP_END, -}; - -struct WifiApFeatureOps { - uint32_t (*startAp)(struct NetDevice *dev, WifiApSetting *settings); - uint32_t (*stopAp)(struct NetDevice *dev); - uint32_t (*delStation)(struct NetDevice *dev, struct StationDelParameters *params); - uint32_t (*changeBeacon)(struct NetDevice *dev, WifiApSetting *apSettings); -}; - -struct WifiApFeature { - struct WifiFeature fe; - struct WifiApFeatureOps ops; -}; - -struct WifiApFeature *WifiApGetFeature(const struct WifiModule *module); - -struct WifiFeature *GetWifiApFeatureDelc(void); - -#ifdef __cplusplus -} -#endif -#endif // HDFLITE_AP_H diff --git a/model/network/wifi/compoments/sta/sta.c b/model/network/wifi/compoments/sta/sta.c deleted file mode 100755 index 9ba8b981..00000000 --- a/model/network/wifi/compoments/sta/sta.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "sta.h" -#include "hdf_wifi_product.h" - -#if __cplusplus -extern "C" { -#endif - -struct WifiStaFeature g_staFeature; - -static int32_t StaInit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -static int32_t StaDeinit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -static uint32_t Scan(struct NetDevice *netDev, struct WifiScanRequest *request) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, startScan); - return macOps->startScan(netDev, request); -} - -static void AbortScan(struct NetDevice *netDev) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; - if (macOps == NULL) { - HDF_LOGI("mac ops not registered"); - return; - } - - if (macOps->abortScan != NULL) { - macOps->abortScan(netDev); - } else { - HDF_LOGE("macOps abortScan not implement"); - } -} - -static uint32_t Connect(struct NetDevice *netDev, struct WifiConnectParams *param) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeBeacon); - return macOps->connect(netDev, param); -} - -static uint32_t Disconnect(struct NetDevice *netDev, uint16_t reasonCode) -{ - struct WifiMac80211Ops *macOps = (struct WifiMac80211Ops *)g_staFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, disconnect); - return macOps->disconnect(netDev, reasonCode); -} - -struct WifiStaFeature g_staFeature = { - .fe = { - .name = "sta", - .init = StaInit, - .deInit = StaDeinit, - }, - .ops = { - .scan = Scan, - .abortScan = AbortScan, - .connect = Connect, - .disconnect = Disconnect, - }, -}; - -struct WifiStaFeature *GetWifiStaFeature(const struct WifiModule *module) -{ - return (struct WifiStaFeature *)GetFeature(module, HDF_WIFI_FEATURE_STA); -} - -struct WifiFeature *GetWifiStaFeatureDelc(void) -{ - return (struct WifiFeature *)&g_staFeature; -} - -#ifdef __cplusplus -} -#endif diff --git a/model/network/wifi/compoments/sta/sta.h b/model/network/wifi/compoments/sta/sta.h deleted file mode 100755 index 2dd85021..00000000 --- a/model/network/wifi/compoments/sta/sta.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef HDFLITE_STA_H -#define HDFLITE_STA_H - -#include "wifi_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct WifiStaFeatureOps { - uint32_t (*scan)(struct NetDevice *dev, struct WifiScanRequest *request); - void (*abortScan)(struct NetDevice *dev); - uint32_t (*connect)(struct NetDevice *dev, struct WifiConnectParams *sme); - uint32_t (*disconnect)(struct NetDevice *dev, uint16_t reason_code); -}; - -struct WifiStaFeature { - struct WifiFeature fe; - struct WifiStaFeatureOps ops; -}; - -struct WifiStaFeature *GetWifiStaFeature(const struct WifiModule *module); -struct WifiFeature *GetWifiStaFeatureDelc(void); -#ifdef __cplusplus -} -#endif - -#endif // HDFLITE_STA_H diff --git a/model/network/wifi/compoments/eapol/eapol.c b/model/network/wifi/core/compoments/eapol/eapol.c old mode 100755 new mode 100644 similarity index 73% rename from model/network/wifi/compoments/eapol/eapol.c rename to model/network/wifi/core/compoments/eapol/eapol.c index 032f7b9b..f1e02bbc --- a/model/network/wifi/compoments/eapol/eapol.c +++ b/model/network/wifi/core/compoments/eapol/eapol.c @@ -1,36 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "eapol.h" -#include #include "securec.h" #include "osal_time.h" #include "osal_mem.h" @@ -51,8 +27,10 @@ static int32_t EnableEapol(const struct NetDevice *netDevice, struct EapolEnable *buff) { + struct EapolData *eapol = NULL; + RETURN_IF_INPUT_VALID(netDevice, buff); - struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + eapol = (struct EapolData *)netDevice->specialProcPriv; eapol->regFlag = true; eapol->context = buff->context; eapol->notify = buff->notify; @@ -61,11 +39,13 @@ static int32_t EnableEapol(const struct NetDevice *netDevice, struct EapolEnable static int32_t DisableEapol(const struct NetDevice *netDevice) { + struct EapolData *eapol = NULL; + if (netDevice == NULL || netDevice->specialProcPriv == NULL) { HDF_LOGE("%s: netDevice = null or specialProcPriv = null!", __func__); return HDF_ERR_INVALID_PARAM; } - struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + eapol = (struct EapolData *)netDevice->specialProcPriv; eapol->regFlag = false; eapol->context = NULL; eapol->notify = NULL; @@ -74,10 +54,14 @@ static int32_t DisableEapol(const struct NetDevice *netDevice) static int32_t GetEapol(const struct NetDevice *netDevice, struct EapolRx *buff) { - RETURN_IF_INPUT_VALID(netDevice, buff); - struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + struct EapolData *eapol = NULL; struct EapolRx *eapolRx = buff; - struct NetBuf *netBuff = NULL; + NetBuf *netBuff = NULL; + uint8_t *p = NULL; + uint32_t len; + + RETURN_IF_INPUT_VALID(netDevice, buff); + eapol = (struct EapolData *)netDevice->specialProcPriv; if (NetBufQueueIsEmpty(&eapol->eapolQueue)) { HDF_LOGE("%s fail : eapolQueue empty!", __func__); return HDF_FAILURE; @@ -88,8 +72,8 @@ static int32_t GetEapol(const struct NetDevice *netDevice, struct EapolRx *buff) return HDF_FAILURE; } - uint8_t *p = NetBufGetAddress(netBuff, E_DATA_BUF); - uint32_t len = NetBufGetDataLen(netBuff); + 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).", __func__, netBuff->len, eapolRx->len); @@ -110,6 +94,9 @@ static int32_t GetEapol(const struct NetDevice *netDevice, struct EapolRx *buff) static int32_t SendEapol(struct NetDevice *netDevice, struct EapolTx *buff) { + struct EapolTx *eapolTx = buff; + NetBuf *netBuff = NULL; + if (netDevice == NULL || buff == NULL) { HDF_LOGE("%s : netdevice = null or buff = null.", __func__); return HDF_ERR_INVALID_PARAM; @@ -119,12 +106,11 @@ static int32_t SendEapol(struct NetDevice *netDevice, struct EapolTx *buff) return HDF_FAILURE; } - struct EapolTx *eapolTx = buff; if (eapolTx->buff == NULL) { HDF_LOGE("%s::eapolTx->buff = null!", __func__); return HDF_ERR_INVALID_PARAM; } - struct NetBuf *netBuff = NetBufDevAlloc(netDevice, eapolTx->len); + netBuff = NetBufDevAlloc(netDevice, eapolTx->len); if (netBuff == NULL) { HDF_LOGE("%s : netBuff alloc fail!", __func__); return HDF_FAILURE; @@ -141,17 +127,20 @@ static int32_t SendEapol(struct NetDevice *netDevice, struct EapolTx *buff) static void HandleEapolQueue(struct EapolData *eapol) { + int64_t currentTime = 0; + int64_t intervalTime = 0; + uint16_t maxCount; + OsalTimespec timeSpec; + NetBuf *netBuf = NULL; + if (eapol == NULL) { return; } - int64_t currentTime = 0; - int64_t intervalTime = 0; - OsalTimespec timeSpec; - struct NetBuf *netBuf = NULL; + if (OsalGetTime(&timeSpec) == HDF_SUCCESS) { currentTime = timeSpec.sec; } - uint16_t maxCount = (eapol->maxCount != 0) ? eapol->maxCount : EAPOL_MAX_COUNT; + maxCount = (eapol->maxCount != 0) ? eapol->maxCount : EAPOL_MAX_COUNT; /* The queue is empty to update enqueueTime and count */ if (NetBufQueueIsEmpty(&eapol->eapolQueue)) { eapol->enqueueTime = currentTime; @@ -183,10 +172,12 @@ static void HandleEapolQueue(struct EapolData *eapol) return; } -static int32_t WriteEapolToQueue(const struct NetDevice *netDevice, struct NetBuf *buff) +static int32_t WriteEapolToQueue(const struct NetDevice *netDevice, NetBuf *buff) { + struct EapolData *eapol = NULL; + RETURN_IF_INPUT_VALID(netDevice, buff); - struct EapolData *eapol = (struct EapolData *)netDevice->specialProcPriv; + eapol = (struct EapolData *)netDevice->specialProcPriv; if (eapol->regFlag && (eapol->notify != NULL)) { HandleEapolQueue(eapol); /* eapol data enqueue and notify wap processing */ @@ -216,6 +207,8 @@ struct Eapol g_eapol = { int32_t CreateEapolData(struct NetDevice *netDevice) { + struct EapolData *eapolData = NULL; + if (netDevice == NULL) { HDF_LOGE("%s fail : netdev = null!", __func__); return HDF_ERR_INVALID_PARAM; @@ -224,7 +217,7 @@ int32_t CreateEapolData(struct NetDevice *netDevice) HDF_LOGI("%s already create!", __func__); return HDF_SUCCESS; } - struct EapolData *eapolData = (struct EapolData *)OsalMemCalloc(sizeof(struct EapolData)); + eapolData = (struct EapolData *)OsalMemCalloc(sizeof(struct EapolData)); if (eapolData == NULL) { HDF_LOGE("%s fail : malloc fail!", __func__); return HDF_FAILURE; @@ -238,11 +231,13 @@ int32_t CreateEapolData(struct NetDevice *netDevice) void DestroyEapolData(struct NetDevice *netDevice) { + struct EapolData *eapolData = NULL; + if (netDevice == NULL || netDevice->specialProcPriv == NULL) { HDF_LOGE("%s already free!", __func__); return; } - struct EapolData *eapolData = (struct EapolData *)netDevice->specialProcPriv; + eapolData = (struct EapolData *)netDevice->specialProcPriv; NetBufQueueClear(&eapolData->eapolQueue); OsalMemFree(eapolData); netDevice->specialProcPriv = NULL; diff --git a/model/network/wifi/core/compoments/eapol/eapol.h b/model/network/wifi/core/compoments/eapol/eapol.h new file mode 100644 index 00000000..d82b6c69 --- /dev/null +++ b/model/network/wifi/core/compoments/eapol/eapol.h @@ -0,0 +1,60 @@ +/* + * 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_EAPOL_H +#define HDF_EAPOL_H + +#include "hdf_netbuf.h" +#include "net_device.h" + +#define EAPOL_MAX_COUNT 10 +#define EAPOL_MAX_ENQUEUE_TIME 300 /* 300 Second */ + +struct EapolData { + bool regFlag; /* is already regstered */ + uint16_t count; /* eapol frame count in NetBuffQueue. */ + uint16_t maxCount; + int64_t enqueueTime; /* record eapol frame time for dfx. */ + void (*notify)(const char *name, void *context); /* notify eapol frame enqueue message */ + void *context; + NetBufQueue eapolQueue; +}; + +struct Eapol { + struct EapolInterface *eapolOp; +}; + +struct EapolEnable { + void (*notify)(const char *name, void *context); + void *context; +}; + +struct EapolRx { + uint8_t *buff; + uint32_t len; +}; + +struct EapolTx { + uint8_t *buff; + uint32_t len; +}; + +struct EapolInterface { + int32_t (*enableEapol)(const struct NetDevice *netDevice, struct EapolEnable *buff); + int32_t (*disableEapol)(const struct NetDevice *netDevice); + int32_t (*getEapol)(const struct NetDevice *netDevice, struct EapolRx *buff); + int32_t (*sendEapol)(struct NetDevice *netDevice, struct EapolTx *buff); + int32_t (*writeEapolToQueue)(const struct NetDevice *netDevice, NetBuf *buff); +}; + +/* API */ +const struct Eapol *EapolGetInstance(void); +void DestroyEapolData(struct NetDevice *netDevice); +int32_t CreateEapolData(struct NetDevice *netDevice); + +#endif /* HDF_EAPOL_H */ \ No newline at end of file diff --git a/model/network/wifi/core/compoments/softap/ap.c b/model/network/wifi/core/compoments/softap/ap.c new file mode 100644 index 00000000..21daac1a --- /dev/null +++ b/model/network/wifi/core/compoments/softap/ap.c @@ -0,0 +1,469 @@ +/* + * 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 "ap.h" +#include +#include +#include "message/message_router.h" +#include "message/sidecar.h" +#include "wifi_base.h" +#include "wifi_mac80211_ops.h" +#include "hdf_wlan_services.h" +#include "hdf_wlan_utils.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +#ifdef __cplusplus +extern "C" { +#endif +static uint32_t ChangeBeacon(struct NetDevice *netDev, WifiApSetting *apSettings) +{ + struct WlanBeaconConf beaconConf = { 0 }; + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + if (netDev == NULL || apSettings == NULL) { + HDF_LOGE("%s: parameter null", __func__); + return HDF_FAILURE; + } + + beaconConf.interval = apSettings->beaconInterval; + beaconConf.DTIMPeriod = apSettings->dtimPeriod; + beaconConf.hiddenSSID = (apSettings->hiddenSsid == 1); + beaconConf.headIEs = apSettings->beaconData.head; + beaconConf.headIEsLength = apSettings->beaconData.headLen; + beaconConf.tailIEs = apSettings->beaconData.tail; + beaconConf.tailIEsLength = apSettings->beaconData.tailLen; + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, ConfigBeacon); + return chipDriver->apOps->ConfigBeacon(netDev, &beaconConf); +} + +static int32_t StartAp(struct NetDevice *netDev, WifiApSetting *apSettings) +{ + HDF_LOGE("%s:starting ap...", __func__); + struct WlanAPConf apConf = { 0 }; + int32_t ret; + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + apConf.band = IEEE80211_BAND_2GHZ; + errno_t err = memcpy_s(apConf.ssidConf.ssid, IEEE80211_MAX_SSID_LEN, apSettings->ssid, apSettings->ssidLen); + if (err != EOK) { + HDF_LOGE("%s: memcpy_s failed!ret=%d", __func__, err); + return HDF_FAILURE; + } + apConf.ssidConf.ssidLen = apSettings->ssidLen; + apConf.centerFreq1 = apSettings->freqParams.centerFreq1; + apConf.channel = apSettings->freqParams.channel; + apConf.width = apSettings->freqParams.bandwidth; + + 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); + return HDF_FAILURE; + } + + ret = ChangeBeacon(netDev, apSettings); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:ChangeBeacon failed!ret=%d", __func__, ret); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, StartAp); + ret = chipDriver->apOps->StartAp(netDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:StartAp failed!ret=%d", __func__, ret); + return HDF_FAILURE; + } + return NetIfSetStatus(netDev, NETIF_UP); +} + +static uint32_t StopAp(struct NetDevice *netDev) +{ + uint32_t ret; + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, StopAp); + ret = chipDriver->apOps->StopAp(netDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("StopAp:failed, error[%d]", ret); + return ret; + } + + return NetIfSetStatus(netDev, NETIF_DOWN); +} + +static uint32_t DelStation(struct NetDevice *netDev, struct StationDelParameters *params) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, DelStation); + return chipDriver->apOps->DelStation(netDev, params->mac); +} + +static uint32_t SetCountryCode(struct NetDevice *netDev, const char *code, uint32_t len) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, SetCountryCode); + return chipDriver->apOps->SetCountryCode(netDev, code, len); +} + +static uint32_t GetAssociatedStasCount(struct NetDevice *netDev, uint32_t *num) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, GetAssociatedStasCount); + return chipDriver->apOps->GetAssociatedStasCount(netDev, num); +} + +static uint32_t GetAssociatedStasInfo(struct NetDevice *netDev, WifiStaInfo *staInfo, uint32_t num) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->apOps, GetAssociatedStasInfo); + return chipDriver->apOps->GetAssociatedStasInfo(netDev, staInfo, num); +} + +static int32_t WifiCmdSetAp(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + WifiApSetting *apSettings = NULL; + uint32_t settingLen = 0; + const char *ifName = NULL; + struct NetDevice *netdev = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&apSettings, &settingLen) || apSettings == NULL || + settingLen != sizeof(WifiApSetting)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "apSettings"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->beaconData.head), &(apSettings->beaconData.headLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "head"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->beaconData.tail), &(apSettings->beaconData.tailLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "tail"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->ssid), &(apSettings->ssidLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ssid"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->meshSsid), &(apSettings->meshSsidLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "meshSsid"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + HDF_LOGI("%s:%s starting AP ...", __func__, ifName); + return StartAp(netdev, apSettings); +} + +static int32_t WifiCmdStopAp(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + const char *ifName = NULL; + struct NetDevice *netdev = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + HDF_LOGI("%s:%s stopping AP ...", __func__, ifName); + return StopAp(netdev); +} + +static int32_t WifiCmdChangeBeacon(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + WifiApSetting *apSettings = NULL; + uint32_t settingLen = 0; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&apSettings, &settingLen) || apSettings == NULL || + settingLen != sizeof(WifiApSetting)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "apSettings", settingLen); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->beaconData.head), &(apSettings->beaconData.headLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "head"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->beaconData.tail), &(apSettings->beaconData.tailLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "tail"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->ssid), &(apSettings->ssidLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ssid"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(apSettings->meshSsid), &(apSettings->meshSsidLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "meshSsid"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + return ChangeBeacon(netdev, apSettings); +} + +static int32_t WifiCmdStaRemove(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + struct StationDelParameters params; + const char *ifName = NULL; + uint32_t dataSize = 0; + int32_t ret; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + params.subtype = 0; + params.reasonCode = 0; + if (!HdfSbufReadBuffer(reqData, (const void **)¶ms.mac, &dataSize) || dataSize != ETH_ADDR_LEN) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "mac", dataSize); + return HDF_FAILURE; + } + + ret = DelStation(netdev, ¶ms); + HDF_LOGI("%s:del station XX:XX:XX:XX:XX:%02X ret=%d", __func__, params.mac[ETH_ADDR_LEN - 1], ret); + return ret; +} + +static int32_t GetAssociatedStas(struct NetDevice *netdev, uint32_t num, struct HdfSBuf *rspData) +{ + int32_t ret; + WifiStaInfo *staInfo = NULL; + + staInfo = (WifiStaInfo *)OsalMemCalloc(sizeof(WifiStaInfo) * num); + if (staInfo == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed!", __func__); + return HDF_FAILURE; + } + ret = GetAssociatedStasInfo(netdev, staInfo, num); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to get sta info,%d", __func__, ret); + OsalMemFree(staInfo); + return ret; + } + if (!HdfSbufWriteBuffer(rspData, staInfo, sizeof(WifiStaInfo) * num)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + OsalMemFree(staInfo); + return HDF_FAILURE; + } + OsalMemFree(staInfo); + return HDF_SUCCESS; +} + +static int32_t WifiCmdGetAssociatedStas(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + uint32_t num; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + ret = GetAssociatedStasCount(netdev, &num); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to get user num,ret=%d", __func__, ret); + return ret; + } + if (!HdfSbufWriteUint32(rspData, num)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + if (num == 0) { + return HDF_SUCCESS; + } + ret = GetAssociatedStas(netdev, num, rspData); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to GetAssociatedStas,%d", __func__, ret); + return ret; + } + return ret; +} + +static int32_t WifiCmdSetCountryCode(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + const char *code = NULL; + uint32_t replayDataSize; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&code, &replayDataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "code"); + return HDF_FAILURE; + } + ret = SetCountryCode(netdev, code, replayDataSize); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to set country code,%d", __func__, ret); + } + return ret; +} + +static struct MessageDef g_wifiApFeatureCmds[] = { + DUEMessage(CMD_AP_START, WifiCmdSetAp, 0), + DUEMessage(CMD_AP_STOP, WifiCmdStopAp, 0), + DUEMessage(CMD_AP_CHANGE_BEACON, WifiCmdChangeBeacon, 0), + DUEMessage(CMD_AP_DEL_STATION, WifiCmdStaRemove, 0), + DUEMessage(CMD_AP_GET_ASSOC_STA, WifiCmdGetAssociatedStas, 0), + DUEMessage(CMD_AP_SET_COUNTRY_CODE, WifiCmdSetCountryCode, 0) +}; +ServiceDefine(APService, AP_SERVICE_ID, g_wifiApFeatureCmds); + +static Service *g_apService = NULL; + +int32_t ApInit(struct WifiFeature *feature) +{ + (void)feature; + if (g_apService == NULL) { + ServiceCfg cfg = { + .dispatcherId = DEFAULT_DISPATCHER_ID + }; + g_apService = CreateService(APService, &cfg); + if (g_apService == NULL) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t ApDeinit(struct WifiFeature *feature) +{ + (void)feature; + if (g_apService != NULL && g_apService->Destroy != NULL) { + g_apService->Destroy(g_apService); + g_apService = NULL; + } + return HDF_SUCCESS; +} + +struct WifiFeature g_apFeature = { + .name = "ap", + .init = ApInit, + .deInit = ApDeinit +}; + +struct WifiFeature *GetWifiApFeature(void) +{ + return &g_apFeature; +} + +#ifdef __cplusplus +} +#endif diff --git a/model/network/wifi/core/compoments/softap/ap.h b/model/network/wifi/core/compoments/softap/ap.h new file mode 100644 index 00000000..8a9056ef --- /dev/null +++ b/model/network/wifi/core/compoments/softap/ap.h @@ -0,0 +1,23 @@ +/* + * 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 HDFLITE_AP_H +#define HDFLITE_AP_H + +#include "wifi_module.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct WifiFeature *GetWifiApFeature(void); + +#ifdef __cplusplus +} +#endif +#endif // HDFLITE_AP_H diff --git a/model/network/wifi/core/compoments/sta/sta.c b/model/network/wifi/core/compoments/sta/sta.c new file mode 100644 index 00000000..f72abde6 --- /dev/null +++ b/model/network/wifi/core/compoments/sta/sta.c @@ -0,0 +1,469 @@ +/* + * 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 "sta.h" +#include "securec.h" +#include "message/message_router.h" +#include "message/sidecar.h" +#include "wifi_base.h" +#include "hdf_wlan_services.h" +#include "hdf_wlan_utils.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +#ifdef __cplusplus +extern "C" { +#endif + +inline static int32_t Connect(struct NetDevice *netDev, struct WlanConnectParams *param) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->staOps, Connect); + return chipDriver->staOps->Connect(netDev, param); +} + +inline static int32_t Disconnect(struct NetDevice *netDev, uint16_t reasonCode) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->staOps, Disconnect); + return chipDriver->staOps->Disconnect(netDev, reasonCode); +} + +inline static int32_t ScanAll(struct NetDevice *netDev, struct WlanScanRequest *params) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->staOps, StartScan); + return chipDriver->staOps->StartScan(netDev, params); +} + +inline static int32_t AbortScan(struct NetDevice *netDev) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->staOps, AbortScan); + return chipDriver->staOps->AbortScan(netDev); +} + +static int WifiFillScanParam(struct WlanScanRequest *params, struct HdfSBuf *reqData) +{ + uint32_t dataSize = 0; + + if (!HdfSbufReadBuffer(reqData, (const void **)¶ms->bssid, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "apSettings"); + return HDF_FAILURE; + } + + if (!HdfSbufReadBuffer(reqData, (const void **)¶ms->ssids, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ssids"); + return HDF_FAILURE; + } + params->ssidCount = dataSize / sizeof(params->ssids[0]); + + if (!HdfSbufReadBuffer(reqData, (const void **)¶ms->extraIEs, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "extraIes"); + return HDF_FAILURE; + } + params->extraIEsLen = dataSize; + + if (!HdfSbufReadBuffer(reqData, (const void **)¶ms->freqs, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "freqs"); + return HDF_FAILURE; + } + params->freqsCount = + (dataSize / sizeof(params->freqs[0])) < MAX_FREQ_FTILTER_COUNT ? (dataSize / sizeof(params->freqs[0])) : 0; + + return HDF_SUCCESS; +} + +static uint8_t WifiValidIeAttr(const uint8_t *ie, uint32_t len) +{ + uint8_t elemLen; + + if (ie == NULL) { // ie null is normal + return true; + } + + while (len != 0) { + if (len < 2) { + return false; + } + len -= 2; + + elemLen = ie[1]; + if (elemLen > len) { + return false; + } + len -= elemLen; + ie += 2 + elemLen; + } + + return true; +} + +static int WifiFillAssocParams(WifiAssociateParams *assoc, struct HdfSBuf *reqData) +{ + uint32_t dataSize = 0; + + if (!HdfSbufReadBuffer(reqData, (const void **)&assoc->bssid, &dataSize) || dataSize != ETH_ADDR_LEN) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "bssid"); + return HDF_FAILURE; + } + + if (!HdfSbufReadBuffer(reqData, (const void **)&assoc->ssid, &(assoc->ssidLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ssid"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&assoc->ie, &(assoc->ieLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ie"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&assoc->key, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "key"); + return HDF_FAILURE; + } + if (!HdfSbufReadUint8(reqData, &assoc->authType)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "authType"); + return HDF_FAILURE; + } + if (!HdfSbufReadUint8(reqData, &assoc->privacy)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "privacy"); + return HDF_FAILURE; + } + if (!HdfSbufReadUint8(reqData, &assoc->keyIdx)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "keyIdx"); + return HDF_FAILURE; + } + if (!HdfSbufReadUint8(reqData, &assoc->mfp)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "mfp"); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(reqData, &assoc->freq)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "freq"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&assoc->crypto, &dataSize)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "crypto"); + return HDF_FAILURE; + } + if ((assoc->ssid == NULL) || (assoc->ssidLen == 0)) { + HDF_LOGE("%s:void ssid", __func__); + return HDF_FAILURE; + } + + if (WifiValidIeAttr(assoc->ie, assoc->ieLen) == false) { + HDF_LOGE("%s:illegal ie", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int WifiSetAssocParams(const WifiAssociateParams *assoc, const struct NetDevice *netdev, + struct WlanConnectParams *params) +{ + params->ssid = assoc->ssid; + params->ssidLen = assoc->ssidLen; + params->ie = assoc->ie; + params->ieLen = assoc->ieLen; + + if ((assoc->authType > WIFI_AUTHTYPE_AUTOMATIC) || (assoc->authType == WIFI_AUTHTYPE_SAE)) { + HDF_LOGE("%s:illegal authType %u", __func__, assoc->authType); + return HDF_FAILURE; + } + params->authType = assoc->authType; + + params->bssid = assoc->bssid; + params->privacy = assoc->privacy; + if ((assoc->mfp != WIFI_MFP_REQUIRED) && (assoc->mfp != WIFI_MFP_NO) && (assoc->mfp != WIFI_MFP_OPTIONAL)) { + HDF_LOGE("%s:unexpected mfp.mfp=%u", __func__, assoc->mfp); + return HDF_FAILURE; + } + + params->mfp = (WifiMfp)assoc->mfp; + if (assoc->key != NULL) { + params->key = assoc->key; + params->keyLen = assoc->keyLen; + params->keyIdx = assoc->keyIdx; + } + + if (memcpy_s(¶ms->crypto, sizeof(WifiCryptoSetting), assoc->crypto, sizeof(WifiCryptoSetting)) != EOK) { + HDF_LOGE("%s:copy crypto failed!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdAssoc(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct WlanConnectParams params = { 0 }; + WifiAssociateParams assoc = { 0 }; + struct NetDevice *netdev = NULL; + struct WlanHwCapability *capability = NULL; + const char *ifName = NULL; + int32_t ret; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (WifiFillAssocParams(&assoc, reqData) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + if ((netdev = NetDeviceGetInstByName(ifName)) == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (WifiSetAssocParams(&assoc, netdev, ¶ms) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + capability = GetHwCapability(netdev); + if (capability == NULL) { + HDF_LOGE("%s:GetHwCapability failed!", __func__); + return HDF_FAILURE; + } + do { + params.centerFreq = assoc.freq; + HDF_LOGI("%s:%s connecting to AP ...", __func__, ifName); + ret = Connect(netdev, ¶ms); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:fail to do connect,%d", __func__, ret); + break; + } + } while (false); + + if (capability->Release != NULL) { + capability->Release(capability); + capability = NULL; + } + + return ret; +} + +static int32_t WifiCmdDisconnect(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + uint16_t reasonCode; + const char *ifName = NULL; + int ret; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + if (!HdfSbufReadUint16(reqData, &reasonCode)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "reasonCode"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + HDF_LOGW("%s:%s disconnecting from AP...", __func__, ifName); + ret = Disconnect(netdev, reasonCode); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:fail to do disconnect,%d", __func__, ret); + } + return ret; +} + +static int32_t WifiCmdScan(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + struct WlanScanRequest params = { 0 }; + int32_t ret; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + ret = WifiFillScanParam(¶ms, reqData); + if (ret != HDF_SUCCESS) { + return ret; + } + + ret = ScanAll(netdev, ¶ms); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:ScanAll failed!ret=%d", __func__, ret); + } + return ret; +} + +static int32_t WifiCmdAbortScan(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + int32_t ret; + const char *ifName = HdfSbufReadString(reqData); + + (void)context; + (void)rspData; + + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + ret = AbortScan(netdev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:AbortScan failed!ret=%d", __func__, ret); + } + + // keep return SUCCESS if AbortScan return FAILED + return HDF_SUCCESS; +} + +static int32_t WifiCmdSetScanningMacAddress(const RequestContext *context, struct HdfSBuf *reqData, + struct HdfSBuf *rspData) +{ + int32_t ret; + uint8_t isFuncValid; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + unsigned char *mac = NULL; + uint32_t replayDataSize; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&mac, &replayDataSize) || mac == NULL || + replayDataSize != IEEE80211_MAC_ADDR_LEN) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "mac"); + return HDF_FAILURE; + } + + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->staOps, SetScanningMacAddress); + + ret = chipDriver->staOps->SetScanningMacAddress(netdev, mac, IEEE80211_MAC_ADDR_LEN); + if (ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT) { + HDF_LOGE("%s: fail to do set scanning mac addr!ret=%d", __func__, ret); + return ret; + } + isFuncValid = (ret == HDF_ERR_NOT_SUPPORT) ? false : true; + if (!HdfSbufWriteUint8(rspData, isFuncValid)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static struct MessageDef g_wifiStaFeatureCmds[] = { + DUEMessage(CMD_STA_CONNECT, WifiCmdAssoc, 0), + DUEMessage(CMD_STA_DISCONNECT, WifiCmdDisconnect, 0), + DUEMessage(CMD_STA_SCAN, WifiCmdScan, 0), + DUEMessage(CMD_STA_ABORT_SCAN, WifiCmdAbortScan, 0), + DUEMessage(CMD_STA_SET_SCAN_MAC_ADDR, WifiCmdSetScanningMacAddress, 0) +}; +ServiceDefine(STAService, STA_SERVICE_ID, g_wifiStaFeatureCmds); + +Service *g_staService = NULL; + +int32_t StaInit(struct WifiFeature *feature) +{ + (void)feature; + if (g_staService == NULL) { + ServiceCfg cfg = { + .dispatcherId = DEFAULT_DISPATCHER_ID + }; + g_staService = CreateService(STAService, &cfg); + if (g_staService == NULL) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t StaDeinit(struct WifiFeature *feature) +{ + (void)feature; + if (g_staService != NULL && g_staService->Destroy != NULL) { + g_staService->Destroy(g_staService); + g_staService = NULL; + } + return HDF_SUCCESS; +} + +struct WifiFeature g_staFeature = { + .name = "sta", + .init = StaInit, + .deInit = StaDeinit +}; + +struct WifiFeature *GetWifiStaFeature(void) +{ + return &g_staFeature; +} + +#ifdef __cplusplus +} +#endif diff --git a/model/network/wifi/core/compoments/sta/sta.h b/model/network/wifi/core/compoments/sta/sta.h new file mode 100644 index 00000000..9bae776b --- /dev/null +++ b/model/network/wifi/core/compoments/sta/sta.h @@ -0,0 +1,24 @@ +/* + * 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 HDFLITE_STA_H +#define HDFLITE_STA_H + +#include "wifi_module.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct WifiFeature *GetWifiStaFeature(void); + +#ifdef __cplusplus +} +#endif + +#endif // HDFLITE_STA_H diff --git a/model/network/wifi/core/hdf_wifi_core.c b/model/network/wifi/core/hdf_wifi_core.c new file mode 100644 index 00000000..32179061 --- /dev/null +++ b/model/network/wifi/core/hdf_wifi_core.c @@ -0,0 +1,548 @@ +/* + * 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 "securec.h" +#include "gpio_if.h" +#include "hdf_wifi_core.h" +#include "devsvc_manager_clnt.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "hdf_wifi_cmd.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "osal_thread.h" +#include "message/message_router.h" +#include "hdf_wlan_chipdriver_manager.h" +#include "hdf_wlan_sdio.h" +#include "hdf_wlan_sdio.h" +#include "hdf_wlan_config.h" +#include "hdf_wlan_utils.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +int32_t HdfWifiGetBusIdx(void) +{ + struct HdfConfigWlanRoot *rootConfig = NULL; + rootConfig = HdfWlanGetModuleConfigRoot(); + if (rootConfig != NULL) { + return rootConfig->wlanConfig.deviceList.deviceInst[0].bus.busIdx; + } + return -1; +} + +/** + * @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) +{ + /* get config vendId, deviceId and chip-name which used in detect match process */ + HdfWlanGetSdioTableByConfig(); + + HdfWlanSdioScanTriggerByBusIndex(busConfig->busIdx); + int ret = HdfWlanGetDetectedChip(data, busConfig); + HdfWlanSdioDriverUnReg(); + if (ret != HDF_SUCCESS) { + return ret; + } + HDF_LOGI("driver name = %s", __func__, data->driverName); + return HDF_SUCCESS; +} + +static int HdfWifiDriverBind(struct HdfDeviceObject *dev) +{ + ErrorCode errCode; + static struct IDeviceIoService wifiService = { + .object.objectId = 1, + .Dispatch = DispatchToMessage, + }; + + if (dev == NULL) { + return HDF_FAILURE; + } + + errCode = StartMessageRouter(MESSAGE_NODE_CONFIG_DEFAULT); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:Start message router failed!", __func__); + return HDF_FAILURE; + } + + errCode = EnableDefaultDispatcher(); + if (errCode != ME_SUCCESS) { + (void)ShutdownMessageRouter(); + HDF_LOGE("%s:EnableDefaultDispatcher failed!", __func__); + return errCode; + } + dev->service = &wifiService; + return HDF_SUCCESS; +} + +static struct HdfConfigWlanDeviceList *HdfWlanGetDeviceList(void) +{ + struct HdfConfigWlanRoot *rootConfig = HdfWlanGetModuleConfigRoot(); + if (rootConfig == NULL) { + HDF_LOGE("%s: HdfWlanGetModuleConfigRoot get failed", __func__); + return NULL; + } + return &rootConfig->wlanConfig.deviceList; +} + +/* CreatePowerMgrByConfig,call by HdfWlanMainInit */ +struct PowerManager *HdfWlanCreatePowerMgrByConfig(void) +{ + struct HdfConfWlanPowers *powerConfig = NULL; + struct HdfConfigWlanRoot *rootConfig = HdfWlanGetModuleConfigRoot(); + if (rootConfig == NULL) { + HDF_LOGE("%s: HdfWlanGetModuleConfigRoot get failed", __func__); + return NULL; + } + powerConfig = &rootConfig->wlanConfig.deviceList.deviceInst[0].powers; + return HdfWlanCreatePowerManager(powerConfig); +} + +struct ResetManager *CreateResetMgrByConfig(void) +{ + uint8_t bootUpTimeOut; + struct HdfConfWlanRest *resetConfig = NULL; + struct HdfConfigWlanRoot *rootConfig = HdfWlanGetModuleConfigRoot(); + if (rootConfig == NULL) { + HDF_LOGE("%s: HdfWlanGetModuleConfigRoot get failed", __func__); + return NULL; + } + resetConfig = &rootConfig->wlanConfig.deviceList.deviceInst[0].reset; + bootUpTimeOut = rootConfig->wlanConfig.deviceList.deviceInst[0].bootUpTimeOut; + return HdfWlanCreateResetManager(resetConfig, bootUpTimeOut); +} + +/* get wlan related config */ +static int32_t HdfWlanGetConfig(const struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%s: input pointer is null", __func__); + return HDF_FAILURE; + } + if (HdfParseWlanConfig(device->property) != HDF_SUCCESS) { + HDF_LOGE("%s:ParseWifiConfig failed!", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t HdfWlanPowerOnProcess(struct PowerManager *powerMgr) +{ + if (powerMgr == NULL) { + HDF_LOGE("%s:Input is NULL!", __func__); + return HDF_FAILURE; + } + + if (powerMgr->On(powerMgr) != HDF_SUCCESS) { + HDF_LOGE("%s:power on failed!", __func__); + return HDF_FAILURE; + } + HDF_LOGW("%s:Chip power on!", __func__); + return HDF_SUCCESS; +} +static int32_t HdfWlanResetProcess(struct ResetManager *resetMgr) +{ + if (resetMgr == NULL) { + HDF_LOGE("%s:input is NULL!", __func__); + return HDF_FAILURE; + } + if (resetMgr->Reset(resetMgr) != HDF_SUCCESS) { + HDF_LOGE("%s:reset failed!", __func__); + return HDF_FAILURE; + } + HDF_LOGW("%s:Chip reset success!", __func__); + return HDF_SUCCESS; +} +static struct HdfChipDriverFactory *HdfWlanGetDriverFactory(const char *driverName) +{ + struct HdfChipDriverManager *initMgr = NULL; + if (driverName == NULL) { + HDF_LOGE("%s: chipName is NULL", __func__); + return NULL; + } + initMgr = HdfWlanGetChipDriverMgr(); + if (initMgr == NULL) { + HDF_LOGE("%s: initMgr is NULL", __func__); + return NULL; + } + return initMgr->GetChipDriverByName(driverName); +} + +static int32_t HdfWlanDeinitInterface(struct HdfWlanDevice *device, const char *ifName, + struct HdfChipDriverFactory *factory) +{ + int ret; + struct NetDevice *netdev = NULL; + struct HdfChipDriver *chipDriver = NULL; + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGW("%s:netif already released!ifName=%s", __func__, ifName); + return HDF_SUCCESS; + } + chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad netdev!ChipDriver is NULL. ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + ret = chipDriver->deinit(chipDriver, netdev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:chip driver deinit failed!ifName=%s", __func__, ifName); + return ret; + } + // check if chip driver released NetDevice + if (NetDeviceGetInstByName(ifName) != NULL) { + ret = ReleasePlatformNetDevice(netdev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:release netdevice failed!ifName=%s", __func__, ifName); + return ret; + } + } else { + HDF_LOGW("%s:chip driver release platform netdevice detected!ifName=%s", __func__, ifName); + } + + if (factory->Release != NULL) { + factory->Release(chipDriver); + } + chipDriver = NULL; + + return HDF_SUCCESS; +} + +static int32_t HdfWlanInitInterface(struct HdfWlanDevice *device, struct HdfChipDriverFactory *factory, uint8_t index) +{ + int32_t ret; + NetDevice *netDev = NULL; + struct HdfChipDriver *chipDriver = NULL; + do { + struct HdfWifiNetDeviceData *data = NULL; + chipDriver = factory->Build(device, index); + if (chipDriver == NULL) { + HDF_LOGE("%s:chip driver %s build fail!", __func__, factory->driverName); + ret = HDF_FAILURE; + break; + } + + if (chipDriver->init == NULL) { + HDF_LOGI("%s: chip driver %s not 'init' api", __func__, factory->driverName); + ret = HDF_DEV_ERR_OP; + break; + } + + netDev = AllocPlatformNetDevice(device); + if (netDev == NULL) { + HDF_LOGE("%s:allocate net device failed!", __func__); + ret = HDF_FAILURE; + break; + } + data = GetPlatformData(netDev); + if (data == NULL) { + HDF_LOGE("%s:platform data is NULL!", __func__); + ret = HDF_FAILURE; + break; + } + data->device = device; + + ret = chipDriver->init(chipDriver, netDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:init chip %s failed! ret=%d", __func__, factory->driverName, ret); + break; + } + + data->chipDriver = chipDriver; + chipDriver = NULL; + } while (false); + + if (ret != HDF_SUCCESS) { + if (chipDriver != NULL && factory->Release != NULL) { + factory->Release(chipDriver); + } + if (netDev != NULL) { + ReleasePlatformNetDevice(netDev); + } + } + return ret; +} + +static int32_t HdfWlanDeinitInterfaces(struct HdfWlanDevice *device, struct HdfChipDriverFactory *chipDriverFact) +{ + int32_t ret = HDF_SUCCESS; + char *ifNames = NULL; + uint8_t ifNameCount = 0; + uint8_t i; + + ifNames = HdfWlanGetIfNames(device->id, &ifNameCount); + if (ifNames == NULL) { + HDF_LOGE("%s: HdfWlanGetIfNames failed!", __func__); + return HDF_FAILURE; + } + + for (i = 0; i < ifNameCount; i++) { + ret = HdfWlanDeinitInterface(device, ifNames + (i * IFNAMSIZ), chipDriverFact); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Deinit netif %s failed!ret=%d", __func__, ifNames + (i * IFNAMSIZ), ret); + break; + } + } + OsalMemFree(ifNames); + ifNames = NULL; + return ret; +} + + +/* build chip driver according to the detected chip and the load factory */ +static int32_t HdfWlanInitInterfaces(struct HdfWlanDevice *device, struct HdfChipDriverFactory *chipDriverFact) +{ + int32_t ret = HDF_SUCCESS; + uint8_t i; + uint8_t maxIFCount = chipDriverFact->GetMaxIFCount(chipDriverFact); + for (i = 0; i < maxIFCount; i++) { + ret = HdfWlanInitInterface(device, chipDriverFact, i); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Init NetInterface failed!driverName=%s,portIndex=%d", __func__, device->driverName, i); + } + } + HDF_LOGI("%s:%s init interfaces finished!", __func__, chipDriverFact->driverName); + return ret; +} + +inline static void ReleaseWlanDevice(struct HdfWlanDevice *device) +{ + if (device->powers != NULL && device->powers->Release != NULL) { + device->powers->Release(device->powers); + device->powers = NULL; + } + if (device->reset != NULL && device->reset->Release != NULL) { + device->reset->Release(device->reset); + device->reset = NULL; + } + OsalMemFree(device); +} + +static struct HdfWlanDevice *ProbeDevice(struct HdfConfigWlanDevInst *deviceConfig) +{ + struct HdfWlanDevice *device = NULL; + int32_t ret; + if (deviceConfig == NULL) { + return NULL; + } + device = (struct HdfWlanDevice *)OsalMemCalloc(sizeof(struct HdfWlanDevice)); + if (device == NULL) { + HDF_LOGE("%s:oom", __func__); + return NULL; + } + do { + device->powers = HdfWlanCreatePowerManager(&deviceConfig->powers); + device->reset = HdfWlanCreateResetManager(&deviceConfig->reset, deviceConfig->bootUpTimeOut); + + ret = HdfWlanPowerOnProcess(device->powers); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:HdfWlanPowerOnProcess failed!", __func__); + break; + } + + ret = HdfWlanResetProcess(device->reset); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:HdfWlanResetProcess failed!", __func__); + break; + } + + ret = HdfWlanSdioScan(device, &deviceConfig->bus); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:NO Sdio Card in hdf wlan init proc", __func__); + break; + } + } while (false); + + if (ret != HDF_SUCCESS) { + ReleaseWlanDevice(device); + return NULL; + } + return device; +} + +int32_t DeinitDevice(struct HdfWlanDevice *device) +{ + struct HdfChipDriverFactory *chipDriverFact = NULL; + int32_t ret; + if (device == NULL) { + HDF_LOGE("%s:Input is NULL!", __func__); + return HDF_FAILURE; + } + chipDriverFact = HdfWlanGetDriverFactory(device->driverName); + if (chipDriverFact == NULL) { + HDF_LOGE("%s: get chipDriverFact failed! driverName=%s", __func__, device->driverName); + return HDF_FAILURE; + } + ret = HdfWlanDeinitInterfaces(device, chipDriverFact); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Deinit interface of device %d failed!ret=%d", __func__, device->id, ret); + return ret; + } + + if (chipDriverFact->DeinitChip != NULL) { + return chipDriverFact->DeinitChip(device); + } + return HDF_SUCCESS; +} + +int32_t InitDevice(struct HdfWlanDevice *device) +{ + int32_t ret; + struct HdfChipDriverFactory *chipDriverFact = NULL; + + chipDriverFact = HdfWlanGetDriverFactory(device->driverName); + if (chipDriverFact == NULL) { + HDF_LOGE("%s: get chipDriverFact failed! driverName=%s", __func__, device->driverName); + return HDF_FAILURE; + } + if (chipDriverFact->InitChip != NULL) { + ret = chipDriverFact->InitChip(device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Init chip failed! ret=%d!", __func__, ret); + return ret; + } + } + + ret = HdfWlanInitInterfaces(device, chipDriverFact); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:init interfaces failed! ret=%d!", __func__, ret); + } else { + HDF_LOGD("%s:init interfaces success! netIfMap=%x.", __func__, device->netIfMap); + } + return ret; +} + +/* thread callback function */ +static int32_t HdfWlanInitThread(void *para) +{ + const uint32_t initDelaySec = 5; + struct HdfDeviceObject *device = (struct HdfDeviceObject *)para; + struct SubscriberCallback callback = { NULL }; + struct HdfConfigWlanDeviceList *devList = NULL; + struct HdfWlanDevice *wlanDevice = NULL; + uint16_t i; + int32_t ret; + + OsalSleep(initDelaySec); + HDF_LOGW("Driver HdfWiFi initing..."); + if (device == NULL) { + return HDF_FAILURE; + } + + devList = HdfWlanGetDeviceList(); + if (devList == NULL) { + HDF_LOGW("%s:No device defined.", __func__); + return HDF_SUCCESS; + } + for (i = 0; i < devList->deviceListSize; i++) { + ret = HdfWlanConfigSDIO(devList->deviceInst[i].bus.busIdx); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:HdfWlanConfigSDIO %d failed!ret=%d", __func__, devList->deviceInst[i].bus.busIdx, ret); + continue; + } + + wlanDevice = ProbeDevice(&(devList->deviceInst[i])); + if (wlanDevice == NULL) { + HDF_LOGE("%s:Device %d detect failed!", __func__, i); + continue; + } + + ret = HdfWlanAddDevice(wlanDevice); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:add device failed!", __func__); + ReleaseWlanDevice(wlanDevice); + continue; + } + + // Load chip driver + (void)DevSvcManagerClntSubscribeService(wlanDevice->driverName, callback); + (void)InitDevice(wlanDevice); + } + + HDF_LOGV("%s:finished.", __func__); + return HDF_SUCCESS; +} +/* load chip factory thread */ +static int32_t HdfWlanScanAndInitThread(struct HdfDeviceObject *device) +{ + struct OsalThread factoryTread; + struct OsalThreadParam chipLoadCfg = { + .name = "chip_factory_load", + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = 0x2000, + }; + + int32_t ret = OsalThreadCreate(&factoryTread, HdfWlanInitThread, (void *)device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to create thread", __func__); + return HDF_ERR_THREAD_CREATE_FAIL; + } + ret = OsalThreadStart(&factoryTread, &chipLoadCfg); + if (ret != HDF_SUCCESS) { + /* lay stress on the use of threadcreate */ + HDF_LOGE("LoadChipFactoryThread: start LoadChipFactoryThread thread fail:%d", ret); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + return HDF_SUCCESS; +} + +/* main init process including config, powers, load the factory, and chip init */ +static int32_t HdfWlanMainInit(struct HdfDeviceObject *device) +{ + struct HdfConfigWlanRoot *rootConfig = NULL; + const struct HdfConfigWlanModuleConfig *moduleConfig = NULL; + + HDF_LOGV("%s:start..", __func__); + if (device == NULL) { + return HDF_FAILURE; + } + if (HdfWlanGetConfig(device) != HDF_SUCCESS) { + HDF_LOGE("%s:HdfWlanGetConfig get wlan config failed!", __func__); + return HDF_FAILURE; + } + /* feature init */ + rootConfig = HdfWlanGetModuleConfigRoot(); + moduleConfig = &rootConfig->wlanConfig.moduleConfig; + if (HdfWlanInitProduct(device, moduleConfig) != HDF_SUCCESS) { + HDF_LOGE("%s:HdfWlanInitProduct failed!", __func__); + return HDF_FAILURE; + } + if (HdfWlanScanAndInitThread(device) != HDF_SUCCESS) { + HDF_LOGE("%s: LoadChipFactoryThread failed, the load process failed!", __func__); + return HDF_FAILURE; + } + HDF_LOGV("%s:finished.", __func__); + return HDF_SUCCESS; +} +/* release the resource created in the init process */ +static void HdfWlanDriverRelease(struct HdfDeviceObject *object) +{ + ErrorCode errCode; + HDF_LOGW("Driver HdfWiFi deiniting..."); + (void)object; + + errCode = ShutdownMessageRouter(); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:shutdown router failed!err=%d", __func__, errCode); + } + HDF_LOGW("Driver HdfWiFi deinited."); +} + +struct HdfDriverEntry g_hdfWifiEntry = { + .moduleVersion = 1, + .Bind = HdfWifiDriverBind, + .Init = HdfWlanMainInit, + .Release = HdfWlanDriverRelease, + .moduleName = "HDF_WIFI" +}; + +HDF_INIT(g_hdfWifiEntry); diff --git a/model/network/wifi/core/hdf_wifi_core.h b/model/network/wifi/core/hdf_wifi_core.h new file mode 100644 index 00000000..c171fd61 --- /dev/null +++ b/model/network/wifi/core/hdf_wifi_core.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 HDF_WIFI_CORE_H +#define HDF_WIFI_CORE_H + +#include "hdf_base.h" +#include "hdf_wifi_product.h" + +#ifdef __cplusplus +extern "C" { +#endif +int32_t HdfWifiGetBusIdx(void); + +int32_t DeinitDevice(struct HdfWlanDevice *device); + +int32_t InitDevice(struct HdfWlanDevice *device); + +#ifdef __cplusplus +} +#endif + +#endif // HDF_WIFI_PRODUCT_H diff --git a/model/network/wifi/core/hdf_wlan_sdio.h b/model/network/wifi/core/hdf_wlan_sdio.h new file mode 100644 index 00000000..553c17fc --- /dev/null +++ b/model/network/wifi/core/hdf_wlan_sdio.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 HDF_WLAN_SDIO_ADAPT_H +#define HDF_WLAN_SDIO_ADAPT_H + +#include "hdf_base.h" +#include "hdf_wifi_product.h" +#include "hdf_wlan_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +void HdfWlanGetSdioTableByConfig(void); +void HdfWlanSdioScanTriggerByBusIndex(int32_t busIdex); +void HdfWlanSdioDriverUnReg(void); +int HdfWlanGetDetectedChip(struct HdfWlanDevice *device, const struct HdfConfigWlanBus *busConfig); + +int32_t HdfWlanConfigSDIO(uint8_t busId); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + + +#endif diff --git a/model/network/wifi/core/module/wifi_base.c b/model/network/wifi/core/module/wifi_base.c new file mode 100644 index 00000000..072e10b7 --- /dev/null +++ b/model/network/wifi/core/module/wifi_base.c @@ -0,0 +1,1252 @@ +/* + * 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 "wifi_base.h" +#include "eapol.h" +#include "hdf_wlan_services.h" +#include "hdf_wlan_utils.h" +#include "hdf_wifi_event.h" +#include "hdf_wlan_chipdriver_manager.h" +#include "hdf_wlan_config.h" +#include "message/message_router.h" +#include "message/sidecar.h" +#include "securec.h" +#include "wifi_mac80211_ops.h" +#include "wifi_module.h" +#include "../hdf_wifi_core.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + +#define WIFI_24G_CHANNEL_NUM 14 +#define DEFAULT_EAPOL_PACKAGE_SIZE 800 + +Service *g_baseService = NULL; + +struct HdfWifiEventToClientMap g_hdfWifiEventToClientMap; +struct HdfWifiEventToClientMap *HdfWifiGetEventToClientMap(void) +{ + return &g_hdfWifiEventToClientMap; +} + +inline static uint32_t EnableEapol(struct NetDevice *netdev, WifiEnableEapol *param) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->enableEapol(netdev, (struct EapolEnable *)param); +} +inline static uint32_t DisableEapol(struct NetDevice *netdev) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->disableEapol(netdev); +} +inline static uint32_t SendEapol(struct NetDevice *netdev, WifiTxEapol *txData) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->sendEapol(netdev, (struct EapolTx *)txData); +} +inline static uint32_t ReceiveEapol(struct NetDevice *netdev, WifiRxEapol *rxData) +{ + const struct Eapol *eapol = EapolGetInstance(); + return eapol->eapolOp->getEapol(netdev, (struct EapolRx *)rxData); +} + +static uint32_t SetMode(struct NetDevice *netDev, uint8_t iftype) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, SetMode); + return chipDriver->ops->SetMode(netDev, iftype); +} + +static uint32_t AddKey(struct NetDevice *netDev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, + struct KeyParams *params) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, AddKey); + return chipDriver->ops->AddKey(netDev, keyIndex, pairwise, macAddr, params); +} + +static uint32_t DelKey(struct NetDevice *netDev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, DelKey); + return chipDriver->ops->DelKey(netDev, keyIndex, pairwise, macAddr); +} + +static uint32_t SetDefaultKey(struct NetDevice *netDev, uint8_t keyIndex, bool unicast, bool multicast) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, SetDefaultKey); + return chipDriver->ops->SetDefaultKey(netDev, keyIndex, unicast, multicast); +} + +static void WifiSetKeyParams(const WifiKeyExt *keyExt, struct KeyParams *params, int8_t *pairwise) +{ + params->key = (uint8_t *)(keyExt->key); + params->keyLen = (int32_t)keyExt->keyLen; + params->seqLen = (int32_t)keyExt->seqLen; + params->seq = keyExt->seq; + params->cipher = keyExt->cipher; + *pairwise = (keyExt->type == WIFI_KEYTYPE_PAIRWISE); +} + +static int32_t WifiCmdNewKey(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netDev = NULL; + struct KeyParams params; + int8_t pairwise; + WifiKeyExt *keyExt = NULL; + uint32_t len = 0; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&keyExt, &len) || keyExt == NULL || len != sizeof(WifiKeyExt)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "keyExt"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->addr), &len)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "addr"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->key), &(keyExt->keyLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "key"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->seq), &(keyExt->seqLen))) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "seq"); + return HDF_FAILURE; + } + netDev = NetDeviceGetInstByName(ifName); + if (netDev == NULL) { + HDF_LOGE("%s:netDev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + (void)memset_s(¶ms, sizeof(struct KeyParams), 0, sizeof(struct KeyParams)); + WifiSetKeyParams(keyExt, ¶ms, &pairwise); + return AddKey(netDev, keyExt->keyIdx, pairwise, keyExt->addr, ¶ms); +} + +static int32_t WifiCmdDelKey(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int8_t pairwise; + struct NetDevice *netDev = NULL; + WifiKeyExt *keyExt = NULL; + uint32_t len = 0; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&keyExt, &len) || keyExt == NULL || len != sizeof(WifiKeyExt)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "keyExt", len); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->addr), &len)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "addr", len); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->key), &(keyExt->keyLen))) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "key", keyExt->keyLen); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->seq), &(keyExt->seqLen))) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "seq", keyExt->seqLen); + return HDF_FAILURE; + } + netDev = NetDeviceGetInstByName(ifName); + if (netDev == NULL) { + HDF_LOGE("%s:netDev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + pairwise = (keyExt->type == WIFI_KEYTYPE_PAIRWISE); + + return DelKey(netDev, keyExt->keyIdx, pairwise, keyExt->addr); +} + +static uint8_t WifiGetMulticast(WifiKeyExt *keyExt) +{ + uint8_t multicast = FALSE; + + if (keyExt->def == TRUE) { + multicast = TRUE; + } + if (keyExt->defMgmt == TRUE) { + multicast = TRUE; + } + if (keyExt->defaultTypes == WIFI_KEY_DEFAULT_TYPE_MULTICAST) { + multicast = TRUE; + } + return multicast; +} + +static int32_t WifiCmdSetKey(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + uint8_t index; + uint8_t unicast; + uint8_t multicast; + struct NetDevice *netDev = NULL; + WifiKeyExt *keyExt = NULL; + uint32_t len = 0; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&keyExt, &len) || keyExt == NULL || len != sizeof(WifiKeyExt)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "keyExt", len); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->addr), &len)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "addr", len); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->key), &(keyExt->keyLen))) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "key", keyExt->keyLen); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&(keyExt->seq), &(keyExt->seqLen))) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "seq", keyExt->seqLen); + return HDF_FAILURE; + } + netDev = NetDeviceGetInstByName(ifName); + if (netDev == NULL) { + HDF_LOGE("%s:netDev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + index = (uint8_t)keyExt->keyIdx; + unicast = TRUE; + multicast = WifiGetMulticast(keyExt); + + return SetDefaultKey(netDev, index, unicast, multicast); +} + +static int32_t WifiCmdSendEapol(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + WifiTxEapol eapol = { 0 }; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + if (!HdfSbufReadBuffer(reqData, (const void **)&(eapol.buf), &(eapol.len))) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "buf", eapol.len); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + return SendEapol(netdev, &eapol); +} + +static int32_t WifiCmdReceiveEapol(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + WifiRxEapol eapol = { 0 }; + const char *ifName = NULL; + int32_t ret; + + (void)context; + if (reqData == NULL || rspData == NULL) { + HDF_LOGE("%s: reqData or rspData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + eapol.len = DEFAULT_EAPOL_PACKAGE_SIZE; + eapol.buf = OsalMemCalloc(DEFAULT_EAPOL_PACKAGE_SIZE); + if (eapol.buf == NULL) { + HDF_LOGE("%s: oom", __func__); + return HDF_FAILURE; + } + + ret = ReceiveEapol(netdev, &eapol); + HDF_LOGI("%s:receiveEapol ret=%d", __func__, ret); + if (!ret) { + if (!HdfSbufWriteBuffer(rspData, eapol.buf, eapol.len)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_ERR_IO; + } + } + OsalMemFree(eapol.buf); + return ret; +} + +static int32_t WifiCmdEnableEapol(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + WifiEnableEapol eapol; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + eapol.callback = (void *)HdfWifiEventEapolRecv; + eapol.contex = NULL; + + return EnableEapol(netdev, &eapol); +} + +static int32_t WifiCmdDisableEapol(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + return DisableEapol(netdev); +} + +static int32_t WifiCmdGetAddr(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + int32_t ret = HDF_SUCCESS; + + (void)context; + if (reqData == NULL || rspData == NULL) { + HDF_LOGE("%s: reqData or rspData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s: invalid netdev", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteBuffer(rspData, netdev->macAddr, ETH_ADDR_LEN)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_ERR_IO; + } + return ret; +} + +static int32_t WifiCmdSetMode(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + + WifiSetMode *mode = NULL; + + const char *ifName = NULL; + uint32_t dataSize = 0; + int32_t ret; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&mode, &dataSize) || mode == NULL || + dataSize != sizeof(WifiSetMode)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "mode", dataSize); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s: invalid netdev", __func__); + return HDF_FAILURE; + } + + HDF_LOGW("%s:%s changing mode to %u ...", __func__, ifName, mode->iftype); + + ret = SetMode(netdev, mode->iftype); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to do change intf,%d", __func__, ret); + } + return ret; +} + +static int32_t WifiFillHwFeature(struct NetDevice *netdev, WifiHwFeatureData *featureData) +{ + int32_t ret = HDF_SUCCESS; + struct WlanHwCapability *capability = GetHwCapability(netdev); + if (capability == NULL) { + HDF_LOGE("%s:GetHwCapability failed!", __func__); + return HDF_FAILURE; + } + do { + uint32_t loop; + if (capability->supportedRateCount > MAX_SUPPORTED_RATE) { + HDF_LOGE("%s: bitrates %d 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]); + 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); + ret = HDF_FAILURE; + break; + } + featureData->channelNum = band->channelCount; + featureData->htCapab = capability->htCapability; + + for (loop = 0; loop < band->channelCount; ++loop) { + featureData->iee80211Channel[loop].flags = band->channels[loop].flags; + featureData->iee80211Channel[loop].freq = band->channels[loop].centerFreq; + featureData->iee80211Channel[loop].channel = band->channels[loop].channelId; + } + } else { + HDF_LOGE("%s: Supportting 2.4G is required by now!", __func__); + ret = HDF_FAILURE; + break; + } + + // 5G not supported + } while (false); + + if (capability->Release != NULL) { + capability->Release(capability); + capability = NULL; + } + return ret; +} + +static uint32_t GetDeviceMacAddr(struct NetDevice *netdev, int32_t type, uint8_t *mac, uint8_t len) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, GetDeviceMacAddr); + + return chipDriver->ops->GetDeviceMacAddr(netdev, type, mac, len); +} + +static uint32_t SetMacAddr(struct NetDevice *netdev, uint8_t *mac, uint8_t len) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, SetMacAddr); + return chipDriver->ops->SetMacAddr(netdev, mac, len); +} + +static uint32_t SetTxPower(struct NetDevice *netdev, int32_t power) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, SetTxPower); + return chipDriver->ops->SetTxPower(netdev, power); +} + +static uint32_t GetValidFreqsWithBand(struct NetDevice *netdev, int32_t band, int32_t *freqs, uint32_t *num) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + + RETURN_IF_CHIPOPS_NOT_IMPLEMENT(chipDriver->ops, GetValidFreqsWithBand); + return chipDriver->ops->GetValidFreqsWithBand(netdev, band, freqs, num); +} + +static int32_t WifiCmdGetHwFeature(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + struct NetDevice *netdev = NULL; + WifiHwFeatureData featureData = { 0 }; + const char *ifName = NULL; + int32_t ret; + + (void)context; + if (reqData == NULL || rspData == NULL) { + HDF_LOGE("%s: reqData or rspData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s: invalid netdev", __func__); + return HDF_FAILURE; + } + + ret = WifiFillHwFeature(netdev, &featureData); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: WifiFillHwFeature failed!ret=%d", __func__, ret); + return HDF_FAILURE; + } + + if (!HdfSbufWriteBuffer(rspData, &featureData, sizeof(featureData))) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_ERR_IO; + } + return ret; +} + +static int32_t SetNetIfInfo(struct NetDevice *netdev, uint32_t type) +{ + int ret = 0; + + if (netdev != NULL) { + ret = netdev->netDeviceIf->open(netdev); + (void)NetIfSetStatus(netdev, NETIF_UP); + } + if (type == WIFI_IFTYPE_AP) { + if (NetIfDhcpsStart(netdev, NULL, 0) == 0) { + HDF_LOGI("dhcp servier start ok."); + } + } + return ret; +} + +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; +} + +static void SetNetworkAddr(struct NetDevice *netdev, uint32_t type) +{ + IpV4Addr ip; + IpV4Addr netmask; + 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 + } else { + ip.addr = 0x010ca8c0UL; // 192, 168, 12, 1 + netmask.addr = 0x00ffffffUL; // 255, 255, 255, 0 + gw.addr = 0x010ca8c0UL; // 192, 168, 12, 1 + } + + if (netdev != NULL) { + NetIfSetAddr(netdev, &ip, &netmask, &gw); + } +} + +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 + + if (netdev != NULL) { + NetIfSetAddr(netdev, &ip, &netmask, &gw); + } +} + +static int32_t WifiCmdSetNetdev(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + WifiSetNewDev *info = NULL; + const char *ifName = NULL; + uint32_t dataSize = 0; + int ret = 0; + struct NetDevice *netdev = NULL; + + (void)context; + (void)rspData; + if (reqData == NULL) { + HDF_LOGE("%s: reqData is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + if (!HdfSbufReadBuffer(reqData, (const void **)&info, &dataSize) || info == NULL || + dataSize != sizeof(WifiSetNewDev)) { + HDF_LOGE("%s: %s!ParamName=%s,readSize=%u", __func__, ERROR_DESC_READ_REQ_FAILED, "devinfo", dataSize); + return HDF_FAILURE; + } + + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL || netdev->netDeviceIf == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + + if (info->status == FALSE && NetDeviceIsInstRunning(netdev) && netdev->netDeviceIf->stop != NULL) { + UnsetNetworkAddr(netdev); + ret = UnsetNetIfInfo(netdev); + } else if (info->status == TRUE && !NetDeviceIsInstRunning(netdev) && netdev->netDeviceIf->open != NULL) { + SetNetworkAddr(netdev, info->ifType); + ret = SetNetIfInfo(netdev, info->ifType); + } + return ret; +} + +static int32_t WifiSendMlme(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)context; + (void)reqData; + (void)rspData; + + return HDF_SUCCESS; +} + +static int32_t WifiCmdSendAction(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)context; + (void)reqData; + (void)rspData; + + return HDF_SUCCESS; +} + +static int32_t WifiCmdGetNetworkInfo(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)context; + (void)reqData; + uint32_t netDevNum = 1; + char *defaultIfName = "wlan0"; + uint8_t supportMode[PROTOCOL_80211_IFTYPE_NUM] = {0}; + + if (!HdfSbufWriteUint32(rspData, netDevNum)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + if (!HdfSbufWriteString(rspData, defaultIfName)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + supportMode[PROTOCOL_80211_IFTYPE_STATION] = 1; + supportMode[PROTOCOL_80211_IFTYPE_AP] = 1; + if (!HdfSbufWriteBuffer(rspData, supportMode, PROTOCOL_80211_IFTYPE_NUM)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdIsSupportCombo(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + uint8_t isComboValid; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + isComboValid = false; + if (!HdfSbufWriteUint8(rspData, isComboValid)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdGetSupportCombo(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)context; + uint8_t isComboValid; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + isComboValid = false; + if (!HdfSbufWriteUint8(rspData, isComboValid)) { + HDF_LOGE("%s: write fail", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdGetDevMacAddr(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + uint8_t isEfuseSavedMac; + int32_t type; + unsigned char devMac[IEEE80211_MAC_ADDR_LEN] = {0}; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadInt32(reqData, &type)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "type"); + return HDF_FAILURE; + } + ret = GetDeviceMacAddr(netdev, type, devMac, IEEE80211_MAC_ADDR_LEN); + if (ret && ret != HDF_ERR_NOT_SUPPORT) { + HDF_LOGE("%s: fail to get device mac addr,%d", __func__, ret); + return ret; + } + isEfuseSavedMac = (ret == HDF_ERR_NOT_SUPPORT) ? false : true; + if (!HdfSbufWriteUint8(rspData, isEfuseSavedMac)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + if (!HdfSbufWriteBuffer(rspData, devMac, IEEE80211_MAC_ADDR_LEN)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdSetMacAddr(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + unsigned char *mac = NULL; + uint32_t replayDataSize; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadBuffer(reqData, (const void **)&mac, &replayDataSize) || mac == NULL || + replayDataSize != IEEE80211_MAC_ADDR_LEN) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "mac"); + return HDF_FAILURE; + } + ret = SetMacAddr(netdev, mac, IEEE80211_MAC_ADDR_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to set mac addr,%d", __func__, ret); + } + return ret; +} + +static int32_t WifiCmdGetValidFreqsWithBand(const RequestContext *context, struct HdfSBuf *reqData, + struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + int32_t band; + int32_t freqs[WIFI_24G_CHANNEL_NUM] = {0}; + uint32_t num = 0; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadInt32(reqData, &band)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "band"); + return HDF_FAILURE; + } + ret = GetValidFreqsWithBand(netdev, band, freqs, &num); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to get valid freqs,%d", __func__, ret); + return ret; + } + if (!HdfSbufWriteUint32(rspData, num)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + if (!HdfSbufWriteBuffer(rspData, freqs, num * sizeof(int32_t))) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + return ret; +} + +static int32_t WifiCmdSetTxPower(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + struct NetDevice *netdev = NULL; + const char *ifName = NULL; + int32_t power; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifName); + return HDF_FAILURE; + } + if (!HdfSbufReadInt32(reqData, &power) || power < 0) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "power"); + return HDF_FAILURE; + } + ret = SetTxPower(netdev, power); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to set tx power,%d", __func__, ret); + } + return ret; +} + +static int32_t WifiCmdSetClient(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + uint32_t clientNum = 0; + + (void)rspData; + if (reqData == NULL || context == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(reqData, &clientNum)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "clientNum"); + return HDF_FAILURE; + } + + struct HdfWifiEventToClientMap *eventToClientMap = HdfWifiGetEventToClientMap(); + if (eventToClientMap == NULL) { + HDF_LOGE("%s:get HdfWifiEventToClientMap failed", __func__); + return HDF_FAILURE; + } + + if (clientNum == WIFI_KERNEL_TO_WPA_CLIENT) { + eventToClientMap->wpaClient = context->client; + } else if (clientNum == WIFI_KERNEL_TO_HAL_CLIENT) { + eventToClientMap->halClient = context->client; + } + return HDF_SUCCESS; +} + +static int32_t HdfdWlanGetChipId(const char *ifName, uint8_t *chipId) +{ + struct NetDevice *netdev = NULL; + struct HdfWifiNetDeviceData *netDeviceData = NULL; + + if (ifName == NULL || chipId == NULL) { + HDF_LOGE("%s: para is NULL", __func__); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s.", __func__, ifName); + return HDF_FAILURE; + } + netDeviceData = GetPlatformData(netdev); + if (netDeviceData == NULL) { + HDF_LOGE("%s:platform netDeviceData is NULL!", __func__); + return HDF_FAILURE; + } + + *chipId = netDeviceData->device->id; + return HDF_SUCCESS; +} + +static int32_t WifiCmdGetChipId(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + const char *ifName = NULL; + uint8_t chipId = 0; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + + ret = HdfdWlanGetChipId(ifName, &chipId); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to get chipId, %d", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: chipid = %d.", __func__, chipId); + if (!HdfSbufWriteUint8(rspData, chipId)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + return ret; +} + +static int32_t WifiCmdGetIfNamesByChipId(const RequestContext *context, struct HdfSBuf *reqData, + struct HdfSBuf *rspData) +{ + uint8_t chipId; + uint8_t ifNameCount = 0; + char *ifNames = NULL; + int32_t ret = HDF_SUCCESS; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(reqData, &chipId)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "chipId"); + return HDF_FAILURE; + } + + ifNames = HdfWlanGetIfNames(chipId, &ifNameCount); + if (ifNames == NULL) { + HDF_LOGE("%s: fail to get ifnames!", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: get ifName num: %d.\n", __func__, ifNameCount); + do { + if (!HdfSbufWriteUint32(rspData, ifNameCount)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_FAILURE; + break; + } + + if (!HdfSbufWriteBuffer(rspData, ifNames, ifNameCount * IFNAMSIZ)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + ret = HDF_FAILURE; + break; + } + } while (false); + if (ifNames != NULL) { + OsalMemFree(ifNames); + } + return ret; +} + +static int32_t WifiResetEntranceCheck(const uint8_t chipId) +{ + uint8_t i; + int32_t ret = HDF_SUCCESS; + uint8_t ifNameCount = 0; + char *ifNames = NULL; + struct NetDevice *netdev = NULL; + + ifNames = HdfWlanGetIfNames(chipId, &ifNameCount); + if (ifNames == NULL) { + HDF_LOGE("%s: HdfWlanGetIfNames failed!", __func__); + return HDF_FAILURE; + } + /* check the netDevice is busy or not, do reset when it is free. */ + for (i = 0; i < ifNameCount; i++) { + netdev = NetDeviceGetInstByName(ifNames + i * IFNAMSIZ); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s", __func__, ifNames + i * IFNAMSIZ); + continue; + } + if (NetDeviceIsInstRunning(netdev)) { + HDF_LOGE("%s: the netdevice is using!", __func__); + ret = ERR_NETDEVICE_IS_USING; + break; + } + } + OsalMemFree(ifNames); + return ret; +} + +static int32_t ResetParaCheck(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + if (context == NULL || reqData == NULL || rspData == NULL) { + HDF_LOGE("%s: para is null!", __func__); + return HDF_FAILURE; + } + + if (context->senderId != BASE_SERVICE_ID) { + HDF_LOGE("%s: the senderId is error!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t WifiCmdDoResetChip(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + uint8_t chipId; + struct HdfWlanDevice *wlanDevice = NULL; + + ret = ResetParaCheck(context, reqData, rspData); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + + if (!HdfSbufReadUint8(reqData, &chipId)) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "chipId"); + return HDF_FAILURE; + } + /* callback function use chipId */ + if (!HdfSbufWriteUint8(rspData, chipId)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + + ret = WifiResetEntranceCheck(chipId); + if (ret != HDF_SUCCESS) { + return ret; + } + + wlanDevice = HdfWlanGetWlanDevice(chipId); + if (wlanDevice == NULL) { + HDF_LOGE("%s: wlanDevice is NULL, not found!", __func__); + return HDF_FAILURE; + } + + ret = DeinitDevice(wlanDevice); + if (ret != HDF_SUCCESS) { + return ret; + } + + /* power reset */ + ret = wlanDevice->reset->Reset(wlanDevice->reset); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:power reset failed!", __func__); + return ERR_POWER_RESET_FAIL; + } + + ret = InitDevice(wlanDevice); + + return ret; +} + +void SendMessageResetDriverCallBack(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData, + ErrorCode rspCode) +{ + uint8_t chipId; + (void)context; + + if (rspData == NULL || reqData == NULL) { + HDF_LOGE("%s: para is null!", __func__); + return; + } + + if (!HdfSbufReadUint8(rspData, &chipId)) { + HDF_LOGE("%s: read data failed! ParamName=%s", __func__, "chipId"); + return; + } + + int32_t ret = HdfWifiEventResetResult(chipId, rspCode); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: send resetDriver event fail!", __func__); + } + return; +} + +static int32_t WifiCmdResetDriver(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + + (void)context; + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + struct HdfSBuf *data = HdfSBufCopy(reqData); + + ret = g_baseService->SendAsyncMessage(g_baseService, BASE_SERVICE_ID, CMD_BASE_DO_RESET_PRIVATE, data, + SendMessageResetDriverCallBack); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to reset the driver,%d", __func__, ret); + } + return ret; +} + +static struct MessageDef g_wifiBaseFeatureCmds[] = { + DUEMessage(CMD_BASE_NEW_KEY, WifiCmdNewKey, 0), + DUEMessage(CMD_BASE_DEL_KEY, WifiCmdDelKey, 0), + DUEMessage(CMD_BASE_SET_DEFAULT_KEY, WifiCmdSetKey, 0), + DUEMessage(CMD_BASE_SEND_MLME, WifiSendMlme, 0), + DUEMessage(CMD_BASE_SEND_EAPOL, WifiCmdSendEapol, 0), + DUEMessage(CMD_BASE_RECEIVE_EAPOL, WifiCmdReceiveEapol, 0), + DUEMessage(CMD_BASE_ENALBE_EAPOL, WifiCmdEnableEapol, 0), + DUEMessage(CMD_BASE_DISABLE_EAPOL, WifiCmdDisableEapol, 0), + DUEMessage(CMD_BASE_GET_ADDR, WifiCmdGetAddr, 0), + DUEMessage(CMD_BASE_SET_MODE, WifiCmdSetMode, 0), + DUEMessage(CMD_BASE_GET_HW_FEATURE, WifiCmdGetHwFeature, 0), + DUEMessage(CMD_BASE_SET_NETDEV, WifiCmdSetNetdev, 0), + DUEMessage(CMD_BASE_SEND_ACTION, WifiCmdSendAction, 0), + DUEMessage(CMD_BASE_SET_CLIENT, WifiCmdSetClient, 0), + DUEMessage(CMD_BASE_GET_NETWORK_INFO, WifiCmdGetNetworkInfo, 0), + DUEMessage(CMD_BASE_IS_SUPPORT_COMBO, WifiCmdIsSupportCombo, 0), + DUEMessage(CMD_BASE_GET_SUPPORT_COMBO, WifiCmdGetSupportCombo, 0), + DUEMessage(CMD_BASE_GET_DEV_MAC_ADDR, WifiCmdGetDevMacAddr, 0), + DUEMessage(CMD_BASE_SET_MAC_ADDR, WifiCmdSetMacAddr, 0), + DUEMessage(CMD_BASE_GET_VALID_FREQ, WifiCmdGetValidFreqsWithBand, 0), + DUEMessage(CMD_BASE_SET_TX_POWER, WifiCmdSetTxPower, 0), + DUEMessage(CMD_BASE_GET_CHIPID, WifiCmdGetChipId, 0), + DUEMessage(CMD_BASE_GET_IFNAMES, WifiCmdGetIfNamesByChipId, 0), + DUEMessage(CMD_BASE_RESET_DRIVER, WifiCmdResetDriver, 0), + DUEMessage(CMD_BASE_DO_RESET_PRIVATE, WifiCmdDoResetChip, 0), +}; +ServiceDefine(BaseService, BASE_SERVICE_ID, g_wifiBaseFeatureCmds); + +int32_t BaseInit() +{ + if (g_baseService == NULL) { + ServiceCfg cfg = { + .dispatcherId = DEFAULT_DISPATCHER_ID + }; + g_baseService = CreateService(BaseService, &cfg); + if (g_baseService == NULL) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t BaseDeinit() +{ + if (g_baseService != NULL && g_baseService->Destroy != NULL) { + g_baseService->Destroy(g_baseService); + g_baseService = NULL; + } + return HDF_SUCCESS; +} diff --git a/model/network/wifi/core/module/wifi_base.h b/model/network/wifi/core/module/wifi_base.h new file mode 100644 index 00000000..0063458a --- /dev/null +++ b/model/network/wifi/core/module/wifi_base.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_WIFI_BASE_H +#define HDF_WIFI_BASE_H + +#include "hdf_device_desc.h" + +#define ERROR_DESC_READ_REQ_FAILED "Read request data failed" +#define ERROR_DESC_WRITE_RSP_FAILED "Write response data failed" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ERR_NETDEVICE_IS_USING (-101) /**< NetDevice is using, can not do reset. */ +#define ERR_DEINIT_DRIVER_FAIL (-102) /**< Deinit driver failed. */ +#define ERR_DEINIT_HI3881CHIP_FAIL (-103) /**< Deinit hi3881 chip failed. */ +#define ERR_POWER_RESET_FAIL (-104) /**< Power reset failed. */ +#define ERR_INIT_DRIVER_FAIL (-105) /**< Init driver failed. */ +#define ERR_INIT_HI3881CHIP_FAIL (-106) /**< Init hi3881 chip failed. */ + +enum WifiClientType { + WIFI_KERNEL_TO_WPA_CLIENT = 0, + WIFI_KERNEL_TO_HAL_CLIENT = 1, + WIFI_CLIENT_BUTT +}; + +struct HdfWifiEventToClientMap { + struct HdfDeviceIoClient *wpaClient; /**< Structure of the Wpa Device Client */ + struct HdfDeviceIoClient *halClient; /**< Structure of the Ifeature Device Client */ +}; + +struct HdfWifiEventToClientMap *HdfWifiGetEventToClientMap(void); + +int32_t BaseInit(void); +int32_t BaseDeinit(void); + +#ifdef __cplusplus +} +#endif +#endif // #ifndef HDF_WIFI_FEATURE_H \ No newline at end of file diff --git a/model/network/wifi/core/module/wifi_feature.c b/model/network/wifi/core/module/wifi_feature.c new file mode 100644 index 00000000..761bb0da --- /dev/null +++ b/model/network/wifi/core/module/wifi_feature.c @@ -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. + */ + +#include "wifi_module.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *feature) +{ + if ((module == NULL) || (feature == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM)) { + HDF_LOGE("%s: para error", __func__); + return HDF_FAILURE; + } + module->feList.fe[featureType] = (struct WifiFeature *)feature; + if (feature->init != NULL) { + return feature->init(feature); + } + + HDF_LOGE("%s: feature has no init", __func__); + return HDF_FAILURE; +} + +int32_t DelFeature(struct WifiModule *module, uint16_t featureType) +{ + struct WifiFeature *featureData = NULL; + if ((module == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM)) { + HDF_LOGE("%s: para error", __func__); + return HDF_FAILURE; + } + + featureData = module->feList.fe[featureType]; + if ((featureData != NULL) && (featureData->deInit != NULL)) { + featureData->deInit(module->feList.fe[featureType]); + featureData = NULL; + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +#ifdef __cplusplus +} +#endif diff --git a/model/network/wifi/core/module/wifi_module.c b/model/network/wifi/core/module/wifi_module.c new file mode 100644 index 00000000..061478f0 --- /dev/null +++ b/model/network/wifi/core/module/wifi_module.c @@ -0,0 +1,98 @@ +/* + * 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 "wifi_module.h" +#include "wifi_base.h" +#include "ap.h" +#include "sta.h" +#include "hdf_wlan_config.h" +#include "securec.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t DelFeature(struct WifiModule *module, uint16_t featureType); +int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData); + +static int32_t InitFeatures(struct WifiModule *module) +{ + int32_t ret; + uint32_t i; + + if (module == NULL) { + HDF_LOGE("%s: input module is NULL", __func__); + return HDF_FAILURE; + } + ret = BaseInit(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:BaseInit failed!ret=%d", __func__, ret); + return ret; + } + + module->feList.fe[HDF_WIFI_FEATURE_AP] = GetWifiApFeature(); + module->feList.fe[HDF_WIFI_FEATURE_STA] = GetWifiStaFeature(); + + for (i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { + if ((module->moduleConfig.hslConfig->featureMap & (1 << i)) && module->feList.fe[i] != NULL) { + module->feList.fe[i]->init(module->feList.fe[i]); + } + } + return HDF_SUCCESS; +} + +static int32_t DeInitFeatures(struct WifiModule *module) +{ + int32_t ret; + uint32_t i; + if (module == NULL) { + HDF_LOGE("%s: no module", __func__); + return HDF_FAILURE; + } + // make sure the features should be free firstly + for (i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { + if ((module->feList.fe[i] != NULL) && (module->feList.fe[i]->deInit != NULL)) { + module->feList.fe[i]->deInit(module->feList.fe[i]); + module->feList.fe[i] = NULL; + } + } + + ret = BaseDeinit(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:BaseDeinit failed!ret=%d", __func__, ret); + } + return ret; +} + +int16_t InitWifiModule(struct WifiModule *module, const struct HdfConfigWlanModuleConfig *config) +{ + int32_t ret; + if (module == NULL || config == NULL) { + HDF_LOGE("%s:Input is NULL!", __func__); + return HDF_FAILURE; + } + module->iface.deInit = DeInitFeatures; + module->iface.addFeature = AddFeature; + module->iface.delFeature = DelFeature; + module->modulePrivate = NULL; + module->moduleConfig.hslConfig = config; + + ret = InitFeatures(module); + if (ret != 0) { + HDF_LOGE("%s: module int error ret=%d", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGD("%s:hdf wifi module init succ", __func__); + return HDF_SUCCESS; +} + +#ifdef __cplusplus +} +#endif diff --git a/model/network/wifi/include/hdf_wifi_cmd.h b/model/network/wifi/include/hdf_wifi_cmd.h old mode 100755 new mode 100644 index 1199ea86..aee3f941 --- a/model/network/wifi/include/hdf_wifi_cmd.h +++ b/model/network/wifi/include/hdf_wifi_cmd.h @@ -1,40 +1,17 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 _WIFI_HAL_H_ -#define _WIFI_HAL_H_ +#ifndef HDF_WIFI_CMD_H +#define HDF_WIFI_CMD_H -#include +#include "hdf_base.h" #include -#include +#include "net_device.h" #include "hdf_device_desc.h" #include "hdf_sbuf.h" @@ -104,55 +81,6 @@ typedef enum { WIFI_HIDDEN_SSID_ZERO_CONTENTS } WifiHiddenSsid; -typedef enum { - WIFI_WPA_CMD_SET_AP = 0, - WIFI_WPA_CMD_NEW_KEY, - WIFI_WPA_CMD_DEL_KEY, - WIFI_WPA_CMD_SET_KEY, - WIFI_WPA_CMD_SEND_MLME, - WIFI_WPA_CMD_SEND_EAPOL = 5, - WIFI_WPA_CMD_RECEIVE_EAPOL, - WIFI_WPA_CMD_ENALBE_EAPOL, - WIFI_WPA_CMD_DISABLE_EAPOL, - WIFI_WPA_CMD_GET_ADDR, - WIFI_WPA_CMD_SET_POWER = 10, - WIFI_WPA_CMD_SET_MODE, - WIFI_WPA_CMD_GET_HW_FEATURE, - WIFI_WPA_CMD_STOP_AP, - WIFI_WPA_CMD_DEL_VIRTUAL_INTF, - WIFI_WPA_CMD_SCAN = 15, - WIFI_WPA_CMD_DISCONNECT, - WIFI_WPA_CMD_ASSOC, - WIFI_WPA_CMD_SET_NETDEV, - WIFI_WPA_CMD_SET_AP_WPS_P2P_IE, - WIFI_WPA_CMD_CHANGE_BEACON = 20, - WIFI_WPA_CMD_DHCP_START, - WIFI_WPA_CMD_DHCP_STOP, - WIFI_WPA_CMD_DHCP_SUCC_CHECK, - WIFI_WPA_CMD_SET_REKEY_INFO, - WIFI_WPA_CMD_SET_PM_ON = 25, - WIFI_WPA_CMD_IP_NOTIFY_DRIVER, - WIFI_WPA_CMD_SET_MAX_STA, - WIFI_WPA_CMD_STA_REMOVE, - WIFI_WPA_CMD_SEND_ACTION, - WIFI_WPA_CMD_SET_MESH_USER = 30, - WIFI_WPA_CMD_SET_MESH_GTK, - WIFI_WPA_CMD_EN_AUTO_PEER, - WIFI_WPA_CMD_EN_ACCEPT_PEER, - WIFI_WPA_CMD_EN_ACCEPT_STA, - WIFI_WPA_CMD_ADD_IF = 35, - WIFI_WPA_CMD_PROBE_REQUEST_REPORT, - WIFI_WPA_CMD_REMAIN_ON_CHANNEL, - WIFI_WPA_CMD_CANCEL_REMAIN_ON_CHANNEL, - WIFI_WPA_CMD_SET_P2P_NOA, - WIFI_WPA_CMD_SET_P2P_POWERSAVE = 40, - WIFI_WPA_CMD_REMOVE_IF, - WIFI_WPA_CMD_GET_P2P_MAC_ADDR, - WIFI_WPA_CMD_GET_DRIVER_FLAGS, - WIFI_WPA_CMD_SET_USR_APP_IE, - WIFI_WPA_CMD_BUTT -} WifiWPACmdType; - typedef enum { WIFI_WPA_EVENT_NEW_STA = 0, WIFI_WPA_EVENT_DEL_STA, @@ -169,6 +97,7 @@ typedef enum { WIFI_WPA_EVENT_CHANNEL_SWITCH, WIFI_WPA_EVENT_EAPOL_RECV, WIFI_WPA_EVENT_TIMEOUT_DISCONN, + WIFI_WPA_EVENT_RESET_DRIVER = 15, WIFI_WPA_EVENT_BUTT } WifiWpaEventType; @@ -223,6 +152,10 @@ typedef struct { WifiPhyMode mode; } WifiSetNewDev; +typedef struct { + uint8_t mac[ETH_ADDR_LEN]; +} WifiStaInfo; + typedef struct { int32_t numRates; int32_t mode; @@ -354,9 +287,11 @@ typedef struct { uint32_t flags; } WifiIeee80211Channel; +#define MAX_SUPPORTED_RATE 12 + typedef struct { int32_t channelNum; - uint16_t bitrate[12]; + uint16_t bitrate[MAX_SUPPORTED_RATE]; uint16_t htCapab; uint8_t resv[2]; WifiIeee80211Channel iee80211Channel[14]; @@ -478,8 +413,6 @@ typedef enum { WIFI_CHAN_NO_160MHZ = 1 << 8, } WifiChannelFlags; -int32_t WifiCmdProcess(struct HdfDeviceObject *device, int32_t cmd, struct HdfSBuf *reqData, struct HdfSBuf *rspData); - #ifdef __cplusplus #if __cplusplus } diff --git a/model/network/wifi/include/hdf_wifi_config.h b/model/network/wifi/include/hdf_wifi_config.h old mode 100755 new mode 100644 index 89ffaf4e..9dd4d937 --- a/model/network/wifi/include/hdf_wifi_config.h +++ b/model/network/wifi/include/hdf_wifi_config.h @@ -1,38 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_WIFI_CONFIG_HEADER_H #define HDF_WIFI_CONFIG_HEADER_H -#include +#include "hdf_base.h" #include "device_resource_if.h" #define WIFI_CONFIG_NAME_MAX 20 diff --git a/model/network/wifi/include/hdf_wlan_config.h b/model/network/wifi/include/hdf_wlan_config.h new file mode 100644 index 00000000..16bfac3e --- /dev/null +++ b/model/network/wifi/include/hdf_wlan_config.h @@ -0,0 +1,126 @@ +/* + * 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_WLAN_CONFIG_H +#define HDF_WLAN_CONFIG_H + +#include "device_resource_if.h" +#define WLAN_DEVICE_MAX 3 +#define WLAN_MAX_CHIP_NUM 3 +#define BUS_FUNC_MAX 1 +#define CHIP_SDIO_DEVICE_ID_COUNT 1 + +struct HdfConfigWlanStation { + const char *name; + uint8_t mode; +}; + +struct HdfConfigWlanHostAp { + const char *name; + uint8_t mode; + uint8_t vapResNum; + uint8_t userResNum; +}; + +struct HdfConfigWlanP2P { + const char *name; + uint8_t mode; +}; + +struct HdfConfigWlanMac80211 { + uint8_t mode; +}; + +struct HdfConfigWlanPhy { + uint8_t mode; +}; + +struct HdfConfigWlanModuleConfig { + uint32_t featureMap; + const char *msgName; + struct HdfConfigWlanStation station; + struct HdfConfigWlanHostAp hostAp; + struct HdfConfigWlanP2P p2p; + struct HdfConfigWlanMac80211 mac80211; + struct HdfConfigWlanPhy Phy; +}; + +/* ----------------------------------------------* + * deviceList architecture * + * ---------------------------------------------- */ +struct HdfConfigWlanPower { + uint8_t powerSeqDelay; + uint8_t powerType; + uint8_t gpioId; + uint8_t activeLevel; +}; + + +struct HdfConfWlanPowers { + uint8_t powerCount; + struct HdfConfigWlanPower power0; + struct HdfConfigWlanPower power1; +}; + +struct HdfConfWlanRest { + uint8_t resetType; + uint8_t gpioId; + uint8_t activeLevel; + uint8_t resetHoldTime; +}; + +struct HdfConfigWlanBus { + uint8_t busType; + uint8_t busIdx; + uint8_t funcNum[BUS_FUNC_MAX]; + uint32_t funcNumSize; + uint16_t timeout; + uint16_t blockSize; +}; + +struct HdfConfigWlanDevInst { + uint8_t deviceInstId; + struct HdfConfWlanPowers powers; + struct HdfConfWlanRest reset; + struct HdfConfigWlanBus bus; + uint8_t bootUpTimeOut; +}; + +struct HdfConfigWlanDeviceList { + struct HdfConfigWlanDevInst deviceInst[WLAN_DEVICE_MAX]; + uint16_t deviceListSize; +}; +/* ----------------------------------------------* + * chip config * + * ---------------------------------------------- */ +struct HdfConfWlanSdioArgs { + uint16_t vendorId; + uint16_t deviceId[1]; +}; +struct HdfConfigWlanChipInst { + const char *driverName; + struct HdfConfWlanSdioArgs chipSdio; +}; +struct HdfConfigWlanChipList { + struct HdfConfigWlanChipInst chipInst[WLAN_MAX_CHIP_NUM]; + uint16_t chipInstSize; +}; + +struct HdfConfigWlanConfig { + const char* hostChipName; + struct HdfConfigWlanModuleConfig moduleConfig; + struct HdfConfigWlanDeviceList deviceList; + struct HdfConfigWlanChipList chipList; +}; +struct HdfConfigWlanRoot { + struct HdfConfigWlanConfig wlanConfig; +}; + +struct HdfConfigWlanRoot *HdfWlanGetModuleConfigRoot(void); +int32_t HdfParseWlanConfig(const struct DeviceResourceNode *node); + +#endif \ No newline at end of file diff --git a/model/network/wifi/module/wifi_base.c b/model/network/wifi/module/wifi_base.c deleted file mode 100755 index 4b029e3a..00000000 --- a/model/network/wifi/module/wifi_base.c +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "wifi_module.h" -#include "ap.h" -#include "eapol.h" -#include "sta.h" -#include "wifi_mac80211_ops.h" - - -struct WifiBaseFeature g_baseFeature; - -int32_t BaseInit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -int32_t BaseDeinit(struct WifiFeature *feature) -{ - (void)feature; - return HDF_SUCCESS; -} - -static uint32_t EnableEapol(struct NetDevice *netdev, WifiEnableEapol *param) -{ - const struct Eapol *eapol = EapolGetInstance(); - return eapol->eapolOp->enableEapol(netdev, (struct EapolEnable *)param); -} -static uint32_t DisableEapol(struct NetDevice *netdev) -{ - const struct Eapol *eapol = EapolGetInstance(); - return eapol->eapolOp->disableEapol(netdev); -} -static uint32_t SendEapol(struct NetDevice *netdev, WifiTxEapol *txData) -{ - const struct Eapol *eapol = EapolGetInstance(); - return eapol->eapolOp->sendEapol(netdev, (struct EapolTx *)txData); -} -static uint32_t ReceiveEapol(struct NetDevice *netdev, WifiRxEapol *rxData) -{ - const struct Eapol *eapol = EapolGetInstance(); - return eapol->eapolOp->getEapol(netdev, (struct EapolRx *)rxData); -} - -static uint32_t ChangeVirtualIntf(struct NetDevice *netDev, uint8_t iftype, uint32_t *flags, - struct VifParams *params) -{ - struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, changeVirtualIntf); - return macOps->changeVirtualIntf(netDev, iftype, flags, params); -} - -static uint32_t AddKey(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr, - struct KeyParams *params) -{ - struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, addKey); - return macOps->addKey(netdev, keyIndex, pairwise, macAddr, params); -} - -static uint32_t DelKey(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr) -{ - struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, delKey); - return macOps->delKey(netdev, keyIndex, pairwise, macAddr); -} - -static uint32_t SetDefaultKey(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicast) -{ - struct WifiMac80211Ops *macOps = g_baseFeature.fe.chip->ops; - RETURN_IF_MACOPS_NOT_REGISTERED(macOps); - RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, setDefaultKey); - return macOps->setDefaultKey(netdev, keyIndex, unicast, multicast); -} - -static uint32_t SetDefaultMgmtKey(struct NetDevice *netdev, uint8_t keyIndex) -{ - (void)netdev; - (void)keyIndex; - return HDF_SUCCESS; -} - -struct WifiBaseFeature g_baseFeature = { - .fe = { - .name = "base", - .init = BaseInit, - .deInit = BaseDeinit, - }, - .ops = { - .enableEapol = EnableEapol, - .disableEapol = DisableEapol, - .sendEapol = SendEapol, - .receiveEapol = ReceiveEapol, - .changeVirtualIntf = ChangeVirtualIntf, - .addKey = AddKey, - .delKey = DelKey, - .setDefaultKey = SetDefaultKey, - .setDefaultMgmtKey = SetDefaultMgmtKey, - } -}; - -struct WifiFeatureList g_featureList = { 0 }; - -int32_t InitFeatures(struct WifiModule *module) -{ - if (module == NULL) { - HDF_LOGE("%s: error, no module", __func__); - return HDF_FAILURE; - } - - g_featureList.fe[HDF_WIFI_FEATURE_BASE] = (struct WifiFeature *)&g_baseFeature; - g_featureList.fe[HDF_WIFI_FEATURE_AP] = GetWifiApFeatureDelc(); - g_featureList.fe[HDF_WIFI_FEATURE_STA] = GetWifiStaFeatureDelc(); - - module->feList = &g_featureList; - - for (uint32_t i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { - if ((module->moduleConfig.hslConfig->featureMap & (1 << i)) && module->feList->fe[i] != NULL) { - module->feList->fe[i]->init(module->feList->fe[i]); - } - } - return HDF_SUCCESS; -} - -struct WifiBaseFeature *WifiBaseGetFeature(const struct WifiModule *module) -{ - return (struct WifiBaseFeature *)GetFeature(module, HDF_WIFI_FEATURE_BASE); -} diff --git a/model/network/wifi/module/wifi_base.h b/model/network/wifi/module/wifi_base.h deleted file mode 100755 index fb7c443c..00000000 --- a/model/network/wifi/module/wifi_base.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _HDF_WIFI_FEATURE_H_ -#define _HDF_WIFI_FEATURE_H_ - -#include "wifi_module.h" -#include "hdf_wifi_cmd.h" -#include "net_device.h" -#include "wifi_mac80211_ops.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct WiFiBaseFeatureOps { - uint32_t (*enableEapol)(struct NetDevice *netdev, WifiEnableEapol *param); - uint32_t (*disableEapol)(struct NetDevice *netdev); - uint32_t (*sendEapol)(struct NetDevice *netdev, WifiTxEapol *txData); - uint32_t (*receiveEapol)(struct NetDevice *netdev, WifiRxEapol *rxData); - uint32_t (*changeVirtualIntf)(struct NetDevice *netdev, uint8_t iftype, uint32_t *flags, - struct VifParams *params); - uint32_t (*addKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *mac_addr, - struct KeyParams *params); - uint32_t (*delKey)(struct NetDevice *netdev, uint8_t keyIndex, bool pairwise, const uint8_t *macAddr); - uint32_t (*setDefaultKey)(struct NetDevice *netdev, uint8_t keyIndex, bool unicast, bool multicast); - uint32_t (*setDefaultMgmtKey)(struct NetDevice *netdev, uint8_t keyIndex); -} WiFiBaseFeatureOps; - -struct WifiBaseFeature { - struct WifiFeature fe; - WiFiBaseFeatureOps ops; -}; - - -struct WifiModule *HdfGetWifiModule(void); -struct WifiBaseFeature *WifiBaseGetFeature(const struct WifiModule *module); -struct WifiFeature *GetFeature(const struct WifiModule *module, uint16_t featureType); -int32_t DeInitFeatures(struct WifiModule *module); -int32_t InitFeatures(struct WifiModule *module); - -#define RETURN_IF_MACOPS_NOT_IMPLEMENT(macOps, opsName) do { \ - if (macOps->opsName == NULL) { \ - HDF_LOGE("macOps" #opsName "not implement"); \ - return HDF_ERR_INVALID_OBJECT; \ - } \ - } while (0) - -#define RETURN_IF_MACOPS_NOT_REGISTERED(macOps) do { \ - if (macOps == NULL) { \ - HDF_LOGE("macOps not registered"); \ - return HDF_ERR_INVALID_OBJECT; \ - } \ - } while (0) - -#ifdef __cplusplus -} -#endif -#endif // #ifndef _HDF_WIFI_FEATURE_H_ \ No newline at end of file diff --git a/model/network/wifi/module/wifi_feature.c b/model/network/wifi/module/wifi_feature.c deleted file mode 100755 index 706527bd..00000000 --- a/model/network/wifi/module/wifi_feature.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include "wifi_module.h" - -#if __cplusplus -extern "C" { -#endif - -struct WifiFeature *GetFeature(const struct WifiModule *module, uint16_t featureType) -{ - if ((module == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) || (module->feList == NULL)) { - return NULL; - } - return module->feList->fe[featureType]; -} - -int32_t AddFeature(struct WifiModule *module, uint16_t featureType, struct WifiFeature *featureData) -{ - if ((module == NULL) || (featureData == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) - || (module->feList == NULL)) { - HDF_LOGE("%s: para error", __func__); - return HDF_FAILURE; - } - module->feList->fe[featureType] = (struct WifiFeature *)featureData; - if (featureData->init != NULL) { - return featureData->init(featureData); - } - - HDF_LOGE("%s: featureData null", __func__); - return HDF_FAILURE; -} - -int32_t DelFeature(struct WifiModule *module, uint16_t featureType) -{ - struct WifiFeature *featureData = NULL; - if ((module == NULL) || (featureType >= HDF_WIFI_FEATURE_NUM) || (module->feList == NULL)) { - HDF_LOGE("%s: para error", __func__); - return HDF_FAILURE; - } - - featureData = module->feList->fe[featureType]; - if ((featureData != NULL) && (featureData->deInit != NULL)) { - featureData->deInit(module->feList->fe[featureType]); - featureData = NULL; - return HDF_SUCCESS; - } - return HDF_FAILURE; -} - -int32_t DeInitFeatures(struct WifiModule *module) -{ - if ((module == NULL) || (module->feList == NULL)) { - HDF_LOGE("%s: no module", __func__); - return HDF_FAILURE; - } - // make sure the features should be free firstly - for (int32_t i = 0; i < HDF_WIFI_FEATURE_NUM; i++) { - if ((module->feList->fe[i] != NULL) && (module->feList->fe[i]->deInit != NULL)) { - module->feList->fe[i]->deInit(module->feList->fe[i]); - } - } - - return HDF_SUCCESS; -} - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/model/network/wifi/module/wifi_module.c b/model/network/wifi/module/wifi_module.c deleted file mode 100755 index 60dff60a..00000000 --- a/model/network/wifi/module/wifi_module.c +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "wifi_module.h" -#include "wifi_base.h" -#include "hdf_wifi_product.h" -#include "securec.h" -#if __cplusplus -extern "C" { -#endif - -struct WifiModule *HdfGetWifiModule(void) -{ - struct HdfWifiProductData *productData = HdfWifiGetProduct(); - - if (productData == NULL) { - return NULL; - } - return productData->module; -} - -int32_t UpdateWiFiModule(struct WifiModule *module) -{ - (void)module; - return HDF_SUCCESS; -} - -void WifiModuleDelete(struct WifiModule *module) -{ - if (module == NULL) { - return; - } - if ((module->iface != NULL) && (module->iface->deInit != NULL)) { - module->iface->deInit(module); - OsalMemFree(module->iface); - } - - OsalMemFree(module); - return; -} - -struct WifiModule *WifiModuleCreate(const struct HdfConfigWifiModuleConfig *config) -{ - int32_t ret; - struct WifiModuleIface *iface = NULL; - struct WifiModule *module = OsalMemAlloc(sizeof(*module)); - if (module == NULL) { - HDF_LOGE("%s: no memory for module", __func__); - goto error; - } - (void)memset_s(module, sizeof(*module), 0, sizeof(*module)); - - iface = OsalMemAlloc(sizeof(*iface)); - if (iface == NULL) { - HDF_LOGE("%s: no memory for module iface", __func__); - goto error; - } - - iface->init = InitFeatures; - iface->deInit = DeInitFeatures; - iface->updateModule = UpdateWiFiModule; - iface->addFeature = AddFeature; - iface->delFeature = DelFeature; - module->modulePrivate = NULL; - module->iface = iface; - module->moduleConfig.hslConfig = config; - - ret = module->iface->init(module); - if (ret != 0) { - HDF_LOGE("%s: module int error ret=%d", __func__, ret); - goto error; - } - return module; -error: - WifiModuleDelete(module); - return NULL; -} - -#ifdef __cplusplus -} -#endif - diff --git a/model/network/wifi/netdevice/net_device_impl.h b/model/network/wifi/netdevice/net_device_impl.h deleted file mode 100755 index ec5080e4..00000000 --- a/model/network/wifi/netdevice/net_device_impl.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef HDF_NET_DEVICE_IMPL_MODULE_H -#define HDF_NET_DEVICE_IMPL_MODULE_H - -#include -#include -#include -#include "net_device.h" - -#define MAX_NETDEVICE_COUNT 20 - -struct NetDeviceImpl { - struct NetDevice *netDevice; - struct NetDeviceImplOp *interFace; - void *osPrivate; -}; -typedef enum { - NO_IN_INTERRUPT, - IN_INTERRUPT, - MAX_RECEIVE_FLAGE -} ReceiveFlage; - -struct NetDeviceImplOp { - int32_t (*init)(struct NetDeviceImpl *netDevice); - int32_t (*deInit)(struct NetDeviceImpl *netDevice); - int32_t (*add)(struct NetDeviceImpl *netDevice, Protocol80211IfType ifType); - int32_t (*delete)(struct NetDeviceImpl *netDevice); - int32_t (*setStatus)(struct NetDeviceImpl *netDevice, NetIfStatus status); - int32_t (*setLinkStatus)(struct NetDeviceImpl *netDevice, NetIfLinkStatus status); - int32_t (*receive)(struct NetDeviceImpl *netDevice, struct NetBuf *buff, ReceiveFlage flage); - int32_t (*setIpAddr)(struct NetDeviceImpl *netDevice, const IpV4Addr *ipAddr, const IpV4Addr *netMask, - const IpV4Addr *gw); - int32_t (*dhcpsStart)(struct NetDeviceImpl *netDevice, char *ip, uint16_t ipNum); - int32_t (*dhcpsStop)(struct NetDeviceImpl *netDevice); - int32_t (*dhcpStart)(struct NetDeviceImpl *netDevice); - int32_t (*dhcpStop)(struct NetDeviceImpl *netDevice); - int32_t (*dhcpIsBound)(struct NetDeviceImpl *netDevice); -}; - -#endif /* HDF_NET_DEVICE_IMPL_MODULE_H */ \ No newline at end of file diff --git a/model/network/wifi/platform/include/flow_control.h b/model/network/wifi/platform/include/flow_control.h new file mode 100644 index 00000000..c6e0603e --- /dev/null +++ b/model/network/wifi/platform/include/flow_control.h @@ -0,0 +1,364 @@ +/* + * 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. + */ + +/** + * @addtogroup WLAN + * @{ + * + * @brief Provides cross-OS migration, component adaptation, and modular assembly and compilation. + * + * Based on the unified APIs provided by the WLAN module, developers of the Hardware Driver Interface + * (HDI) are capable of creating, disabling, scanning for, and connecting to WLAN hotspots, managing WLAN chips, + * network devices, and power, and applying for, releasing, and moving network data buffers. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file flow_control.h + * + * @brief Declares flow control modules and provides functions such as initializing and deinitializing a + * flow control module, and transmitting and receiving data packets based on the flow control priority. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef WIFI_FLOW_CONTROL_H +#define WIFI_FLOW_CONTROL_H +#include "osal_sem.h" +#include "osal_spinlock.h" +#include "osal_thread.h" +#include "hdf_netbuf.h" + +/** + * @brief Enumerates flow control queue IDs. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + CTRL_QUEUE_ID = 0, /**< Control queue ID */ + VIP_QUEUE_ID, /**< VIP queue ID */ + NORMAL_QUEUE_ID, /**< Normal queue ID */ + TCP_DATA_QUEUE_ID, /**< TCP data queue ID */ + TCP_ACK_QUEUE_ID, /**< TCP ACK queue ID */ + BK_QUEUE_ID, /**< Background flow queue ID */ + BE_QUEUE_ID, /**< Best-effort flow queue ID */ + VI_QUEUE_ID, /**< Video flow queue ID */ + VO_QUEUE_ID, /**< Voice flow queue ID */ + QUEUE_ID_COUNT /**< Total number of queue IDs */ +} FlowControlQueueID; + +/** + * @brief Enumerates flow directions. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + FLOW_TX = 0, /**< Transmit */ + FLOW_RX, /**< Receive */ + FLOW_DIR_COUNT /**< Total number of flow directions */ +} FlowDir; + +/** + * @brief Enumerates flow control thread statuses. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + THREAD_INIT_FAIL = 0, /**< Failed to initialize */ + THREAD_INIT_SUCCESS, /**< Initialized successfully */ + THREAD_STARTING, /**< Starting */ + THREAD_WAITING, /**< Waiting */ + THREAD_RUNNING, /**< Running */ + THREAD_STOPPING, /**< Stopping */ + THREAD_STOPPED, /**< Stopped */ + THREAD_DESTROYED, /**< Destroyed */ + THREAD_STATUS_COUNT /**< Total number of thread statuses */ +}FcThreadStatus; + +/** + * @brief Describes a flow control queue. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlQueue { + FlowControlQueueID queueID; /**< Flow control queue ID */ + NetBufQueue dataQueue; /**< Network data queue */ + uint32_t queueThreshold; /**< Network data queue threshold */ + OsalSpinlock lock; /**< Queue lock */ + uint32_t pktCount; /**< Number of packets received by the network data queue */ +}; + +/** + * @brief Manages flow control queues. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlQueues { + struct FlowControlQueue queues[QUEUE_ID_COUNT]; /**< Array of flow control queues */ +}; + + +/** + * @brief Provides flow control operations. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlOp { + /** + * @brief Checks whether the device is a station or P2P client. + * + * @return Returns true if the device is a station or P2P client; returns false otherwise. + * + * @since 1.0 + * @version 1.0 + */ + bool (*isDeviceStaOrP2PClient)(void); + + /** + * @brief Transmits data packets. + * + * @param q Indicates the pointer to the network data queue. + * @param fcmPrivate Indicates the pointer to the private structure in the WLAN driver for + * transmitting data packets. + * @param fwPriorityId Indicates the ID of the flow control priority. + * @return Returns 0 if data packets are transmitted; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*txDataPacket)(NetBufQueue *q, void *fcmPrivate, int32_t fwPriorityId); + + /** + * @brief Receives data packets. + * + * @param q Indicates the pointer to the network data queue. + * @param fcmPrivate Indicates the pointer to the private structure in the WLAN driver for receiving data packets. + * @param fwPriorityId Indicates the ID of the flow control priority. + * @return Returns 0 if data packets are received; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*rxDataPacket)(NetBufQueue *q, void *fcmPrivate, int32_t fwPriorityId); + + /** + * @brief Obtains the transmit flow control queue ID defined by the driver vendor. + * + * @param para Indicates the pointer to the structure defined by the driver and used to obtain the transmit + * flow control queue ID. + * @return Returns the pointer to the transmit flow control queue ID, as enumerated in {@link FlowControlQueueID}. + * + * @since 1.0 + * @version 1.0 + */ + FlowControlQueueID (*getTxQueueId)(const void *para); + + /** + * @brief Obtains the receive flow control queue ID defined by the driver vendor. + * + * @param para Indicates the pointer to the structure defined by the driver and used to obtain the receive + * flow control queue ID. + * @return Returns the pointer to the receive flow control queue ID, as enumerated in {@link FlowControlQueueID}. + * + * @since 1.0 + * @version 1.0 + */ + FlowControlQueueID (*getRxQueueId)(const void *para); + + /** + * @brief Obtains the ID of the priority of a specified transmit flow control queue. + * + * @param id Indicates the ID of the transmit flow control queue. + * @return Returns 0 if the priority ID is obtained; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*getTxPriorityId)(FlowControlQueueID id); + + /** + * @brief Obtains the ID of the priority of a specified receive flow control queue. + * + * @param id Indicates the ID of the receive flow control queue. + * @return Returns 0 if the priority ID is obtained; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*getRxPriorityId)(FlowControlQueueID id); +}; + +/** + * @brief Describes a flow control module. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlModule { + OSAL_DECLARE_THREAD(txTransferThread); /**< Transmit flow transfer thread */ + OSAL_DECLARE_THREAD(rxTransferThread); /**< Receive flow transfer thread */ + struct OsalSem sem[FLOW_DIR_COUNT]; /**< Array of semaphores */ + FcThreadStatus threadStatus[FLOW_DIR_COUNT]; /**< Array of flow control thread statuses */ + struct FlowControlQueues fcmQueue[FLOW_DIR_COUNT]; /**< Array of flow control queues */ + struct FlowControlOp *op; /**< Flow control operation */ + struct FlowControlInterface *interface; /**< Flow control function */ + void *fcmPriv; /**< Private data of the flow control module */ +}; + +/** + * @brief Provides flow control functions, such as obtaining the queue ID and registering a flow control operation API. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlInterface { + /** + * @brief Obtains the flow control queue ID based on the network data buffer. + * + * @param buff Indicates the pointer to the network data buffer. + * @return Returns the {@link FlowControlQueueID}. + * + * @since 1.0 + * @version 1.0 + */ + FlowControlQueueID (*getQueueIdByEtherBuff)(const NetBuf *buff); + + /** + * @brief Sets the threshold for a specified flow control queue. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule} that contains the flow control queue. + * @param queueThreshold Indicates the threshold to set. + * @param id Indicates the ID of the flow control queue. + * @param dir Indicates the flow control direction, as enumerated in {@link FlowDir}. + * @return Returns 0 if the threshold is set; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*setQueueThreshold)(struct FlowControlModule *fcm, uint32_t queueThreshold, uint32_t id, uint32_t dir); + + /** + * @brief Sends data to a specified {@link FlowControlModule}. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule}. + * @param buff Indicates the pointer to the buffer that stores the data to send. + * @param id Indicates the ID of the flow control queue. + * @param dir Indicates the flow control direction, as enumerated in {@link FlowDir}. + * @return Returns 0 if the data is sent; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*sendBuffToFCM)(struct FlowControlModule *fcm, NetBuf *buff, uint32_t id, uint32_t dir); + + /** + * @brief Schedules a specified {@link FlowControlModule}. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule}. + * @param dir Indicates the flow control direction, as enumerated in {@link FlowDir}. + * @return Returns 0 if the {@link FlowControlModule} is scheduled; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*schedFCM)(struct FlowControlModule *fcm, FlowDir dir); + + /** + * @brief Registers a specified flow control operation API. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule}. + * @param op Indicates the pointer to the flow control operation API to register. + * @return Returns 0 if the API is registered; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ + int32_t (*registerFlowControlOp)(struct FlowControlModule *fcm, struct FlowControlOp *op); +}; + +/** + * @brief Processes Ethernet data. + * + * @param buff Indicates the pointer to the data to process. + * @param len Indicates the data length. + * + * @return Returns the {@link FlowControlQueueID}. + * + * @since 1.0 + * @version 1.0 + */ +typedef FlowControlQueueID (*EtherTypeProcessFun)(const void *buff, uint32_t len); + +/** + * @brief Describes how to process Ethernet data. + * + * @since 1.0 + * @version 1.0 + */ +struct EtherProcessMap { + uint16_t etherType; /**< Ethernet data type */ + EtherTypeProcessFun processFun; /**< Function for processing Ethernet data */ +}; + +/** + * @brief Initializes a specified {@link FlowControlModule}. + * + * @param fcmPriv Indicates the pointer to the private data of the {@link FlowControlModule}. + * + * @return Returns the pointer to the initialized {@link FlowControlModule}. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlModule *InitFlowControl(void *fcmPriv); + +/** + * @brief Obtains a {@link FlowControlModule}. + * + * @return Returns the pointer to the {@link FlowControlModule}. + * + * @since 1.0 + * @version 1.0 + */ +struct FlowControlModule *GetFlowControlModule(void); + +/** + * @brief Deinitializes a specified {@link FlowControlModule}. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule}. + * + * @since 1.0 + * @version 1.0 + */ +void DeInitFlowControl(struct FlowControlModule *fcm); + +/** + * @brief Sends a flow control queue. + * + * @param fcm Indicates the pointer to the {@link FlowControlModule} that contains the flow control queue. + * @param id Indicates the ID of the flow control queue. + * @param dir Indicates the flow control direction, as enumerated in {@link FlowDir}. + * + * @return Returns 0 if the flow control queue is sent; returns a negative value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t SendFlowControlQueue(struct FlowControlModule *fcm, uint32_t id, uint32_t dir); + +#endif /* WIFI_FLOW_CONTROL_H */ +/** @} */ diff --git a/model/network/wifi/platform/include/hdf_wlan_priority_queue.h b/model/network/wifi/platform/include/hdf_wlan_priority_queue.h new file mode 100644 index 00000000..608db5e8 --- /dev/null +++ b/model/network/wifi/platform/include/hdf_wlan_priority_queue.h @@ -0,0 +1,33 @@ +/* + * 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_WLAN_PRIORITY_QUEUE_H +#define HDF_WLAN_PRIORITY_QUEUE_H + +#include "hdf_base.h" +#include "osal/osal_sem.h" + +#define HIGHEST_PRIORITY 0 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { +} PriorityQueue; + +PriorityQueue *CreatePriorityQueue(uint16_t queueSize, uint8_t priorityLevelCount); +void DestroyPriorityQueue(PriorityQueue *); +void *PopPriorityQueue(PriorityQueue *queue, uint32_t waitInMS); +int32_t PushPriorityQueue(PriorityQueue *queue, const uint8_t priority, void *context); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/model/network/wifi/platform/include/hdf_wlan_queue.h b/model/network/wifi/platform/include/hdf_wlan_queue.h new file mode 100644 index 00000000..143dc15b --- /dev/null +++ b/model/network/wifi/platform/include/hdf_wlan_queue.h @@ -0,0 +1,22 @@ +/* + * 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_WLAN_QUEUE_H +#define HDF_WLAN_QUEUE_H +#include "hdf_base.h" + +typedef struct { +} HdfWlanQueue; + +HdfWlanQueue *CreateQueue(uint16_t maxQueueSize); +void DestroyQueue(HdfWlanQueue* queue); + +void *PopQueue(HdfWlanQueue *queue); +int32_t PushQueue(HdfWlanQueue *queue, void *context); + + +#endif diff --git a/model/network/wifi/platform/include/hdf_wlan_services.h b/model/network/wifi/platform/include/hdf_wlan_services.h new file mode 100644 index 00000000..e419062d --- /dev/null +++ b/model/network/wifi/platform/include/hdf_wlan_services.h @@ -0,0 +1,66 @@ +/* + * 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_WLAN_SERVICES_H +#define HDF_WLAN_SERVICES_H + +enum PlatformServiceID { + INTERFACE_SERVICE_ID = 0, + BASE_SERVICE_ID, + AP_SERVICE_ID, + STA_SERVICE_ID, + AUTO_ALLOC_SERVICE_ID_START = 300 +}; + +enum BaseCommands { + CMD_BASE_NEW_KEY, + CMD_BASE_DEL_KEY, + CMD_BASE_SET_DEFAULT_KEY, + CMD_BASE_SEND_MLME, + CMD_BASE_SEND_EAPOL, + CMD_BASE_RECEIVE_EAPOL = 5, + CMD_BASE_ENALBE_EAPOL, + CMD_BASE_DISABLE_EAPOL, + 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, + CMD_BASE_GET_NETWORK_INFO = 15, + CMD_BASE_IS_SUPPORT_COMBO, + CMD_BASE_GET_SUPPORT_COMBO, + CMD_BASE_GET_DEV_MAC_ADDR, + CMD_BASE_SET_MAC_ADDR, + CMD_BASE_GET_VALID_FREQ = 20, + CMD_BASE_SET_TX_POWER, + CMD_BASE_GET_CHIPID, + CMD_BASE_GET_IFNAMES, + CMD_BASE_RESET_DRIVER, + CMD_BASE_DO_RESET_PRIVATE = 25, +}; + +enum APCommands { + CMD_AP_START = 0, + CMD_AP_STOP, + CMD_AP_CHANGE_BEACON, + CMD_AP_DEL_STATION, + CMD_AP_GET_ASSOC_STA, + CMD_AP_SET_COUNTRY_CODE, +}; + +enum STACommands { + CMD_STA_CONNECT = 0, + CMD_STA_DISCONNECT, + CMD_STA_SCAN, + CMD_STA_ABORT_SCAN, + CMD_STA_SET_SCAN_MAC_ADDR +}; + +#endif \ No newline at end of file diff --git a/model/network/wifi/platform/include/hdf_wlan_utils.h b/model/network/wifi/platform/include/hdf_wlan_utils.h new file mode 100644 index 00000000..79ffa727 --- /dev/null +++ b/model/network/wifi/platform/include/hdf_wlan_utils.h @@ -0,0 +1,31 @@ +/* + * 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_WLAN_UTILS_H +#define HDF_WLAN_UTILS_H +#include "hdf_wifi_product.h" +#include "wifi_mac80211_ops.h" + +const char *GetPlatformDriverName(void); + +struct HdfWifiNetDeviceData *GetPlatformData(const struct NetDevice *netDev); + +struct HdfChipDriver *GetChipDriver(const struct NetDevice *netDev); + +struct WlanChannel* WifiGetChannel(struct WlanHwCapability* capality, int32_t freq); + +struct WlanHwCapability* GetHwCapability(struct NetDevice *netDev); + +NetDevice *AllocPlatformNetDevice(struct HdfWlanDevice *device); +int32_t RenewNetDevice(NetDevice **netDev); +int32_t ReleasePlatformNetDevice(struct NetDevice *netDev); + +int32_t GetPlatformIfName(uint8_t id, char *ifName, uint32_t ifNameSize); +char* HdfWlanGetIfNames(const uint8_t chipId, uint8_t *ifNameCount); + +#endif \ No newline at end of file diff --git a/model/network/wifi/platform/include/message/message_config.h b/model/network/wifi/platform/include/message/message_config.h new file mode 100644 index 00000000..1a301bcb --- /dev/null +++ b/model/network/wifi/platform/include/message/message_config.h @@ -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. + */ + +#ifndef __MESSAGE_CONFIG_H__ +#define __MESSAGE_CONFIG_H__ +#include "message_types.h" + +#ifndef MESSAGE_ENGINE_MAX_SERVICE +#define MESSAGE_ENGINE_MAX_SERVICE 15 +#endif + +#ifndef MESSAGE_ENGINE_MAX_DISPATCHER +#define MESSAGE_ENGINE_MAX_DISPATCHER 10 +#endif + +#ifndef MESSAGE_ENGINE_DISPATCHERID_ASSIGN_START +#define MESSAGE_ENGINE_DISPATCHERID_ASSIGN_START 5 +#endif + +#ifndef DEFAULT_DISPATCHER_QUEUE_SIZE +#define DEFAULT_DISPATCHER_QUEUE_SIZE 128 +#endif + +#ifndef DEFAULT_DISPATCHER_PRIORITY_COUNT +#define DEFAULT_DISPATCHER_PRIORITY_COUNT 2 +#endif + +#define IOCTL_SEND_QUEUE_SIZE 300 +#define IOCTL_SEND_QUEUE_PROPIRTY_LEVEL 1 + +#define MAX_OBJ_REF_COUNT 200 + +#define MAX_NODE_REF_COUNT 200 + +#define MESSAGE_DEVICE "/dev/msg_engine" +#define MESSAGE_DEVICE_MODE 0660 + +#define QUEUE_OPER_TIMEOUT 1000 + +#define MAX_BLOCK_SIZE 16380L + +#define SYSTEM_ALIGN_WIDTH (sizeof(void*)) + +#define USER_TO_KERNEL_SYNC_MESSAGE_TIMEOUT 10000L + +typedef struct DispatcherConfig_ { + DispatcherId dispatcherId; + uint8_t priorityLevelCount; + uint16_t queueSize; +} DispatcherConfig; + +#endif \ No newline at end of file diff --git a/model/network/wifi/platform/include/message/message_router.h b/model/network/wifi/platform/include/message/message_router.h new file mode 100644 index 00000000..32473046 --- /dev/null +++ b/model/network/wifi/platform/include/message/message_router.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 MESSAGE_ROUTER_H +#define MESSAGE_ROUTER_H +#include "message_config.h" +#include "osal/osal_mutex.h" +#include "sidecar.h" +#define DEFAULT_DISPATCHER_ID 0 + +#ifdef __cplusplus +extern "C" { +#endif + +enum MessageNodeType { + MESSAGE_NODE_CONFIG_DEFAULT = 0, +#ifdef KERNEL_SERVER_SUPPORT + MESSAGE_NODE_REMOTE_KERNEL_SERVER = 2, +#endif +#ifdef USERSPACE_CLIENT_SUPPORT + MESSAGE_NODE_REMOTE_USERSPACE_CLIENT = 4 +#endif +}; + +ErrorCode StartMessageRouter(uint8_t nodesConfig); + +ErrorCode ShutdownMessageRouter(void); + +ErrorCode AddDispatcher(DispatcherConfig *config); + +ErrorCode EnableDefaultDispatcher(void); + +ErrorCode RegistLocalService(const DispatcherId dispatcherId, struct ServiceDef *mapper); + +ErrorCode UnregistLocalService(const DispatcherId dispatcherId, ServiceId serviceId); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/model/network/wifi/platform/include/message/message_types.h b/model/network/wifi/platform/include/message/message_types.h new file mode 100644 index 00000000..32dce6f5 --- /dev/null +++ b/model/network/wifi/platform/include/message/message_types.h @@ -0,0 +1,77 @@ +/* + * 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 __MESSAGE_TYPES_H__ +#define __MESSAGE_TYPES_H__ +#include "hdf_base.h" + +typedef uint8_t NodeId; +#define LOCAL_NODE_INDEX 0 +#define REMOTE_NODE_INDEX 1 +#define NO_SUCH_NODE_INDEX 255 + +typedef uint8_t ServiceId; + +typedef int32_t ErrorCode; + +typedef uint8_t DispatcherId; + +enum MessageEngineStatus { + ME_STATUS_STOPPED = 0, + ME_STATUS_STARTTING, + ME_STATUS_RUNNING, + ME_STATUS_STOPPING, + ME_STATUS_TODESTROY +}; + +#define ME_SUCCESS 0 +#define ME_ERROR_NULL_PTR (-1) +#define ME_ERROR_OPER_QUEUE_FAILED (-2) +#define ME_ERROR_OPER_SMSEMIPHORE_FAILED (-3) +#define ME_ERROR_CREATE_THREAD_FAILED (-4) +#define ME_ERROR_NOT_SUPPORTED (-5) +#define ME_ERROR_DELETE_THREAD_FAILED (-6) +#define ME_ERROR_OPER_MUTEX_FAILED (-7) +#define ME_ERROR_OPER_MEM_FAILED (-8) + +#define ME_ERROR_WRONG_TYPE 1 +#define ME_ERROR_MUTI_INIT_NOT_ALLOWED 2 +#define ME_ERROR_INIT_QUEUE_FAILED 3 +#define ME_ERROR_WRONG_STATUS 4 +#define ME_ERROR_SERVICEID_CONFLICT 5 +#define ME_ERROR_PARA_WRONG 6 + +#define ME_ERROR_NO_SUCH_SERVICE 8 +#define ME_ERROR_NO_SUCH_COMMAND 9 +#define ME_ERROR_RES_LAKE 10 +#define ME_ERROR_DISPATCHER_NOT_RUNNING 11 +#define ME_ERROR_NO_SUCH_DISPATCHER 12 +#define ME_ERROR_DISPATCHERID_CONFLICT 13 +#define ME_ERROR_DISPATCHERID_STOPPED 14 +#define ME_ERROR_CONFIG_NOT_ALLOWED 15 +#define ME_ERROR_COMMU_WITH_KERNEL_NODE_FAILED 16 +#define ME_ERROR_MSG_BLOCK_TOO_LONG 17 +#define ME_ERROR_MSG_BLOCK_MISMATCH 18 +#define ME_ERROR_MSG_DISPATCH_FAILED 19 +#define ME_ERROR_MSG_MISMATCH 20 +#define ME_ERROR_COPY_MEM_FROM_USERSPACE_FAILED 21 +#define ME_ERROR_NO_MESSAGE 22 +#define ME_ERROR_COPY_MEM_TO_USERSPACE_FAILED 23 +#define ME_ERROR_NO_MORE_BLOCK_VALUES 24 +#define ME_ERROR_PARSE_DATABLOCK_FAILED 25 +#define ME_ERROR_BAD_DISPATCHER 26 +#define ME_ERROR_NO_SUCH_NODE 27 +#define ME_ERROR_BAD_NODE 28 +#define ME_ERROR_CREATE_REMOTE_SERVICE_FAILED 29 +#define ME_ERROR_SERVICE_REQ_TIMEOUT 30 +#define ME_ERROR_BAD_SERVICE 31 +#define ME_ERROR_PROC_TIMEOUT 32 + +#define BYTE_WIDTH 8 + +#endif diff --git a/model/network/wifi/platform/include/message/sidecar.h b/model/network/wifi/platform/include/message/sidecar.h new file mode 100644 index 00000000..4e1d7f59 --- /dev/null +++ b/model/network/wifi/platform/include/message/sidecar.h @@ -0,0 +1,124 @@ +/* + * 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 __SIDECAR_H__ +#define __SIDECAR_H__ +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal/osal_sem.h" +#include "message_types.h" +#include "hdf_sbuf.h" + +enum MessageType { + MESSAGE_REQ_START = 0, + MESSAGE_TYPE_SYNC_REQ, + MESSAGE_TYPE_ASYNC_REQ, + + MESSAGE_RSP_START, + MESSAGE_TYPE_SYNC_RSP, + MESSAGE_TYPE_ASYNC_RSP, +}; + +#define INHERT_REQUEST_CONTEXT \ + uint32_t commandId; \ + uint8_t senderId; \ + uint8_t receiverId; \ + uint8_t requestType; \ + bool corssNode; \ + struct HdfDeviceIoClient *client + +#define RESERVED_SERVICE_ID 0 +#define BAD_SERVICE_ID 254 + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t DispatchToMessage(struct HdfDeviceIoClient *client, int id, struct HdfSBuf *reqData, struct HdfSBuf *rspData); + +typedef struct { + INHERT_REQUEST_CONTEXT; +} RequestContext; + +typedef void (*MessageCallBack)(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData, + ErrorCode responseStatus); + +typedef ErrorCode (*MessageHandler)(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData); + +struct MessageContext { + INHERT_REQUEST_CONTEXT; +#if defined(KERNEL_SERVER_SUPPORT) || defined(USERSPACE_CLIENT_SUPPORT) + uint16_t messageID; +#endif + ErrorCode responseStatus; + struct HdfSBuf *reqData; + struct HdfSBuf *rspData; + union { + MessageCallBack callback; + OSAL_DECLARE_SEMAPHORE(rspSemaphore); + }; +}; +typedef struct MessageContext MessageContext; + +typedef struct SideCar_ { + ErrorCode (*SendOneWayMessage)(const struct SideCar_ *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *reqData); + + ErrorCode (*SendSyncMessage)(const struct SideCar_ *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *sendData, struct HdfSBuf *recvData); + + ErrorCode (*SendAsyncMessage)(const struct SideCar_ *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *reqData, MessageCallBack callback); + + ErrorCode (*Destroy)(struct SideCar_ *sideCar); + + void *privateData; +} Service; + +typedef struct { + DispatcherId dispatcherId; +} ServiceCfg; + +struct MessageDef { + MessageHandler handler; + uint8_t pri; +}; + +struct ServiceDef { + ServiceId serviceId; + uint8_t messagesLength; + struct MessageDef *messages; +}; + +Service *InitService(struct ServiceDef *def, const ServiceCfg *cfg); + +#define DUEMessage(CMDID, HANDLER, PRI) \ + [CMDID] = { \ + .handler = HANDLER, \ + .pri = PRI \ + } + +#define ServiceDefine(ServiceName, SERVICE_ID, ServiceMap) \ + Service *CreateService##ServiceName(const ServiceCfg *cfg) \ + { \ + static struct ServiceDef serviceDef = { \ + .serviceId = SERVICE_ID, \ + .messagesLength = sizeof(ServiceMap) / sizeof(struct MessageDef), \ + .messages = ServiceMap \ + }; \ + return InitService(&serviceDef, cfg); \ + } + +#define CreateService(ServiceName, cfg) CreateService##ServiceName(cfg) + + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/model/network/wifi/platform/src/hdf_wifi_event.c b/model/network/wifi/platform/src/hdf_wifi_event.c new file mode 100644 index 00000000..8ad90b5a --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wifi_event.c @@ -0,0 +1,432 @@ +/* + * 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_wifi_event.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" +#include "hdf_slist.h" +#include "hdf_wifi_product.h" +#include "osal_timer.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +int32_t HdfWifiEventNewSta(const struct NetDevice *netDev, const uint8_t *macAddr, uint8_t addrLen, + const struct StationInfo *info) +{ + struct HdfSBuf *data = NULL; + const uint32_t reassoc = 0; + int32_t ret; + + if (netDev == NULL || macAddr == NULL || info == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (info->assocReqIesLen == 0) { + HDF_LOGE("%s assocReqIesLen is 0", __func__); + return HDF_FAILURE; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint32(data, reassoc) || + !HdfSbufWriteBuffer(data, info->assocReqIes, info->assocReqIesLen) || + !HdfSbufWriteBuffer(data, macAddr, addrLen)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + HDF_LOGI("%s netDev->name=%s, MAC=XX:XX:XX:XX:XX:%02X", __func__, netDev->name, + (addrLen > 0) ? macAddr[addrLen - 1] : -1); + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_NEW_STA, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventDelSta(struct NetDevice *netDev, const uint8_t *macAddr, uint8_t addrLen) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if ((netDev == NULL) || (macAddr == NULL)) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteBuffer(data, macAddr, addrLen)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_DEL_STA, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventInformBssFrame(const struct NetDevice *netDev, + const struct WlanChannel *channel, const struct ScannedBssInfo *bssInfo) +{ + struct HdfSBuf *data = NULL; + uint32_t ieLen; + uint32_t beaconLen; + int32_t ret; + + if ((netDev == NULL) || (channel == NULL) || (bssInfo == NULL) || (bssInfo->mgmt == NULL)) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + ieLen = bssInfo->mgmtLen - (uint32_t)OFFSET_OF(struct Ieee80211Mgmt, u.probeResp.variable); + beaconLen = bssInfo->mgmtLen - (uint32_t)OFFSET_OF(struct Ieee80211Mgmt, u.beacon.variable); + if (!HdfSbufWriteString(data, netDev->name) || + !HdfSbufWriteUint16(data, (int16_t)bssInfo->mgmt->u.probeResp.beaconInt) || + !HdfSbufWriteUint16(data, (int16_t)bssInfo->mgmt->u.probeResp.capabInfo) || + !HdfSbufWriteUint32(data, bssInfo->signal) || !HdfSbufWriteUint32(data, channel->centerFreq) || + !HdfSbufWriteUint32(data, (int32_t)channel->flags) || + !HdfSbufWriteBuffer(data, bssInfo->mgmt->bssid, ETH_ADDR_LEN) || + !HdfSbufWriteBuffer(data, bssInfo->mgmt->u.probeResp.variable, ieLen) || + !HdfSbufWriteBuffer(data, bssInfo->mgmt->u.beacon.variable, beaconLen)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_SCAN_RESULT, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventScanDone(const struct NetDevice *netDev, WifiScanStatus status) +{ + uint32_t code = status; + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint32(data, code)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_SCAN_DONE, data); + HdfSBufRecycle(data); + return ret; +} + +#if (_PRE_OS_VERSION_LITEOS == _PRE_OS_VERSION) +#define DHCP_CHECK_CNT 30 +#define DHCP_CHECK_TIME 1000 +uint32_t g_ipCheckOut = 0; +OSAL_DECLARE_TIMER(g_dhcpTimer); + +void HdfDhcpResultCheck(uintptr_t para) +{ + int32_t ret; + struct NetDevice *dev = (struct NetDevice *)para; + + if (dev == NULL) { + return; + } + ret = NetIfDhcpIsBound(dev); + if (ret == 0) { + OsalTimerDelete(&g_dhcpTimer); + return; + } + + if (g_ipCheckOut++ > DHCP_CHECK_CNT) { + OsalTimerDelete(&g_dhcpTimer); + return; + } +} + +static void HdfStartDhcpClient(const struct NetDevice *netDev) +{ + int32_t ret; + + /* start dhcp client */ + (void)NetIfDhcpStop((struct NetDevice *)netDev); + ret = NetIfDhcpStart((struct NetDevice *)netDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("HdfWifiEventConnectResult::start dhcp client failed"); + } + + if (g_dhcpTimer.realTimer != NULL) { + OsalTimerDelete(&g_dhcpTimer); + } + + g_ipCheckOut = 0; + OsalTimerCreate(&g_dhcpTimer, DHCP_CHECK_TIME, HdfDhcpResultCheck, (uintptr_t)netDev); + OsalTimerStartLoop(&g_dhcpTimer); +} +#endif + +int32_t HdfWifiEventConnectResult(const struct NetDevice *netDev, const struct ConnetResult *result) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL || result == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint16(data, result->connectStatus) || + !HdfSbufWriteUint16(data, result->freq) || !HdfSbufWriteBuffer(data, result->bssid, ETH_ADDR_LEN) || + !HdfSbufWriteBuffer(data, result->reqIe, result->reqIeLen) || + !HdfSbufWriteBuffer(data, result->rspIe, result->rspIeLen)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_CONNECT_RESULT, data); + HdfSBufRecycle(data); + +#if (_PRE_OS_VERSION_LITEOS == _PRE_OS_VERSION) + if (result->connectStatus == WIFI_HMAC_MGMT_SUCCESS) { + HdfStartDhcpClient(netDev); + } +#endif + + return ret; +} + +int32_t HdfWifiEventDisconnected(const struct NetDevice *netDev, uint16_t reason, const uint8_t *ie, uint32_t len) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint16(data, reason) || + !HdfSbufWriteBuffer(data, ie, len)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_DISCONNECT, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventMgmtTxStatus(const struct NetDevice *netDev, const uint8_t *buf, size_t len, uint8_t ack) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint8(data, ack) || + !HdfSbufWriteBuffer(data, buf, len)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_TX_STATUS, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventCsaChannelSwitch(const struct NetDevice *netDev, int32_t freq) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint32(data, freq)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_CHANNEL_SWITCH, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventTimeoutDisconnected(const struct NetDevice *netDev) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteString(data, netDev->name)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_TIMEOUT_DISCONN, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventRxMgmt(const struct NetDevice *netDev, int32_t freq, int32_t sigMbm, const uint8_t *buf, size_t len) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s param is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + + if (!HdfSbufWriteString(data, netDev->name) || !HdfSbufWriteUint32(data, freq) || + !HdfSbufWriteUint32(data, sigMbm) || !HdfSbufWriteBuffer(data, buf, len)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_RX_MGMT, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventEapolRecv(const char *name, void *context) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + (void)context; + if (name == NULL) { + return HDF_ERR_INVALID_PARAM; + } + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteString(data, name)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_EAPOL_RECV, data); + HdfSBufRecycle(data); + return ret; +} + +int32_t HdfWifiEventResetResult(const uint8_t chipId, int32_t resetStatus) +{ + struct HdfSBuf *data = NULL; + int32_t ret; + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("%s InitDataBlock failed", __func__); + return HDF_FAILURE; + } + if (!HdfSbufWriteInt32(data, resetStatus)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + if (!HdfSbufWriteUint8(data, chipId)) { + HDF_LOGE("%s sbuf write failed", __func__); + HdfSBufRecycle(data); + return HDF_FAILURE; + } + ret = HdfWlanSendBroadcastEvent(WIFI_WPA_EVENT_RESET_DRIVER, data); + HdfSBufRecycle(data); + return ret; +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif diff --git a/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c b/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c new file mode 100644 index 00000000..63a47e9c --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_chipdriver_manager.c @@ -0,0 +1,87 @@ +/* + * 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_wlan_chipdriver_manager.h" +#include "gpio_if.h" +#include "osal_mem.h" +#include "hdf_log.h" +#include "wifi_module.h" +#include "securec.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +static struct HdfChipDriverFactory *g_wlanChipDriverManagerFactory[MAX_CHIPDRIVER_COUNT] = {NULL}; + +/* chip driver manager method get chip driver factory by chip name */ +struct HdfChipDriverFactory *HdfWlanGetChipDriverByName(const char *driverName) +{ + int32_t i; + if (driverName == NULL) { + HDF_LOGE("%s fail : driverName is NULL", __func__); + return NULL; + } + + for (i = 0; i < MAX_CHIPDRIVER_COUNT; i++) { + if (g_wlanChipDriverManagerFactory[i] != NULL && g_wlanChipDriverManagerFactory[i]->driverName != NULL) { + struct HdfChipDriverFactory *factory = g_wlanChipDriverManagerFactory[i]; + if (strcmp(factory->driverName, driverName) == 0) { + return factory; + } + } + } + return NULL; +} + +/* chip driver manager register */ +int32_t HdfWlanRegChipDriver(struct HdfChipDriverFactory *obj) +{ + int32_t index; + if (obj == NULL || obj->driverName == NULL) { + HDF_LOGE("%s: HdfChipDriverFactory obj is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (HdfWlanGetChipDriverByName(obj->driverName) != NULL) { + HDF_LOGW("%s: chipdriver factory is already registed.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); + return HDF_SUCCESS; + } + } + HDF_LOGE("%s:Factory table is full", __func__); + return HDF_FAILURE; +} + +/* to release the chipdriver manager factory */ +int32_t ChipDriverMgrDeInit(void) +{ + int cnt; + for (cnt = 0; cnt < MAX_CHIPDRIVER_COUNT; cnt++) { + if (g_wlanChipDriverManagerFactory[cnt] != NULL) { + if (g_wlanChipDriverManagerFactory[cnt]->ReleaseFactory != NULL) { + g_wlanChipDriverManagerFactory[cnt]->ReleaseFactory(g_wlanChipDriverManagerFactory[cnt]); + } + g_wlanChipDriverManagerFactory[cnt] = NULL; + } + } + + return HDF_SUCCESS; +} + +static struct HdfChipDriverManager g_chipDriverManager = { + .chipFactoryInsts = g_wlanChipDriverManagerFactory, + .RegChipDriver = HdfWlanRegChipDriver, + .GetChipDriverByName = HdfWlanGetChipDriverByName, +}; +struct HdfChipDriverManager *HdfWlanGetChipDriverMgr(void) +{ + return &g_chipDriverManager; +} \ No newline at end of file diff --git a/model/network/wifi/platform/src/hdf_wlan_config_parser.c b/model/network/wifi/platform/src/hdf_wlan_config_parser.c new file mode 100644 index 00000000..b55b3935 --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_config_parser.c @@ -0,0 +1,565 @@ +/* + * 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_wlan_config.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE +static struct HdfConfigWlanRoot g_configWlanModuleRoot = { 0 }; +static int32_t ParseWlanStaConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanStation *staConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (node == NULL || staConfig == NULL) { + HDF_LOGE("%s: invalid node or staConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetString == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetString(node, "name", &staConfig->name, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: GetString fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "mode", &staConfig->mode, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: GetUint8 fail!", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: name=%s, mode=%d!", __func__, staConfig->name, staConfig->mode); + return HDF_SUCCESS; +} + +static int32_t ParseWlanApConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanHostAp *apConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (node == NULL || apConfig == NULL) { + HDF_LOGE("%s: invalid node or apConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetString == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetString(node, "name", &apConfig->name, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: name fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "mode", &apConfig->mode, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: mode fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "vapResNum", &apConfig->vapResNum, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get vapResNnm fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "userResNum", &apConfig->userResNum, 0); + if (ret != HDF_SUCCESS) { + 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, + apConfig->vapResNum, apConfig->userResNum); + return HDF_SUCCESS; +} + +static int32_t ParseWlanP2PConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanP2P *p2pConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (node == NULL || p2pConfig == NULL) { + HDF_LOGE("%s: invalid node or p2pConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetString == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetString(node, "name", &p2pConfig->name, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: name fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "mode", &p2pConfig->mode, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: mode fail!", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: name=%s, mode=%d", __func__, p2pConfig->name, p2pConfig->mode); + return HDF_SUCCESS; +} + +static int32_t ParseWlanMac80211Config(const struct DeviceResourceNode *node, struct HdfConfigWlanMac80211 *macConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (node == NULL || macConfig == NULL) { + HDF_LOGE("%s: invalid node or macConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "mode", &macConfig->mode, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: mode fail!", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: mode=%d", __func__, macConfig->mode); + return HDF_SUCCESS; +} + +static int32_t ParseWlanPhyConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanPhy *phyConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (node == NULL || phyConfig == NULL) { + HDF_LOGE("%s: invalid node or macConfig!\n", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!\n", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint8(node, "mode", &phyConfig->mode, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: mode fail!\n", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s: mode=%d\n", __func__, phyConfig->mode); + return HDF_SUCCESS; +} + +static int32_t ParseWlanModuleConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanModuleConfig *modConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + const struct DeviceResourceNode *staConfigNode = NULL; + const struct DeviceResourceNode *apConfigNode = NULL; + const struct DeviceResourceNode *p2pConfigNode = NULL; + const struct DeviceResourceNode *macConfigNode = NULL; + const struct DeviceResourceNode *phyConfigNode = NULL; + + if (node == NULL || modConfig == NULL) { + HDF_LOGE("%s: invalid node or moduleConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetChildNode == NULL || drsOps->GetString == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint32(node, "featureMap", &modConfig->featureMap, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: featureMap fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetString(node, "msgName", &modConfig->msgName, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: msgName fail!", __func__); + return HDF_FAILURE; + } + + staConfigNode = drsOps->GetChildNode(node, "Station"); + apConfigNode = drsOps->GetChildNode(node, "HostAp"); + p2pConfigNode = drsOps->GetChildNode(node, "P2P"); + macConfigNode = drsOps->GetChildNode(node, "Mac80211"); + phyConfigNode = drsOps->GetChildNode(node, "Phy"); + if (staConfigNode == NULL || apConfigNode == NULL || p2pConfigNode == NULL || macConfigNode == NULL || + phyConfigNode == NULL) { + HDF_LOGE("%s: get child node fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanStaConfig(staConfigNode, &modConfig->station) != HDF_SUCCESS) { + return HDF_FAILURE; + } + if (ParseWlanApConfig(apConfigNode, &modConfig->hostAp) != HDF_SUCCESS) { + return HDF_FAILURE; + } + if (ParseWlanP2PConfig(p2pConfigNode, &modConfig->p2p) != HDF_SUCCESS) { + return HDF_FAILURE; + } + if (ParseWlanMac80211Config(macConfigNode, &modConfig->mac80211) != HDF_SUCCESS) { + return HDF_FAILURE; + } + if (ParseWlanPhyConfig(phyConfigNode, &modConfig->Phy) != HDF_SUCCESS) { + return HDF_FAILURE; + } + HDF_LOGD("%s: featureMap=%0x, msgName=%s", __func__, modConfig->featureMap, modConfig->msgName); + return HDF_SUCCESS; +} +/* BEGIN for WLAN2.1 : Added by hdf-wlan */ +static int32_t ParseWlanPowerConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanPower *masterPowerConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + if (node == NULL || masterPowerConfig == NULL) { + HDF_LOGE("%s: one of the input para is NULL!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "powerSeqDelay", &masterPowerConfig->powerSeqDelay, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: powersSeqDelay fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "powerType", &masterPowerConfig->powerType, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: powerType fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "gpioId", &masterPowerConfig->gpioId, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: gpioId fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint8(node, "activeLevel", &masterPowerConfig->activeLevel, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: activeLevel fail!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +/* BEGIN for WLAN2.1 to get powers config: Added by hdf-wlan */ +static int32_t ParseWlanPowersConfig(const struct DeviceResourceNode *node, struct HdfConfWlanPowers *powersConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + if (node == NULL || powersConfig == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetChildNode == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + const struct DeviceResourceNode *fstPowerNode = drsOps->GetChildNode(node, "power0"); + if (fstPowerNode == NULL) { + HDF_LOGE("%s: get power0 config fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanPowerConfig(fstPowerNode, &powersConfig->power0) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + const struct DeviceResourceNode *secPowerNode = drsOps->GetChildNode(node, "power1"); + if (fstPowerNode == NULL) { + HDF_LOGE("%s: get power1 config fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanPowerConfig(secPowerNode, &powersConfig->power1) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t ParseWlanResetConfig(const struct DeviceResourceNode *node, struct HdfConfWlanRest *resetConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + if (node == NULL || resetConfig == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "resetType", &resetConfig->resetType, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: powersSeqDelay fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "gpioId", &resetConfig->gpioId, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: gpioId fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "activeLevel", &resetConfig->activeLevel, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: powerType fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "resetHoldTime", &resetConfig->resetHoldTime, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: activeLevel fail!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t ParseWlanBusConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanBus *busConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + + if (node == NULL || busConfig == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL || drsOps->GetUint8Array == NULL || drsOps->GetUint16 == NULL || + drsOps->GetUint32 == NULL || drsOps->GetElemNum == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint8(node, "busType", &busConfig->busType, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: busType fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint8(node, "busIdx", &busConfig->busIdx, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: busType fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint8Array(node, "funcNum", busConfig->funcNum, BUS_FUNC_MAX, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: funcNum fail!", __func__); + return HDF_FAILURE; + } + busConfig->funcNumSize = drsOps->GetElemNum(node, "funcNum"); + + if (drsOps->GetUint16(node, "timeout", &busConfig->timeout, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: timeout fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint16(node, "blockSize", &busConfig->blockSize, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: timeout fail!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t ParseWlanDevInstConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanDevInst *devLstConfig) +{ + struct DeviceResourceIface *drsOps = NULL; + const struct DeviceResourceNode *devPowerNode = NULL; + const struct DeviceResourceNode *chipConfigNode = NULL; + const struct DeviceResourceNode *resetNode = NULL; + if (node == NULL || devLstConfig == NULL) { + HDF_LOGE("%s: invalid node or devLstConfig!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint8 == NULL || drsOps->GetChildNode == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "deviceInstId", &devLstConfig->deviceInstId, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: deviceinstId fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint8(node, "bootUpTimeOut", &devLstConfig->bootUpTimeOut, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: bootUpTimeOut fail!", __func__); + return HDF_FAILURE; + } + + devPowerNode = drsOps->GetChildNode(node, "powers"); + if (devPowerNode == NULL) { + HDF_LOGE("%s: GetChildNode fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanPowersConfig(devPowerNode, &devLstConfig->powers) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + resetNode = drsOps->GetChildNode(node, "reset"); + if (resetNode == NULL) { + HDF_LOGE("%s: GetChildNode fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanResetConfig(resetNode, &devLstConfig->reset) != HDF_SUCCESS) { + return HDF_FAILURE; + } + chipConfigNode = drsOps->GetChildNode(node, "bus"); + if (chipConfigNode == NULL) { + HDF_LOGE("%s: GetChildNode fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanBusConfig(chipConfigNode, &devLstConfig->bus) != HDF_SUCCESS) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t ParseWlanDevListConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanDeviceList *devConfig) +{ + struct DeviceResourceNode *childNode = NULL; + uint32_t index = 0; + if (node == NULL || devConfig == NULL) { + HDF_LOGE("%s: invalid node or devConfig!", __func__); + return HDF_FAILURE; + } + DEV_RES_NODE_FOR_EACH_CHILD_NODE(node, childNode) + { + if (ParseWlanDevInstConfig(childNode, &devConfig->deviceInst[index]) != HDF_SUCCESS) { + return HDF_FAILURE; + } + index++; + devConfig->deviceListSize++; + } + HDF_LOGD("%s: deviceListSize=%d", __func__, devConfig->deviceListSize); + return HDF_SUCCESS; +} + +/* BEGIN for WLAN2.1 to get chips configures: Added by hdf-wlan */ +static int32_t ParseWlanChipSdioConfig(const struct DeviceResourceNode *node, struct HdfConfWlanSdioArgs *sdioArgs) +{ + struct DeviceResourceIface *drsOps = NULL; + if (node == NULL || sdioArgs == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint16 == NULL || drsOps->GetUint16Array == NULL) { + HDF_LOGE("%s: at least one of the paras is NULL!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetUint16(node, "vendorId", &sdioArgs->vendorId, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: vendorId fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetUint16Array(node, "deviceId", sdioArgs->deviceId, CHIP_SDIO_DEVICE_ID_COUNT, 0) != HDF_SUCCESS) { + 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; +} + +static int32_t ParseWlanChipsCompsConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanChipInst *chipInst) +{ + struct DeviceResourceIface *drsOps = NULL; + const struct DeviceResourceNode *chipBusNode = NULL; + if (node == NULL || chipInst == NULL) { + HDF_LOGE("%s: invalid node or busRegsConfig!\n", __func__); + return HDF_FAILURE; + } + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetString == NULL || drsOps->GetChildNode == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + + if (drsOps->GetString(node, "driverName", &chipInst->driverName, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s: vendorId fail!", __func__); + return HDF_FAILURE; + } + HDF_LOGI("%s: driverName=%s", __func__, chipInst->driverName); + + chipBusNode = drsOps->GetChildNode(node, "sdio"); + if (chipBusNode == NULL) { + HDF_LOGE("%s: GetChildNode fail!", __func__); + return HDF_FAILURE; + } + if (ParseWlanChipSdioConfig(chipBusNode, &chipInst->chipSdio) != HDF_SUCCESS) { + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} +/* parse wlan chipList config */ +static int32_t ParseWlanChipsConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanChipList *chipList) +{ + struct DeviceResourceNode *childNode = NULL; + uint32_t cnt = 0; + if (node == NULL || chipList == NULL) { + HDF_LOGE("%s: invalid node or chipList!\n", __func__); + return HDF_FAILURE; + } + + DEV_RES_NODE_FOR_EACH_CHILD_NODE(node, childNode) + { + if (ParseWlanChipsCompsConfig(childNode, &chipList->chipInst[cnt]) != HDF_SUCCESS) { + return HDF_FAILURE; + } + cnt++; + chipList->chipInstSize++; + } + HDF_LOGD("%s: chipSize=%d", __func__, chipList->chipInstSize); + + return HDF_SUCCESS; +} +/* END for WLAN2.1 chips configuration parse : Added by hdf-wlan */ + +static int32_t ParseWlanConfig(const struct DeviceResourceNode *node, struct HdfConfigWlanConfig *wlanConfig) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + const struct DeviceResourceNode *moduleConfigNode = NULL; + const struct DeviceResourceNode *devListNode = NULL; + const struct DeviceResourceNode *chipsNode = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetChildNode == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + if (drsOps->GetString(node, "hostChipName", &wlanConfig->hostChipName, NULL) != HDF_SUCCESS) { + HDF_LOGE("%s: hostChipName fail!", __func__); + return HDF_FAILURE; + } + moduleConfigNode = drsOps->GetChildNode(node, "moduleConfig"); + devListNode = drsOps->GetChildNode(node, "deviceList"); + chipsNode = drsOps->GetChildNode(node, "chipList"); + if (moduleConfigNode == NULL || devListNode == NULL || chipsNode == NULL) { + HDF_LOGE("%s: get child node fail!", __func__); + return HDF_FAILURE; + } + ret = ParseWlanModuleConfig(moduleConfigNode, &wlanConfig->moduleConfig); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + ret = ParseWlanDevListConfig(devListNode, &wlanConfig->deviceList); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + ret = ParseWlanChipsConfig(chipsNode, &wlanConfig->chipList); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + return ret; +} + +int32_t HdfParseWlanConfig(const struct DeviceResourceNode *node) +{ + if (node == NULL) { + HDF_LOGE("%s: node = null!\n", __func__); + return HDF_FAILURE; + } + return ParseWlanConfig(node, &g_configWlanModuleRoot.wlanConfig); +} + +struct HdfConfigWlanRoot *HdfWlanGetModuleConfigRoot() +{ + return &g_configWlanModuleRoot; +} diff --git a/model/network/wifi/platform/src/hdf_wlan_power_manager.c b/model/network/wifi/platform/src/hdf_wlan_power_manager.c new file mode 100644 index 00000000..09494aba --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_power_manager.c @@ -0,0 +1,162 @@ +/* + * 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 "gpio_if.h" +#include "osal_mem.h" +#include "hdf_log.h" +#include "wifi_module.h" +#include "hdf_wlan_chipdriver_manager.h" +#include "securec.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +/* power manager begin */ +enum PowerType { + PowerNotManaged = 0, + PowerManagedByGPIO = 1 +}; + +enum GPIOActiveLevel { + ActiveLow = 0, + ActiveHigh +}; + +/* powerCount=1 single power source */ +struct DevicePowerData { + struct HdfConfigWlanPower power0; + struct HdfConfigWlanPower power1; +}; + +struct PowerManagerImpl { + struct PowerManager base; + struct DevicePowerData powerDatas; +}; + +/* power on method */ +static int32_t HdfWlanSinglePowerActive(struct HdfConfigWlanPower* powerDate) +{ + int32_t ret; + if (powerDate == NULL) { + HDF_LOGE("%s:powerDate is NULL", __func__); + return HDF_FAILURE; + } + if (powerDate->powerType != PowerNotManaged) { + HDF_LOGI("%s:power type is always on", __func__); + return HDF_SUCCESS; + } + ret = GpioSetDir(powerDate->gpioId, 1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:set dir fail! ret=%d\n", __func__, ret); + return HDF_FAILURE; + } + OsalMSleep(powerDate->powerSeqDelay); + ret = GpioWrite(powerDate->gpioId, powerDate->activeLevel); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:set power on fail! ret=%d\n", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +static int32_t HdfWlanSingleDeActive(struct HdfConfigWlanPower* powerDate) +{ + int32_t ret; + uint8_t deActicve; + + if (powerDate == NULL) { + HDF_LOGE("%s: powerDate is NULL", __func__); + return HDF_FAILURE; + } + deActicve = !powerDate->activeLevel; + if (powerDate->powerType == PowerNotManaged) { + HDF_LOGE("%s:power type is not supported in current version", __func__); + return HDF_FAILURE; + } + ret = GpioSetDir(powerDate->gpioId, 1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:set dir fail! ret:%d\n", __func__, ret); + return ret; + } + ret = GpioWrite(powerDate->gpioId, deActicve); + return HDF_SUCCESS; +} + +static int32_t HdfWlanChipPowerOn(struct PowerManager* powerMgr) +{ + int32_t ret; + struct PowerManagerImpl *powerMgrimpl = NULL; + if (powerMgr == NULL) { + HDF_LOGE("%s: powerMgr is NULL", __func__); + return HDF_FAILURE; + } + powerMgrimpl = (struct PowerManagerImpl*)powerMgr; + ret = HdfWlanSinglePowerActive(&powerMgrimpl->powerDatas.power0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: HdfWlanMainPowerOn fail! ret:%d\n", __func__, ret); + (void)HdfWlanSingleDeActive(&powerMgrimpl->powerDatas.power0); + return HDF_FAILURE; + } + ret = HdfWlanSinglePowerActive((struct HdfConfigWlanPower*)&powerMgrimpl->powerDatas.power1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: HdfWlanPowerActive fail! ret:%d\n", __func__, ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +static int32_t HdfWlanChipPowerOff(struct PowerManager* powerMgr) +{ + int32_t ret; + struct PowerManagerImpl *powerMgrimpl = NULL; + if (powerMgr == NULL) { + HDF_LOGE("%s: powerMgr is NULL", __func__); + return HDF_FAILURE; + } + powerMgrimpl = (struct PowerManagerImpl*)powerMgr; + ret = HdfWlanSingleDeActive(&powerMgrimpl->powerDatas.power0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: the main power off fail", __func__); + return HDF_FAILURE; + } + ret = HdfWlanSingleDeActive((struct HdfConfigWlanPower*)&powerMgrimpl->powerDatas.power1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: the standby power off fail", __func__); + return ret; + } + return HDF_SUCCESS; +} + +int32_t HdfWlanPowerMgrRelease(struct PowerManager* powerMgr) +{ + if (powerMgr == NULL) { + HDF_LOGW("%s: powerMgr already deinit or input para error ", __func__); + return HDF_SUCCESS; + } + OsalMemFree(powerMgr); + return HDF_SUCCESS; +} +/** + * @brief create powers manager accoding to the powers config + */ +struct PowerManager* HdfWlanCreatePowerManager(const struct HdfConfWlanPowers *configPowers) +{ + if (configPowers == NULL) { + HDF_LOGE("%s: configPowers is NULL", __func__); + return NULL; + } + struct PowerManagerImpl *powerMgrimpl = NULL; + powerMgrimpl = (struct PowerManagerImpl *)OsalMemCalloc(sizeof(struct PowerManagerImpl)); + if (powerMgrimpl == NULL) { + HDF_LOGE("%s: OsalMemCalloc fail! ", __func__); + return NULL; + } + powerMgrimpl->base.On = HdfWlanChipPowerOn; + powerMgrimpl->base.Off = HdfWlanChipPowerOff; + powerMgrimpl->base.Release = HdfWlanPowerMgrRelease; + powerMgrimpl->powerDatas.power0 = configPowers->power0; + powerMgrimpl->powerDatas.power1 = configPowers->power1; + + return (struct PowerManager *)powerMgrimpl; +} \ No newline at end of file diff --git a/model/network/wifi/platform/src/hdf_wlan_priority_queue.c b/model/network/wifi/platform/src/hdf_wlan_priority_queue.c new file mode 100644 index 00000000..e61c9043 --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_priority_queue.c @@ -0,0 +1,143 @@ +/* + * 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_wlan_priority_queue.h" +#include "securec.h" +#include "osal/osal_sem.h" +#include "osal/osal_mem.h" +#include "utils/hdf_log.h" +#include "hdf_wlan_queue.h" + +#define MAX_PRIORITY_LEVEL 8 + +#define HDF_LOG_TAG HDF_WIFI_CORE + +typedef struct { + PriorityQueue priorityQueue; + uint8_t priorityLevelCount; + OSAL_DECLARE_SEMAPHORE(messageSemaphore); + HdfWlanQueue *queues[0]; +} PriorityQueueImpl; + +PriorityQueue *CreatePriorityQueue(uint16_t queueSize, uint8_t priorityLevelCount) +{ + uint8_t i; + uint32_t queueMemSize; + PriorityQueueImpl *priorityQueue = NULL; + uint32_t ret = HDF_SUCCESS; + if (priorityLevelCount > MAX_PRIORITY_LEVEL || priorityLevelCount == 0) { + HDF_LOGE("%s:priorityLevelCount must in 1 to 8", __func__); + return NULL; + } + queueMemSize = sizeof(PriorityQueueImpl) + (priorityLevelCount * sizeof(HdfWlanQueue *)); + priorityQueue = (PriorityQueueImpl *)OsalMemCalloc(queueMemSize); + if (priorityQueue == NULL) { + return NULL; + } + priorityQueue->priorityLevelCount = priorityLevelCount; + for (i = 0; i < priorityLevelCount; i++) { + priorityQueue->queues[i] = CreateQueue(queueSize); + if (priorityQueue->queues[i] == NULL) { + ret = HDF_FAILURE; + HDF_LOGE("%s:Init message queue failed!QueueID=%d,ret=%d", __func__, i, ret); + break; + } + } + if (ret != HDF_SUCCESS) { + DestroyPriorityQueue((PriorityQueue *)priorityQueue); + return NULL; + } + + HDF_STATUS status = OsalSemInit(&priorityQueue->messageSemaphore, 0); + if (status != HDF_SUCCESS) { + DestroyPriorityQueue((PriorityQueue *)priorityQueue); + return NULL; + } + + return (PriorityQueue *)priorityQueue; +} + +void DestroyPriorityQueue(PriorityQueue *queue) +{ + uint8_t i; + PriorityQueueImpl *queueImpl = (PriorityQueueImpl *)queue; + if (queue == NULL) { + return; + } + + for (i = 0; i < queueImpl->priorityLevelCount; i++) { + if (queueImpl->queues[i] == NULL) { + continue; + } + DestroyQueue(queueImpl->queues[i]); + queueImpl->queues[i] = NULL; + } + HDF_STATUS status = OsalSemDestroy(&queueImpl->messageSemaphore); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:Destroy message queue semaphore failed!status=%d", __func__, status); + } + + OsalMemFree(queueImpl); +} + +int32_t PushPriorityQueue(PriorityQueue *queue, const uint8_t priority, void *context) +{ + uint32_t ret; + uint8_t pri; + PriorityQueueImpl *queueImpl = NULL; + if (queue == NULL || context == NULL) { + return HDF_FAILURE; + } + queueImpl = (PriorityQueueImpl *)queue; + pri = priority; + if (priority >= queueImpl->priorityLevelCount) { + pri = queueImpl->priorityLevelCount - 1; + } + + ret = PushQueue(queueImpl->queues[pri], context); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Write queue failed!ret=%d", __func__, ret); + return ret; + } + + (void)OsalSemPost(&queueImpl->messageSemaphore); + return HDF_SUCCESS; +} + +static void *PopQueueByPri(PriorityQueueImpl *queue) +{ + void *context = NULL; + uint8_t i; + for (i = 0; i < queue->priorityLevelCount; i++) { + context = PopQueue(queue->queues[i]); + if (context != NULL) { + return context; + } + } + return NULL; +} + +void *PopPriorityQueue(PriorityQueue *queue, uint32_t waitInMS) +{ + PriorityQueueImpl *queueImpl = (PriorityQueueImpl *)queue; + void *context = NULL; + HDF_STATUS status; + if (queue == NULL) { + return NULL; + } + + context = PopQueueByPri(queueImpl); + if (context != NULL || waitInMS == 0) { + return context; + } + + status = OsalSemWait(&queueImpl->messageSemaphore, waitInMS); + if (status != HDF_SUCCESS) { + return NULL; + } + return PopQueueByPri(queueImpl); +} diff --git a/model/network/wifi/platform/src/hdf_wlan_product.c b/model/network/wifi/platform/src/hdf_wlan_product.c new file mode 100644 index 00000000..6c75f2ba --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_product.c @@ -0,0 +1,110 @@ +/* + * 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_wifi_product.h" +#include "hdf_wlan_chipdriver_manager.h" +#include "hdf_wlan_utils.h" +#include "securec.h" + +#define MAX_WLAN_DEVICE 3 +/** + * @brief Defines the Product Data. + * + * @since 1.0 + */ +struct HdfWifiProductData { + char state; /* *< WLAN module state */ + struct WifiModule module; /* *< Structure of the WLAN module */ + struct HdfDeviceObject *device; /* *< Structure of the Device Object */ + struct HdfWlanDevice *wlanDevice[MAX_WLAN_DEVICE]; +}; + +static struct HdfWifiProductData *g_hdfWlanProductData = NULL; + +int HdfWlanAddDevice(struct HdfWlanDevice *device) +{ + uint8_t i; + if (device == NULL) { + HDF_LOGE("%s:input is NULL!", __func__); + return HDF_FAILURE; + } + if (g_hdfWlanProductData == NULL) { + HDF_LOGE("%s:please Init product first!", __func__); + return HDF_FAILURE; + } + for (i = 0; i < MAX_WLAN_DEVICE; i++) { + if (g_hdfWlanProductData->wlanDevice[i] == NULL) { + g_hdfWlanProductData->wlanDevice[i] = device; + device->id = i; + return HDF_SUCCESS; + } + } + HDF_LOGE("%s: device list has full!", __func__); + return HDF_FAILURE; +} + +int HdfWlanInitProduct(struct HdfDeviceObject *device, const struct HdfConfigWlanModuleConfig *config) +{ + int ret; + if (g_hdfWlanProductData != NULL) { + HDF_LOGE("%s:already inited!", __func__); + return HDF_FAILURE; + } + g_hdfWlanProductData = OsalMemCalloc(sizeof(struct HdfWifiProductData)); + if (g_hdfWlanProductData == NULL) { + HDF_LOGE("%s:oom", __func__); + return HDF_FAILURE; + } + ret = InitWifiModule(&(g_hdfWlanProductData->module), config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:InitWifiModule failed! ret=%d", __func__, ret); + OsalMemFree(g_hdfWlanProductData); + g_hdfWlanProductData = NULL; + return ret; + } + g_hdfWlanProductData->device = device; + + return HDF_SUCCESS; +} + +int HdfWlanSendBroadcastEvent(uint32_t id, const struct HdfSBuf *data) +{ + if (g_hdfWlanProductData == NULL) { + return HDF_FAILURE; + } + return HdfDeviceSendEvent(g_hdfWlanProductData->device, id, data); +} + +struct WifiModule *HdfWlanGetModule(void) +{ + if (g_hdfWlanProductData == NULL) { + return NULL; + } + return &g_hdfWlanProductData->module; +} + +struct HdfDeviceObject *HdfWlanGetDevice(void) +{ + return g_hdfWlanProductData->device; +} + +struct HdfWlanDevice *HdfWlanGetWlanDevice(uint8_t chipId) +{ + if (chipId >= MAX_WLAN_DEVICE) { + return NULL; + } + return g_hdfWlanProductData->wlanDevice[chipId]; +} + +void HdfWlanDeinitProduct(void) +{ + if (g_hdfWlanProductData != NULL) { + OsalMemFree(g_hdfWlanProductData); + g_hdfWlanProductData = NULL; + } +} diff --git a/model/network/wifi/platform/src/hdf_wlan_reset_manager.c b/model/network/wifi/platform/src/hdf_wlan_reset_manager.c new file mode 100644 index 00000000..188950b8 --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_reset_manager.c @@ -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. + */ +#include "gpio_if.h" +#include "osal_mem.h" +#include "hdf_log.h" +#include "wifi_module.h" +#include "hdf_wlan_chipdriver_manager.h" +#include "securec.h" + +#define HDF_LOG_TAG HDF_WIFI_CORE + +/** + * @brief constant reset manage type + */ +enum ResetType { + ResetAlwaysOn = 0, + ResetManagedByGPIO = 1 +}; + +struct HdfWlanResetData { + struct HdfConfWlanRest resetCfg; + uint8_t bootUpHoldTime; +}; + +struct ResetManagerImpl { + struct ResetManager base; + struct HdfWlanResetData resetData; +}; + +/** + * @brief HdfChipReset + */ +int32_t HdfChipReset(struct ResetManager *resetManager) +{ + int32_t ret; + struct ResetManagerImpl *resetMgrImpl = NULL; + if (resetManager == NULL) { + HDF_LOGE("%s: resetManager is NULL", __func__); + return HDF_FAILURE; + } + resetMgrImpl = (struct ResetManagerImpl*)resetManager; + if (resetMgrImpl->resetData.resetCfg.resetType == ResetAlwaysOn) { + HDF_LOGE("%s: the reset type is not managed", __func__); + return HDF_FAILURE; + } + ret = GpioSetDir(resetMgrImpl->resetData.resetCfg.gpioId, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set dir fail!", __func__); + return ret; + } + ret = GpioWrite(resetMgrImpl->resetData.resetCfg.gpioId, resetMgrImpl->resetData.resetCfg.activeLevel); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: write active fail! ret=%d", __func__, ret); + return ret; + } + OsalMSleep(resetMgrImpl->resetData.resetCfg.resetHoldTime); + + ret = GpioWrite(resetMgrImpl->resetData.resetCfg.gpioId, !resetMgrImpl->resetData.resetCfg.activeLevel); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: write deactive fail! ret=%d", __func__, ret); + return ret; + } + OsalMSleep(resetMgrImpl->resetData.bootUpHoldTime); + + return HDF_SUCCESS; +} +/* to release reset manager resource */ +int32_t HdfWlanResetMgrRelease(struct ResetManager* resetMgr) +{ + if (resetMgr == NULL) { + HDF_LOGE("%s: resetMgr already deinit or input para error ", __func__); + return HDF_FAILURE; + } + OsalMemFree(resetMgr); + return HDF_SUCCESS; +} +/* create power reset manager */ +struct ResetManager* HdfWlanCreateResetManager(const struct HdfConfWlanRest *configReset, uint8_t bootUpTime) +{ + struct ResetManagerImpl *resetMgrImpl = NULL; + if (configReset == NULL) { + HDF_LOGE("%s: configReset is NULL", __func__); + return NULL; + } + resetMgrImpl = (struct ResetManagerImpl *)OsalMemCalloc(sizeof(struct ResetManagerImpl)); + if (resetMgrImpl == NULL) { + HDF_LOGE("%s: OsalMemCalloc fail! ", __func__); + return NULL; + } + if (memcpy_s(&resetMgrImpl->resetData.resetCfg, sizeof(struct HdfConfWlanRest), + configReset, sizeof(struct HdfConfWlanRest)) != EOK) { + HDF_LOGE("%s: memcpy_s is NULL", __func__); + OsalMemFree(resetMgrImpl); + return NULL; + } + resetMgrImpl->resetData.bootUpHoldTime = bootUpTime; + resetMgrImpl->base.Reset = HdfChipReset; + resetMgrImpl->base.Release = HdfWlanResetMgrRelease; + + return (struct ResetManager*)resetMgrImpl; +} \ No newline at end of file diff --git a/model/network/wifi/platform/src/hdf_wlan_utils.c b/model/network/wifi/platform/src/hdf_wlan_utils.c new file mode 100644 index 00000000..8309ceb8 --- /dev/null +++ b/model/network/wifi/platform/src/hdf_wlan_utils.c @@ -0,0 +1,275 @@ +/* + * 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_wlan_utils.h" +#include +#include "hdf_log.h" +#include "wifi_module.h" +#include "hdf_wlan_chipdriver_manager.h" + +const char * const HDF_WIFI_PLATFORM_DRIVER_NAME = "HDF_WIFI_PLATFORM_DRIVER"; + +const char *GetPlatformDriverName(void) +{ + return HDF_WIFI_PLATFORM_DRIVER_NAME; +} + +struct HdfWifiNetDeviceData *GetPlatformData(const struct NetDevice *netDev) +{ + if (netDev == NULL) { + return NULL; + } + + if (netDev->classDriverName != HDF_WIFI_PLATFORM_DRIVER_NAME) { + return NULL; + } + + return (struct HdfWifiNetDeviceData *)(netDev->classDriverPriv); +} + +struct HdfChipDriver *GetChipDriver(const struct NetDevice *netDev) +{ + struct HdfWifiNetDeviceData *data = GetPlatformData(netDev); + if (data != NULL) { + return data->chipDriver; + } + return NULL; +} + +struct WlanHwCapability *GetHwCapability(struct NetDevice *netDev) +{ + struct HdfChipDriver *chipDriver = GetChipDriver(netDev); + struct WlanHwCapability *capability = NULL; + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return NULL; + } + if (chipDriver->ops == NULL || chipDriver->ops->GetHwCapability == NULL) { + HDF_LOGE("%s: chipdriver not implemented", __func__); + return NULL; + } + int32_t ret = chipDriver->ops->GetHwCapability(netDev, &capability); + if (ret != HDF_SUCCESS || capability == NULL) { + HDF_LOGE("%s:GetHwCapability failed!ifName=%s,ret=%d", __func__, netDev->name, ret); + return NULL; + } + return capability; +} + +static uint32_t g_allocatedIfMap = 0; + +#define SET_BIT(target, bit) (target) = ((target) | ((0x1) << (bit))) +#define CLEAR_BIT(target, bit) (target) = ((target) & (~((0x1) << (bit)))) + +int32_t RenewNetDevice(NetDevice **netDev) +{ + char ifName[IFNAMSIZ] = ""; + NetDevice *result = NULL; + struct HdfWifiNetDeviceData *data = NULL; + int32_t ret; + if (netDev == NULL) { + HDF_LOGE("%s:NULL ptr!", __func__); + return HDF_FAILURE; + } + if ((*netDev)->classDriverName != HDF_WIFI_PLATFORM_DRIVER_NAME) { + HDF_LOGE("%s:bad net device!", __func__); + return HDF_FAILURE; + } + if (strcpy_s(ifName, IFNAMSIZ, (*netDev)->name) < 0) { + HDF_LOGE("%s:Copy ifName failed!", __func__); + return HDF_FAILURE; + } + data = GetPlatformData(*netDev); + if (data == NULL) { + HDF_LOGE("%s:GetPlatformData failed!", __func__); + return HDF_FAILURE; + } + + ret = NetDeviceDeInit(*netDev); + if (ret != HDF_SUCCESS) { + return ret; + } + *netDev = NULL; +#ifdef _PRE_HDF_LINUX + result = NetDeviceInit(ifName, strlen(ifName), FULL_OS); +#else + result = NetDeviceInit(ifName, strlen(ifName), LITE_OS); +#endif + if (result == NULL) { + HDF_LOGE("%s:alloc NetDevice return NULL!", __func__); + if (data->device != NULL) { + CLEAR_BIT(data->device->netIfMap, data->netInterfaceId); + } + CLEAR_BIT(g_allocatedIfMap, data->netInterfaceId); + OsalMemFree(data); + *netDev = NULL; + return HDF_FAILURE; + } + result->classDriverName = HDF_WIFI_PLATFORM_DRIVER_NAME; + result->classDriverPriv = data; + *netDev = result; + return HDF_SUCCESS; +} + +int32_t GetPlatformIfName(uint8_t id, char *ifName, uint32_t ifNameSize) +{ + if (ifName == NULL || ifNameSize == 0) { + HDF_LOGE("%s:para is null!", __func__); + return HDF_FAILURE; + } + + if (snprintf_s(ifName, ifNameSize, ifNameSize - 1, "wlan%d", id) < 0) { + HDF_LOGE("%s:format ifName failed!netDevice id=%u", __func__, id); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +struct NetDevice *AllocPlatformNetDevice(struct HdfWlanDevice *device) +{ + uint8_t i; + int32_t ret; + uint8_t id = MAX_IF_COUNT; + struct NetDevice *result = NULL; + char ifName[IFNAMSIZ] = {0}; + struct HdfWifiNetDeviceData *data = NULL; + if (device == NULL) { + return NULL; + } + data = (struct HdfWifiNetDeviceData *)OsalMemCalloc(sizeof(struct HdfWifiNetDeviceData)); + if (data == NULL) { + HDF_LOGE("%s:oom!", __func__); + return NULL; + } + do { + for (i = 0; i < MAX_IF_COUNT; i++) { + if (((g_allocatedIfMap >> i) & 0x1) != 0x1) { + id = i; + break; + } + } + if (id >= MAX_IF_COUNT) { + HDF_LOGE("%s: not enough if!map=%u", __func__, g_allocatedIfMap); + break; + } + + ret = GetPlatformIfName(id, ifName, IFNAMSIZ); + if (ret != HDF_SUCCESS) { + OsalMemFree(data); + break; + } +#ifdef _PRE_HDF_LINUX + result = NetDeviceInit(ifName, strlen(ifName), FULL_OS); +#else + result = NetDeviceInit(ifName, strlen(ifName), LITE_OS); +#endif + } while (false); + if (result == NULL) { + HDF_LOGE("%s:alloc NetDevice return NULL!", __func__); + OsalMemFree(data); + return result; + } + result->classDriverName = HDF_WIFI_PLATFORM_DRIVER_NAME; + result->classDriverPriv = data; + data->netInterfaceId = id; + SET_BIT(device->netIfMap, id); + SET_BIT(g_allocatedIfMap, id); + return result; +} + +int32_t ReleasePlatformNetDevice(struct NetDevice *netDev) +{ + uint8_t id; + struct HdfWifiNetDeviceData *data = NULL; + int32_t ret; + + if (netDev == NULL) { + HDF_LOGE("%s:NULL ptr!", __func__); + return HDF_FAILURE; + } + if (netDev->classDriverName != HDF_WIFI_PLATFORM_DRIVER_NAME) { + HDF_LOGE("%s:Wrong net device!", __func__); + return HDF_FAILURE; + } + + data = GetPlatformData(netDev); + if (data == NULL) { + HDF_LOGE("%s:GetPlatformData failed!", __func__); + return HDF_FAILURE; + } + id = data->netInterfaceId; + + ret = NetDeviceDeInit(netDev); + if (ret != HDF_SUCCESS) { + return ret; + } + if (data->device != NULL) { + CLEAR_BIT(data->device->netIfMap, id); + } + CLEAR_BIT(g_allocatedIfMap, id); + OsalMemFree(data); + return HDF_SUCCESS; +} + +char *HdfWlanGetIfNames(const uint8_t chipId, uint8_t *ifNameCount) +{ + struct HdfWlanDevice *wlanDevice = NULL; + uint32_t netIfMapTemp; + char *ifNames = NULL; + uint32_t bufferSize; + uint8_t i, j; + if (ifNameCount == NULL) { + HDF_LOGE("%s: para is NULL", __func__); + return NULL; + } + + wlanDevice = HdfWlanGetWlanDevice(chipId); + if (wlanDevice == NULL) { + HDF_LOGE("%s:wlanDevice is NULL, not found!", __func__); + return NULL; + } + *ifNameCount = 0; + netIfMapTemp = wlanDevice->netIfMap; + for (i = 0; i < MAX_IF_COUNT; i++) { + if (((netIfMapTemp >> i) & 0x1) != 0) { + (*ifNameCount)++; + } + } + + if (*ifNameCount == 0) { + // Never alloc 0 size + bufferSize = sizeof(char); + } else { + bufferSize = IFNAMSIZ * (uint32_t)(*ifNameCount); + } + + ifNames = (char *)OsalMemCalloc(bufferSize); + if (ifNames == NULL) { + HDF_LOGE("%s: oom!", __func__); + return NULL; + } + + if (ifNameCount == 0) { + return ifNames; + } + + for (i = 0, j = 0; i < MAX_IF_COUNT; i++) { + if (((netIfMapTemp >> i) & 0x1) == 0) { + continue; + } + int32_t ret = GetPlatformIfName(i, ifNames + (j * IFNAMSIZ), IFNAMSIZ); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Get ifName failed!ret=%d", __func__, ret); + OsalMemFree(ifNames); + return NULL; + } + j++; + } + + return ifNames; +} diff --git a/model/network/wifi/platform/src/message/message_dispatcher.c b/model/network/wifi/platform/src/message/message_dispatcher.c new file mode 100644 index 00000000..97d5747a --- /dev/null +++ b/model/network/wifi/platform/src/message/message_dispatcher.c @@ -0,0 +1,425 @@ +/* + * 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 "securec.h" +#include "osal/osal_thread.h" +#include "osal/osal_time.h" +#include "osal/osal_mutex.h" +#include "utils/hdf_log.h" +#include "message_dispatcher.h" +#include "hdf_wlan_priority_queue.h" +#include "message_router_inner.h" + +#ifdef USERSPACE_CLIENT_SUPPORT +#define HDF_LOG_TAG UMsgEngine +#else +#define HDF_LOG_TAG KMsgEngine +#endif + +typedef struct { + INHERT_MESSAGE_DISPATCHER; + OSAL_DECLARE_THREAD(dispatcherThread); +} LocalMessageDispatcher; + +void ReleaseMessageContext(MessageContext *context) +{ + if (context == NULL) { + return; + } + if (context->rspData != NULL) { + HdfSBufRecycle(context->rspData); + context->rspData = NULL; + } + + if (context->corssNode || + (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) { + HdfSBufRecycle(context->reqData); + context->reqData = NULL; + } + OsalMemFree(context); + } +} + +void ReleaseMessageMapper(struct ServiceDef *mapper) +{ + if (mapper == NULL) { + return; + } + if (mapper->messages != NULL) { + OsalMemFree(mapper->messages); + mapper->messages = NULL; + } + OsalMemFree(mapper); +} + +struct MessageDef *GetMsgDef(const struct ServiceDef *serviceDef, uint32_t commandId) +{ + if (serviceDef == NULL || serviceDef->messages == NULL) { + HDF_LOGE("%s:input is NULL!", __func__); + return NULL; + } + if (commandId >= serviceDef->messagesLength) { + HDF_LOGE("%s:commandId exceed service def!", __func__); + return NULL; + } + + struct MessageDef *msgDef = serviceDef->messages + commandId; + if (msgDef->handler == NULL) { + HDF_LOGE("%s:command has no handler!", __func__); + return NULL; + } + return msgDef; +} + +ErrorCode AppendToLocalDispatcher(MessageDispatcher *dispatcher, const uint8_t priority, MessageContext *context) +{ + if (context == NULL) { + HDF_LOGE("%s:Input context is NULL!", __func__); + return ME_ERROR_NULL_PTR; + } + if (dispatcher == NULL) { + HDF_LOGE("%s:Input dispatcher is NULL!", __func__); + return ME_ERROR_NULL_PTR; + } + + if (dispatcher->messageQueue == NULL) { + HDF_LOGE("MessageQueue is NULL."); + return ME_ERROR_NULL_PTR; + } + + if (dispatcher->status != ME_STATUS_RUNNING) { + HDF_LOGE("%s:dispatcher is not running", __func__); + return ME_ERROR_DISPATCHER_NOT_RUNNING; + } + return PushPriorityQueue(dispatcher->messageQueue, priority, context); +} + +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); + return; + } + ServiceId senderId = context->senderId; + context->senderId = context->receiverId; + context->receiverId = senderId; + context->requestType = MESSAGE_RSP_START + context->requestType - MESSAGE_REQ_START; +} + +static void HandleAsyncResponse(MessageContext *context) +{ + if (context == NULL) { + return; + } + + if (context->callback != NULL) { + context->callback((RequestContext *)context, context->reqData, context->rspData, context->responseStatus); + } + + ReleaseMessageContext(context); + context = NULL; +} + +static void HandleSyncResponse(MessageContext *context) +{ + if (context == NULL) { + HDF_LOGE("Input context is NULL!"); + return; + } + 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, + context->receiverId); + } + return; +} + +static void HandleRequestMessage(MessageContext *context) +{ + RemoteService *targetService = RefRemoteService(context->receiverId); + ErrorCode errCode = ME_SUCCESS; + RemoteService *rspService = NULL; + do { + if (targetService == NULL) { + HDF_LOGE("%s:Service %d 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); + errCode = ME_ERROR_NULL_PTR; + break; + } + targetService->ExecRequestMsg(targetService, context); + + // Convert to response message + SetToResponse(context); + + if (context->requestType == MESSAGE_TYPE_ASYNC_RSP && context->callback == NULL) { + ReleaseMessageContext(context); + break; + } + + rspService = RefRemoteService(context->receiverId); + if (rspService == NULL) { + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + if (rspService->SendMessage == NULL) { + errCode = ME_ERROR_BAD_SERVICE; + break; + } + errCode = rspService->SendMessage(rspService, context); + } while (false); + + if (errCode != ME_SUCCESS) { + if (context->requestType == MESSAGE_TYPE_SYNC_RSP || context->requestType == MESSAGE_TYPE_SYNC_REQ) { + (void)OsalSemPost(&context->rspSemaphore); + } else { + ReleaseMessageContext(context); + } + } + + if (targetService != NULL && targetService->Disref != NULL) { + targetService->Disref(targetService); + targetService = NULL; + } + + if (rspService != NULL && rspService->Disref != NULL) { + rspService->Disref(rspService); + rspService = NULL; + } +} + +static void HandleMessage(MessageContext *context) +{ + if (context != NULL) { + switch (context->requestType) { + case MESSAGE_TYPE_SYNC_REQ: + case MESSAGE_TYPE_ASYNC_REQ: + HandleRequestMessage(context); + break; + case MESSAGE_TYPE_SYNC_RSP: + HandleSyncResponse(context); + break; + case MESSAGE_TYPE_ASYNC_RSP: + HandleAsyncResponse(context); + break; + default: + HDF_LOGE("Unsupported message type %d", context->requestType); + } + } +} + +static void ReleaseAllMessage(MessageDispatcher *dispatcher) +{ + MessageContext *context = NULL; + do { + context = PopPriorityQueue(dispatcher->messageQueue, 0); + ReleaseMessageContext(context); + } while (context != NULL); +} + +static int RunDispatcher(void *para) +{ + if (para == NULL) { + HDF_LOGE("Start dispatcher failed! cause:%s\n", "input para is NULL"); + return ME_ERROR_NULL_PTR; + } + MessageDispatcher *dispatcher = (MessageDispatcher *)para; + if (dispatcher->messageQueue == NULL) { + HDF_LOGE("Start dispatcher failed! cause:%s\n", "message queue is NULL"); + return ME_ERROR_NULL_PTR; + } + + if (dispatcher->Ref != NULL) { + dispatcher = dispatcher->Ref(dispatcher); + } + + if (dispatcher->status != ME_STATUS_STARTTING) { + if (dispatcher->Disref != NULL) { + dispatcher->Disref(dispatcher); + } + HDF_LOGE("Start dispatcher failed! cause:%s\n", "dispatcher is not stopped"); + return ME_ERROR_WRONG_STATUS; + } else { + dispatcher->status = ME_STATUS_RUNNING; + } + while (dispatcher->status == ME_STATUS_RUNNING) { + MessageContext *context = PopPriorityQueue(dispatcher->messageQueue, QUEUE_OPER_TIMEOUT); + if (context == NULL) { + continue; + } + HandleMessage(context); + } + + ReleaseAllMessage(dispatcher); + dispatcher->status = ME_STATUS_TODESTROY; + if (dispatcher->Disref != NULL) { + dispatcher->Disref(dispatcher); + dispatcher = NULL; + } + + HDF_LOGW("Dispatcher shutdown!"); + return ME_SUCCESS; +} + +static ErrorCode StartDispatcher(MessageDispatcher *dispatcher) +{ + if (dispatcher == NULL) { + return ME_ERROR_NULL_PTR; + } + HDF_STATUS status = OsalMutexTimedLock(&dispatcher->mutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + return ME_ERROR_OPER_MUTEX_FAILED; + } + ErrorCode errCode = ME_SUCCESS; + do { + if (dispatcher->status != ME_STATUS_STOPPED) { + errCode = ME_ERROR_WRONG_STATUS; + break; + } + dispatcher->status = ME_STATUS_STARTTING; + struct OsalThreadParam config = { + .name = "MessageDispatcher", + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = 0x2000, + }; + LocalMessageDispatcher *localDispatcher = (LocalMessageDispatcher *)dispatcher; + status = OsalThreadCreate(&localDispatcher->dispatcherThread, RunDispatcher, localDispatcher); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadCreate failed!status=%d", __func__, status); + dispatcher->status = ME_STATUS_STOPPED; + errCode = ME_ERROR_CREATE_THREAD_FAILED; + break; + } + status = OsalThreadStart(&localDispatcher->dispatcherThread, &config); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadStart failed!status=%d", __func__, status); + dispatcher->status = ME_STATUS_STOPPED; + OsalThreadDestroy(&localDispatcher->dispatcherThread); + errCode = ME_ERROR_CREATE_THREAD_FAILED; + break; + } + } while (false); + + status = OsalMutexUnlock(&dispatcher->mutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:Destroy mutex failed!", __func__); + } + + if (errCode != ME_SUCCESS) { + return errCode; + } + + do { + OsalMSleep(1); + } while (dispatcher->status == ME_STATUS_STARTTING); + + if (dispatcher->status == ME_STATUS_RUNNING) { + return ME_SUCCESS; + } else { + return ME_ERROR_WRONG_STATUS; + } +} + +static void ShutdownDispatcher(MessageDispatcher *dispatcher) +{ + if (dispatcher == NULL) { + return; + } + + HDF_STATUS status = OsalMutexTimedLock(&dispatcher->mutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Get lock failed!status=%d", status); + return; + } + + do { + if (dispatcher->status != ME_STATUS_RUNNING && dispatcher->status != ME_STATUS_STARTTING) { + HDF_LOGE("%s:wrong status.status=%d", __func__, dispatcher->status); + break; + } + dispatcher->status = ME_STATUS_STOPPING; + } while (false); + + status = OsalMutexUnlock(&dispatcher->mutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:Destroy mutex failed!", __func__); + } +} + +IMPLEMENT_SHARED_OBJ(MessageDispatcher); +static void DestroyLocalDispatcher(MessageDispatcher *dispatcher) +{ + if (dispatcher == NULL) { + return; + } + + ReleaseAllMessage(dispatcher); + + if (dispatcher->messageQueue != NULL) { + DestroyPriorityQueue(dispatcher->messageQueue); + dispatcher->messageQueue = NULL; + } + + int32_t ret = OsalMutexDestroy(&dispatcher->mutex); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Release mutex failed.ret=%d", __func__, ret); + } + + DEINIT_SHARED_OBJ(MessageDispatcher, dispatcher); +} + +ErrorCode CreateLocalDispatcher(MessageDispatcher **dispatcher, const DispatcherConfig *config) +{ + if (dispatcher == NULL || config == NULL) { + return ME_ERROR_NULL_PTR; + } + + LocalMessageDispatcher *localDispatcher = (LocalMessageDispatcher *)OsalMemCalloc(sizeof(LocalMessageDispatcher)); + if (localDispatcher == NULL) { + return ME_ERROR_RES_LAKE; + } + + ErrorCode errCode; + do { + localDispatcher->status = ME_STATUS_STOPPED; + localDispatcher->AppendMessage = AppendToLocalDispatcher; + localDispatcher->Shutdown = ShutdownDispatcher; + localDispatcher->Start = StartDispatcher; + + localDispatcher->messageQueue = CreatePriorityQueue(config->queueSize, config->priorityLevelCount); + if (localDispatcher->messageQueue == NULL) { + errCode = ME_ERROR_OPER_QUEUE_FAILED; + break; + } + + int32_t ret = OsalMutexInit(&localDispatcher->mutex); + if (ret != HDF_SUCCESS) { + errCode = ME_ERROR_OPER_MUTEX_FAILED; + break; + } + + errCode = INIT_SHARED_OBJ(MessageDispatcher, (MessageDispatcher *)localDispatcher, DestroyLocalDispatcher); + if (errCode != ME_SUCCESS) { + break; + } + } while (false); + + if (errCode == ME_SUCCESS) { + *dispatcher = (MessageDispatcher *)localDispatcher; + } else { + DestroyLocalDispatcher((MessageDispatcher *)localDispatcher); + OsalMemFree(localDispatcher); + } + return errCode; +} diff --git a/model/network/wifi/platform/src/message/message_dispatcher.h b/model/network/wifi/platform/src/message/message_dispatcher.h new file mode 100644 index 00000000..f56f708f --- /dev/null +++ b/model/network/wifi/platform/src/message/message_dispatcher.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 MESSAGE_DISPATCHER_H +#define MESSAGE_DISPATCHER_H +#include "osal/osal_mutex.h" +#include "hdf_wlan_priority_queue.h" +#include "shared_obj.h" +#include "sidecar.h" +#include "message_config.h" + +#define BAD_DISPATCHER_ID 255 +#define DISPATCHER_ID_AUTO 254 + +#define MAX_PRI_LEVEL_COUNT 3 + +struct MessageDispatcher; + +#define INHERT_MESSAGE_DISPATCHER \ + SHARED_OBJ(MessageDispatcher); \ + OSAL_DECLARE_MUTEX(mutex); \ + ErrorCode (*AppendMessage)(struct MessageDispatcher *, const uint8_t priority, MessageContext * context); \ + ErrorCode (*Start)(struct MessageDispatcher * dispatcher); \ + void (*Shutdown)(struct MessageDispatcher * dispatcher); \ + PriorityQueue *messageQueue + +typedef struct MessageDispatcher { + INHERT_MESSAGE_DISPATCHER; +} MessageDispatcher; + +void ReleaseMessageMapper(struct ServiceDef *mapper); +void ReleaseMessageContext(MessageContext *context); +void SetToResponse(MessageContext *context); + +struct MessageDef* GetMsgDef(const struct ServiceDef *mapper, uint32_t commandID); + +ErrorCode CreateLocalDispatcher(MessageDispatcher **dispatcher, const DispatcherConfig *config); + +#endif diff --git a/model/network/wifi/platform/src/message/message_router.c b/model/network/wifi/platform/src/message/message_router.c new file mode 100644 index 00000000..ab77a65d --- /dev/null +++ b/model/network/wifi/platform/src/message/message_router.c @@ -0,0 +1,713 @@ +/* + * 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_base.h" +#ifdef USERSPACE_CLIENT_SUPPORT +#include +#include +#endif +#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" + +#ifdef USERSPACE_CLIENT_SUPPORT +#define HDF_LOG_TAG UMsgEngine +#else +#define HDF_LOG_TAG KMsgEngine +#endif + +#ifndef UINT8_MAX +#define UINT8_MAX 256 +#endif + +#if MESSAGE_ENGINE_MAX_DISPATCHER > UINT8_MAX +#error Max MESSAGE_ENGINE_MAX_DISPATCHER is UINT8_MAX +#endif + +IMPLEMENT_SHARED_OBJ(MessageNode); +IMPLEMENT_SHARED_OBJ(RemoteService); + +typedef struct { + uint8_t nodeIndex; + DispatcherId dispatcherId; + RemoteService *remoteService; +} ServiceInfo; + +#define MAX_NODE_COUNT 2 + +OSAL_DECLARE_MUTEX(g_routerMutex) = { + .realMutex = NULL +}; + +static ServiceInfo g_servicesIndex[MESSAGE_ENGINE_MAX_SERVICE] = {0}; + +static MessageNode *g_messageNodes[MAX_NODE_COUNT] = { 0, 0}; + +MessageDispatcher *g_dispatchers[MESSAGE_ENGINE_MAX_DISPATCHER] = {0}; + +static uint8_t g_routerStatus = ME_STATUS_STOPPED; + +static void ReleaseRemoteService(RemoteService *service) +{ + if (service == NULL) { + return; + } + if (service->Shutdown != NULL) { + service->Shutdown(service); + } + if (service->Disref != NULL) { + service->Disref(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); + return NULL; + } + + if (requireLock) { + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return NULL; + } + } + MessageDispatcher *result = NULL; + do { + if (g_dispatchers[dispatcherId] == NULL) { + break; + } + + if (g_dispatchers[dispatcherId]->Ref == NULL) { + break; + } + result = g_dispatchers[dispatcherId]->Ref(g_dispatchers[dispatcherId]); + } while (false); + + if (requireLock) { + HDF_STATUS status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to unlock!status=%d", status); + } + } + return result; +} + +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); + return ME_ERROR_PARA_WRONG; + } + + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + ErrorCode errCode = ME_SUCCESS; + do { + if (g_routerStatus != ME_STATUS_RUNNING) { + errCode = ME_ERROR_WRONG_STATUS; + break; + } + if (g_dispatchers[dispatcherId] != NULL) { + HDF_LOGE("%s:DispatcherId conflict!ID=%d", __func__, dispatcherId); + errCode = ME_ERROR_DISPATCHERID_CONFLICT; + } else { + g_dispatchers[dispatcherId] = dispatcher; + } + } while (false); + + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to unlock!status=%d", status); + } + return errCode; +} + +ErrorCode AddDispatcher(DispatcherConfig *config) +{ + if (config == NULL) { + return ME_ERROR_NULL_PTR; + } + MessageDispatcher *dispatcher = NULL; + ErrorCode errCode = CreateLocalDispatcher(&dispatcher, config); + if (errCode != ME_SUCCESS) { + return errCode; + } + if (dispatcher == NULL) { + HDF_LOGE("%s:CreateDispatcher return NULL!", __func__); + return ME_ERROR_NULL_PTR; + } + do { + 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); + break; + } + } + errCode = RegDispatcher(config->dispatcherId, dispatcher); + } while (false); + + if (errCode != ME_SUCCESS && dispatcher->Shutdown != NULL) { + dispatcher->Shutdown(dispatcher); + } + if (errCode != ME_SUCCESS && dispatcher->Disref != NULL) { + dispatcher->Disref(dispatcher); + } + return errCode; +} + +static void NotifyAllNodesServiceDel(const NodeId nodeId, ServiceId serviceId) +{ + uint8_t i; + for (i = 0; i < MAX_NODE_COUNT; i++) { + if (i == nodeId) { + continue; + } + if (g_messageNodes[i] != NULL && g_messageNodes[i]->NotifyServiceDel != NULL) { + ErrorCode subErrCode = g_messageNodes[i]->NotifyServiceDel(g_messageNodes[i], serviceId); + if (subErrCode != ME_SUCCESS) { + HDF_LOGE("%s:Rollback service add to node failed!nodeId=%d,serviceId=%d,errCode=%d", __func__, i, + serviceId, subErrCode); + } + } + } +} + +static ErrorCode NotifyAllNodesServiceAdd(const NodeId nodeId, struct ServiceDef *mapper) +{ + uint8_t i; + if (mapper == NULL) { + return ME_ERROR_NULL_PTR; + } + + ErrorCode errCode = ME_SUCCESS; + uint8_t notifyNodeIndex; + for (notifyNodeIndex = 0; notifyNodeIndex < MAX_NODE_COUNT; notifyNodeIndex++) { + if (notifyNodeIndex == nodeId) { + continue; + } + if (g_messageNodes[notifyNodeIndex] != NULL && g_messageNodes[notifyNodeIndex]->NotifyServiceAdd != NULL) { + errCode = g_messageNodes[notifyNodeIndex]->NotifyServiceAdd(g_messageNodes[notifyNodeIndex], mapper); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:Notify service add to node failed!nodeId=%d,serviceId=%d,errCode=%d", __func__, + notifyNodeIndex, mapper->serviceId, errCode); + break; + } + } + } + + if (errCode == ME_SUCCESS) { + return ME_SUCCESS; + } + for (i = 0; i < MAX_NODE_COUNT && i < notifyNodeIndex; i++) { + if (i == nodeId) { + continue; + } + if (g_messageNodes[i] != NULL && g_messageNodes[i]->NotifyServiceDel != NULL) { + ErrorCode subErrCode = g_messageNodes[i]->NotifyServiceDel(g_messageNodes[i], mapper->serviceId); + if (subErrCode != ME_SUCCESS) { + HDF_LOGE("%s:Rollback service add to node failed!nodeId=%d,serviceId=%d,errCode=%d", __func__, i, + mapper->serviceId, subErrCode); + } + } + } + return errCode; +} + +static ErrorCode DoRegistService(const NodeId nodeId, const DispatcherId dispatcherId, RemoteService *remoteService) +{ + if (remoteService == NULL) { + return ME_ERROR_NULL_PTR; + } + + if (remoteService->serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + return ME_ERROR_PARA_WRONG; + } + + if (g_routerStatus != ME_STATUS_RUNNING) { + return ME_ERROR_WRONG_STATUS; + } + + HDF_LOGW("%s:Regist service Node:%d;Dispatcher:%d;Service:%d", __func__, nodeId, dispatcherId, + remoteService->serviceId); + + if (g_servicesIndex[remoteService->serviceId].remoteService != NULL) { + HDF_LOGE("%s:Router index find conflict serviceId!", __func__); + return ME_ERROR_SERVICEID_CONFLICT; + } + + g_servicesIndex[remoteService->serviceId].remoteService = remoteService; + g_servicesIndex[remoteService->serviceId].nodeIndex = nodeId; + g_servicesIndex[remoteService->serviceId].dispatcherId = dispatcherId; + + return ME_SUCCESS; +} +static ErrorCode RegistServiceInner(const NodeId nodeId, const DispatcherId dispatcherId, struct ServiceDef *mapper) +{ + if (mapper == NULL) { + return ME_ERROR_NULL_PTR; + } + + if (mapper->serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + HDF_LOGE("%s:serviceId exceed max value! ServiceId=%d", __func__, mapper->serviceId); + return ME_ERROR_PARA_WRONG; + } + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + + MessageNode *node = RefMessageNode(nodeId, false); + if (node == NULL) { + HDF_LOGE("%s:Node not found!", __func__); + return ME_ERROR_NO_SUCH_NODE; + } + RemoteService *remoteService = NULL; + MessageDispatcher *dispatcher = NULL; + + ErrorCode errCode; + do { + if (node->CreateRemoteService == NULL) { + HDF_LOGE("%s:Can not reg service to node %d", __func__, nodeId); + errCode = ME_ERROR_NOT_SUPPORTED; + break; + } + dispatcher = RefDispatcherInner(dispatcherId, false); + + remoteService = node->CreateRemoteService(node, dispatcher, mapper); + if (remoteService == NULL) { + HDF_LOGE("%s:Node create service failed!node=%d", __func__, nodeId); + errCode = ME_ERROR_NULL_PTR; + break; + } + + errCode = NotifyAllNodesServiceAdd(nodeId, mapper); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:NotifyAllNodesServiceAdd failed!err=%d", __func__, errCode); + break; + } + + errCode = DoRegistService(nodeId, dispatcherId, remoteService); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:DoRegistService failed!err=%d.", __func__, errCode); + NotifyAllNodesServiceDel(nodeId, mapper->serviceId); + break; + } + } while (false); + + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to unlock!status=%d", status); + } + + if (dispatcher != NULL && dispatcher->Disref != NULL) { + dispatcher->Disref(dispatcher); + } + if (node != NULL && node->Disref != NULL) { + node->Disref(node); + } + + if (errCode != ME_SUCCESS) { + ReleaseRemoteService(remoteService); + } + + return errCode; +} + +ErrorCode RegistLocalService(const DispatcherId dispatcherId, struct ServiceDef *mapper) +{ + return RegistServiceInner(LOCAL_NODE_INDEX, dispatcherId, mapper); +} + +ErrorCode RegistRemoteService(NodeId nodeId, RemoteService *service) +{ + if (service == NULL) { + return ME_ERROR_NULL_PTR; + } + if (service->serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + HDF_LOGE("%s:serviceId exceed max value! ServiceId=%d", __func__, service->serviceId); + return ME_ERROR_PARA_WRONG; + } + if (nodeId >= MAX_NODE_COUNT) { + HDF_LOGE("%s:NodeId exceed max value! NodeId=%d", __func__, nodeId); + return ME_ERROR_PARA_WRONG; + } + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + + ErrorCode errCode = DoRegistService(nodeId, BAD_DISPATCHER_ID, service); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:RegService failed! errCode=%d", __func__, errCode); + } + + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to unlock!status=%d", status); + } + return errCode; +} +static ErrorCode UnregistServiceInner(const NodeId nodeId, const DispatcherId dispatcherId, const ServiceId serviceId) +{ + if (serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + return ME_ERROR_PARA_WRONG; + } + + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + ErrorCode errCode = ME_SUCCESS; + do { + if (g_servicesIndex[serviceId].nodeIndex != nodeId || g_servicesIndex[serviceId].dispatcherId != dispatcherId) { + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + if (g_servicesIndex[serviceId].remoteService == NULL) { + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + RemoteService *service = g_servicesIndex[serviceId].remoteService; + ReleaseRemoteService(service); + g_servicesIndex[serviceId].remoteService = NULL; + g_servicesIndex[serviceId].nodeIndex = NO_SUCH_NODE_INDEX; + g_servicesIndex[serviceId].dispatcherId = BAD_DISPATCHER_ID; + NotifyAllNodesServiceDel(nodeId, serviceId); + } while (false); + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to unlock!status=%d", status); + } + return errCode; +} + +ErrorCode UnregistLocalService(const DispatcherId dispatcherId, ServiceId serviceId) +{ + return UnregistServiceInner(LOCAL_NODE_INDEX, dispatcherId, serviceId); +} + +ErrorCode UnregistRemoteService(NodeId nodeId, ServiceId serviceId) +{ + (void)nodeId; + return UnregistServiceInner(REMOTE_NODE_INDEX, BAD_DISPATCHER_ID, serviceId); +} +static bool CheckServiceID(ServiceId serviceId, bool allowSync) +{ + if (serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + HDF_LOGE("receiverId exceed MaxServiceID.Route failed!"); + return false; + } + (void)allowSync; + + if (g_servicesIndex[serviceId].remoteService != NULL) { + return true; + } +#ifdef USERSPACE_CLIENT_SUPPORT + if (!allowSync) { + return false; + } + for (uint8_t i = 0; i < MAX_NODE_COUNT; i++) { + if (g_messageNodes[i] != NULL && g_messageNodes[i]->SyncService != NULL) { + (void)g_messageNodes[i]->SyncService(g_messageNodes[i]); + } + } + return CheckServiceID(serviceId, false); +#else + return false; +#endif +} + +RemoteService *RefRemoteService(ServiceId serviceId) +{ + if (serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + return NULL; + } + + if (!CheckServiceID(serviceId, true)) { + return NULL; + } + + RemoteService *service = NULL; + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return NULL; + } + + do { + RemoteService *remoteService = g_servicesIndex[serviceId].remoteService; + if (remoteService != NULL && remoteService->Ref != NULL) { + service = remoteService->Ref(remoteService); + } + } while (false); + + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + } + return service; +} + +ErrorCode SendMessage(MessageContext *context) +{ + RemoteService *service = RefRemoteService(context->receiverId); + if (service == NULL) { + return ME_ERROR_NO_SUCH_SERVICE; + } + ErrorCode errCode; + do { + if (service->SendMessage == NULL) { + errCode = ME_ERROR_NOT_SUPPORTED; + break; + } + errCode = service->SendMessage(service, context); + } while (false); + + if (service->Disref != NULL) { + service->Disref(service); + } + return errCode; +} + +#if defined(KERNEL_SERVER_SUPPORT) || defined(USERSPACE_CLIENT_SUPPORT) +#error("define both KERNEL_SERVER_SUPPORT and USERSPACE_CLIENT_SUPPORT is not allowed!") +#endif + +#if defined(KERNEL_SERVER_SUPPORT) || defined(USERSPACE_CLIENT_SUPPORT) +static ErrorCode CreateRemoteMessageNode(uint8_t nodesConfig) +{ + ErrorCode errCode = ME_SUCCESS; + (void)nodesConfig; + +#ifdef KERNEL_SERVER_SUPPORT + if ((nodesConfig & MESSAGE_NODE_REMOTE_KERNEL_SERVER) != 0) { + HDF_LOGI("Creating kernel server node..."); + errCode = CreateKernelServerNode(&g_messageNodes[REMOTE_NODE_INDEX]); + } +#endif + +#ifdef USERSPACE_CLIENT_SUPPORT + if ((nodesConfig & MESSAGE_NODE_REMOTE_USERSPACE_CLIENT) != 0) { + HDF_LOGI("Creating UserspaceClient server node..."); + errCode = CreateUserspaceClientNode(&g_messageNodes[REMOTE_NODE_INDEX]); + } +#endif + return errCode; +} +#endif + +static ErrorCode InitNodes(void) +{ + ErrorCode errCode = ME_SUCCESS; + uint8_t i; + for (i = 0; i < MAX_NODE_COUNT; i++) { + MessageNode *node = g_messageNodes[i]; + if (node != NULL) { + if (node->Init != NULL) { + errCode = node->Init(node); + } + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s: init node failed!id=%d,ret=%d", __func__, i, errCode); + return errCode; + } + } + } + return ME_SUCCESS; +} + +static void ReleaseNodes(void) +{ + uint8_t i; + for (i = 0; i < MAX_NODE_COUNT; i++) { + MessageNode *node = g_messageNodes[i]; + if (node == NULL) { + continue; + } + if (node->Disref != NULL) { + node->Disref(node); + } + g_messageNodes[i] = NULL; + } +} + +static ErrorCode DoStartMessageRouter(uint8_t nodesConfig) +{ + uint8_t i; + if (g_routerStatus != ME_STATUS_STOPPED) { + HDF_LOGE("Router have already started!"); + return ME_ERROR_MUTI_INIT_NOT_ALLOWED; + } + + for (i = 0; i < UINT8_MAX && 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; + } + + ErrorCode errCode; + do { + HDF_LOGE("%s:Create local node ...", __func__); + errCode = CreateLocalNode(&g_messageNodes[LOCAL_NODE_INDEX]); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:Create local node failed!ret=%d", __func__, errCode); + break; + } +#if defined(KERNEL_SERVER_SUPPORT) || defined(USERSPACE_CLIENT_SUPPORT) + HDF_LOGE("%s:Create remote node ...", __func__); + errCode = CreateRemoteMessageNode(nodesConfig); + if (errCode != ME_SUCCESS) { + HDF_LOGE("%s:Create remote node failed!ret=%d", __func__, errCode); + break; + } +#else + (void)nodesConfig; +#endif + errCode = InitNodes(); + } while (false); + + if (errCode == ME_SUCCESS) { + g_routerStatus = ME_STATUS_RUNNING; + return ME_SUCCESS; + } + + ReleaseNodes(); + return ME_SUCCESS; +} + +ErrorCode EnableDefaultDispatcher(void) +{ + DispatcherConfig config = { + .dispatcherId = DEFAULT_DISPATCHER_ID, + .queueSize = DEFAULT_DISPATCHER_QUEUE_SIZE, + .priorityLevelCount = DEFAULT_DISPATCHER_PRIORITY_COUNT + }; + HDF_LOGI("Regist default dispatcher..."); + ErrorCode errCode = AddDispatcher(&config); + if (errCode != ME_SUCCESS) { + HDF_LOGE("Regist default dispatcher failed!ret=%d", errCode); + } + return errCode; +} + +ErrorCode StartMessageRouter(uint8_t nodesConfig) +{ + if (g_routerMutex.realMutex == NULL) { + HDF_STATUS status = OsalMutexInit(&g_routerMutex); + if (status != HDF_SUCCESS) { + return ME_ERROR_OPER_MUTEX_FAILED; + } + } + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + ErrorCode errCode = DoStartMessageRouter(nodesConfig); + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + } + return errCode; +} + +static ErrorCode DoShutdownMessageRouter(void) +{ + uint8_t i; + if (g_routerStatus == ME_STATUS_STOPPED) { + return ME_SUCCESS; + } + + g_routerStatus = ME_STATUS_STOPPING; + for (i = 0; i < MESSAGE_ENGINE_MAX_SERVICE; i++) { + if (g_servicesIndex[i].remoteService == NULL) { + continue; + } + RemoteService *service = g_servicesIndex[i].remoteService; + g_servicesIndex[i].remoteService = NULL; + g_servicesIndex[i].nodeIndex = NO_SUCH_NODE_INDEX; + g_servicesIndex[i].dispatcherId = BAD_DISPATCHER_ID; + + ReleaseRemoteService(service); + } + + for (i = 0; i < MESSAGE_ENGINE_MAX_DISPATCHER; i++) { + if (g_dispatchers[i] != NULL && g_dispatchers[i]->Shutdown != NULL) { + g_dispatchers[i]->Shutdown(g_dispatchers[i]); + } + if (g_dispatchers[i] != NULL && g_dispatchers[i]->Disref != NULL) { + g_dispatchers[i]->Disref(g_dispatchers[i]); + } + g_dispatchers[i] = NULL; + } + + ReleaseNodes(); + g_routerStatus = ME_STATUS_STOPPED; + return ME_SUCCESS; +} + +ErrorCode ShutdownMessageRouter() +{ + HDF_LOGW("%s:Shutdown router...", __func__); + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + return ME_ERROR_OPER_MUTEX_FAILED; + } + + ErrorCode errCode = DoShutdownMessageRouter(); + + status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("Unable to get lock!status=%d", status); + } + if (errCode == ME_SUCCESS) { + HDF_LOGW("%s:Router down.", __func__); + } + return errCode; +} + +MessageNode *RefMessageNode(const NodeId nodeId, bool isRequireLock) +{ + if (nodeId >= MAX_NODE_COUNT) { + HDF_LOGE("Input nodeId >= MAX_NODE_COUNT"); + return NULL; + } + MessageNode *node = NULL; + if (isRequireLock) { + HDF_STATUS status = OsalMutexTimedLock(&g_routerMutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:require lock failed!", __func__); + return NULL; + } + } + + if (g_messageNodes[nodeId] != NULL && g_messageNodes[nodeId]->Ref != NULL) { + node = g_messageNodes[nodeId]->Ref(g_messageNodes[nodeId]); + } + + if (isRequireLock) { + HDF_STATUS status = OsalMutexUnlock(&g_routerMutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:Unlock mutex failed!", __func__); + } + } + return node; +} diff --git a/model/network/wifi/platform/src/message/message_router_inner.h b/model/network/wifi/platform/src/message/message_router_inner.h new file mode 100644 index 00000000..9359af6b --- /dev/null +++ b/model/network/wifi/platform/src/message/message_router_inner.h @@ -0,0 +1,73 @@ +/* + * 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 MESSAGE_ROUTER_INNER_H +#define MESSAGE_ROUTER_INNER_H +#include "message_types.h" +#include "message_router.h" +#include "message_dispatcher.h" +#include "shared_obj.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct MessageNode; +struct RemoteService; + +#define INHERT_MESSAGE_NODE \ + SHARED_OBJ(MessageNode); \ + OSAL_DECLARE_MUTEX(mutex); \ + ErrorCode (*Init)(struct MessageNode *); \ + struct RemoteService *(*CreateRemoteService)(struct MessageNode *, MessageDispatcher * dispatcher, \ + struct ServiceDef * mapper); \ + ErrorCode (*SyncService)(struct MessageNode *); \ + ErrorCode (*NotifyServiceAdd)(const struct MessageNode *, const struct ServiceDef *mapper); \ + ErrorCode (*NotifyServiceDel)(const struct MessageNode *, const ServiceId serviceId) + +DECLEAR_SHARED_OBJ_FUNC(MessageNode); + +typedef struct MessageNode { + INHERT_MESSAGE_NODE; +} MessageNode; + +#define INHERT_REMOTE_SERVICE SHARED_OBJ(RemoteService); \ + void (*ExecRequestMsg)(const struct RemoteService *service, MessageContext *context); \ + void (*ExecResponseMsg)(const struct RemoteService *service, MessageContext *context); \ + ErrorCode (*SendMessage)(const struct RemoteService *service, MessageContext *context); \ + void (*Shutdown)(struct RemoteService * service); \ + ServiceId serviceId + +DECLEAR_SHARED_OBJ_FUNC(RemoteService); + +typedef struct RemoteService { + INHERT_REMOTE_SERVICE; +} RemoteService; + +RemoteService *RefRemoteService(ServiceId id); + +ErrorCode SendMessage(MessageContext *context); + +ErrorCode CreateLocalNode(MessageNode **node); + +ErrorCode AddDispatcherInner(const NodeId nodeId, DispatcherConfig *config); + +void DestroyDispatcherInner(const NodeId nodeId, const DispatcherId dispatcherId); + +ErrorCode RegistRemoteService(NodeId nodeId, RemoteService *service); + +ErrorCode UnregistRemoteService(NodeId nodeId, ServiceId serviceId); + +MessageNode *RefMessageNode(const NodeId nodeId, bool isRequireLock); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/model/network/wifi/platform/src/message/nodes/local_node.c b/model/network/wifi/platform/src/message/nodes/local_node.c new file mode 100644 index 00000000..5ac55373 --- /dev/null +++ b/model/network/wifi/platform/src/message/nodes/local_node.c @@ -0,0 +1,277 @@ +/* + * 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 "securec.h" +#include "hdf_wlan_priority_queue.h" +#include "utils/hdf_log.h" +#include "message/message_types.h" +#include "../message_router_inner.h" +#include "sidecar.h" + +#ifdef USERSPACE_CLIENT_SUPPORT +#define HDF_LOG_TAG UMsgEngine +#else +#define HDF_LOG_TAG KMsgEngine +#endif + +typedef struct LocalMessageNode { + INHERT_MESSAGE_NODE; +} LocalMessageNode; + +typedef struct LocalNodeService { + INHERT_REMOTE_SERVICE; + MessageDispatcher *dispatcher; + struct ServiceDef *mapper; +} LocalNodeService; + +static void HandleRequestMessage(const RemoteService *service, MessageContext *context) +{ + if (context == NULL || service == NULL) { + HDF_LOGE("%s:input is NULL", __func__); + return; + } + LocalNodeService *localNodeService = (LocalNodeService *)service; + + struct MessageDef messageDef = { NULL, 0 }; + if (localNodeService->mapper != NULL && context->commandId < localNodeService->mapper->messagesLength) { + messageDef = localNodeService->mapper->messages[context->commandId]; + } + if (messageDef.handler == NULL) { + context->responseStatus = ME_ERROR_NO_SUCH_COMMAND; + } else { + context->responseStatus = messageDef.handler((RequestContext *)context, context->reqData, context->rspData); + } +} + +static void HandleResponseMessage(const RemoteService *service, MessageContext *context) +{ + (void)service; + if (context->requestType < MESSAGE_RSP_START) { + return; + } + + if (context->requestType == MESSAGE_TYPE_SYNC_RSP) { + HDF_STATUS status = OsalSemPost(&context->rspSemaphore); + if (status != HDF_SUCCESS) { + ReleaseMessageContext(context); + } + } else if (context->requestType == MESSAGE_TYPE_ASYNC_RSP) { + if (context->callback != NULL) { + context->callback((const RequestContext *)context, context->reqData, context->rspData, + context->responseStatus); + } + ReleaseMessageContext(context); + } else { + HDF_LOGE("%s:Response type not supported!type=%d", __func__, context->requestType); + } +} + +ErrorCode SendMessageLocalNode(const RemoteService *service, MessageContext *context) +{ + 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) { + HandleRequestMessage(service, context); + SetToResponse(context); + return context->responseStatus; + } else if (context->requestType == MESSAGE_TYPE_SYNC_RSP) { + (void)OsalSemPost(&context->rspSemaphore); + return ME_SUCCESS; + } else { + LocalNodeService *localService = (LocalNodeService *)service; + if (localService->dispatcher == NULL || localService->dispatcher->AppendMessage == NULL) { + HDF_LOGE("This service has no dispatcher!"); + return ME_ERROR_NOT_SUPPORTED; + } + if (context->requestType < MESSAGE_RSP_START) { + if (localService->mapper == NULL || localService->mapper->messages == NULL) { + HDF_LOGE("%s:Bad message mapper!", __func__); + return ME_ERROR_NULL_PTR; + } + + if (context->commandId >= localService->mapper->messagesLength || + localService->mapper->messages[context->commandId].handler == NULL) { + HDF_LOGE("%s:Request command not found!", __func__); + 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); + } + } +} + +static void ShutdownLocalService(RemoteService *service) +{ + service->status = ME_STATUS_TODESTROY; +} + +static void DestroyLocalNodeRemoteService(RemoteService *service) +{ + if (service == NULL) { + return; + } + LocalNodeService *localService = (LocalNodeService *)service; + if (localService->dispatcher != NULL && localService->dispatcher->Disref != NULL) { + localService->dispatcher->Disref(localService->dispatcher); + } + localService->mapper = NULL; + localService->dispatcher = NULL; + DEINIT_SHARED_OBJ(RemoteService, service); +} + +RemoteService *CreateLocalNodeService(MessageNode *node, MessageDispatcher *dispatcher, struct ServiceDef *mapper) +{ + if (mapper == NULL) { + return NULL; + } + if (dispatcher == NULL || dispatcher->Ref == NULL) { + HDF_LOGE("%s:Bad dispatcher found!", __func__); + return NULL; + } + (void)node; + + LocalNodeService *service = (LocalNodeService *)OsalMemCalloc(sizeof(LocalNodeService)); + if (service == NULL) { + return NULL; + } + + ErrorCode errCode; + do { + service->status = ME_STATUS_RUNNING; + service->ExecRequestMsg = HandleRequestMessage; + service->ExecResponseMsg = HandleResponseMessage; + service->SendMessage = SendMessageLocalNode; + service->Shutdown = ShutdownLocalService; + service->serviceId = mapper->serviceId; + service->mapper = mapper; + service->dispatcher = dispatcher->Ref(dispatcher); + if (service->dispatcher == NULL) { + errCode = ME_ERROR_NO_SUCH_DISPATCHER; + break; + } + + errCode = INIT_SHARED_OBJ(RemoteService, (RemoteService *)service, DestroyLocalNodeRemoteService); + if (errCode != ME_SUCCESS) { + break; + } + } while (false); + + if (errCode != ME_SUCCESS) { + DestroyLocalNodeRemoteService((RemoteService *)service); + OsalMemFree(service); + return NULL; + } + return (RemoteService *)service; +} + +static ErrorCode InitLocalNode(MessageNode *node) +{ + if (node == NULL) { + return ME_ERROR_NULL_PTR; + } + + HDF_STATUS status = OsalMutexTimedLock(&node->mutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + return ME_ERROR_OPER_MUTEX_FAILED; + } + + ErrorCode errCode = ME_SUCCESS; + do { + if (node->status != ME_STATUS_STOPPED) { + HDF_LOGE("%s:unexpected status %d", __func__, node->status); + errCode = ME_ERROR_MUTI_INIT_NOT_ALLOWED; + break; + } + + node->status = ME_STATUS_STARTTING; + } while (false); + + status = OsalMutexUnlock(&node->mutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:unlock mutex failed!", __func__); + } + + if (errCode != ME_SUCCESS) { + return errCode; + } + + status = OsalMutexTimedLock(&node->mutex, HDF_WAIT_FOREVER); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:lock mutex failed!", __func__); + } + if (errCode == ME_SUCCESS) { + node->status = ME_STATUS_RUNNING; + } else { + node->status = ME_STATUS_STOPPED; + } + + status = OsalMutexUnlock(&node->mutex); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:unlock mutex failed!", __func__); + } + return errCode; +} + +static void DestroyLocalNode(MessageNode *node) +{ + if (node == NULL) { + return; + } + int32_t ret = OsalMutexDestroy(&node->mutex); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Release mutex failed!ret=%d", __func__, ret); + } + DEINIT_SHARED_OBJ(MessageNode, node); +} + +ErrorCode CreateLocalNode(MessageNode **node) +{ + if (node == NULL) { + return ME_ERROR_NULL_PTR; + } + HDF_LOGI("Creating local node..."); + LocalMessageNode *newNode = (LocalMessageNode *)OsalMemCalloc(sizeof(LocalMessageNode)); + if (newNode == NULL) { + return ME_ERROR_RES_LAKE; + } + ErrorCode errCode; + do { + newNode->status = ME_STATUS_STOPPED; + newNode->Init = InitLocalNode; + newNode->CreateRemoteService = CreateLocalNodeService; + newNode->SyncService = NULL; + newNode->NotifyServiceAdd = NULL; + newNode->NotifyServiceDel = NULL; + + int32_t ret = OsalMutexInit(&newNode->mutex); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Init mutex failed!err=%d", __func__, ret); + errCode = ME_ERROR_OPER_MUTEX_FAILED; + break; + } + + errCode = INIT_SHARED_OBJ(MessageNode, (MessageNode *)newNode, DestroyLocalNode); + if (errCode != ME_SUCCESS) { + break; + } + } while (false); + + if (errCode != ME_SUCCESS) { + DestroyLocalNode((MessageNode *)newNode); + OsalMemFree(newNode); + } else { + *node = (MessageNode *)newNode; + } + return errCode; +} \ No newline at end of file diff --git a/model/network/wifi/platform/src/message/shared_obj.h b/model/network/wifi/platform/src/message/shared_obj.h new file mode 100644 index 00000000..9e9291d6 --- /dev/null +++ b/model/network/wifi/platform/src/message/shared_obj.h @@ -0,0 +1,78 @@ +/* + * 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 SHARED_OBJ_H +#define SHARED_OBJ_H + +#include "osal/osal_atomic.h" +#include "osal/osal_mem.h" + +#define SHARED_OBJ(OBJ_TYPE) enum MessageEngineStatus status; \ + OsalAtomic refCount; \ + struct OBJ_TYPE *(*Ref)(struct OBJ_TYPE * obj); \ + void (*Disref)(struct OBJ_TYPE * obj); \ + void (*Destroy)(struct OBJ_TYPE * obj) + +#define DECLEAR_SHARED_OBJ_FUNC(OBJ_TYPE) \ + struct OBJ_TYPE *Reference##OBJ_TYPE(struct OBJ_TYPE *obj); \ + void Disreference##OBJ_TYPE(struct OBJ_TYPE *obj); \ + ErrorCode InitSharedObj##OBJ_TYPE(struct OBJ_TYPE *obj, void (*Destroy)(struct OBJ_TYPE *)); \ + void DeinitSharedObj##OBJ_TYPE(struct OBJ_TYPE *obj) + +#define IMPLEMENT_SHARED_OBJ(OBJ_TYPE) \ + struct OBJ_TYPE *Reference##OBJ_TYPE(struct OBJ_TYPE *obj) \ + { \ + if (obj == NULL) { \ + return NULL; \ + } \ + if (obj->status > ME_STATUS_RUNNING) { \ + return NULL; \ + } \ + struct OBJ_TYPE *result = NULL; \ + if (obj->status <= ME_STATUS_RUNNING && OsalAtomicRead(&obj->refCount) < MAX_OBJ_REF_COUNT) { \ + OsalAtomicInc(&obj->refCount); \ + result = obj; \ + } \ + return result; \ + } \ + void Disreference##OBJ_TYPE(struct OBJ_TYPE *obj) \ + { \ + if (obj == NULL) { \ + return; \ + } \ + OsalAtomicDec(&obj->refCount); \ + if (OsalAtomicRead(&obj->refCount) <= 0) { \ + obj->status = ME_STATUS_TODESTROY; \ + if (obj->Destroy != NULL) { \ + obj->Destroy(obj); \ + OsalMemFree(obj); \ + } \ + } \ + } \ + ErrorCode InitSharedObj##OBJ_TYPE(struct OBJ_TYPE *obj, void (*Destroy)(struct OBJ_TYPE *)) \ + { \ + if (Destroy == NULL) { \ + return ME_ERROR_NULL_PTR; \ + } \ + OsalAtomicSet(&obj->refCount, 1); \ + obj->Ref = Reference##OBJ_TYPE; \ + obj->Disref = Disreference##OBJ_TYPE; \ + obj->Destroy = Destroy; \ + return ME_SUCCESS; \ + } \ + void DeinitSharedObj##OBJ_TYPE(struct OBJ_TYPE *obj) \ + { \ + if (obj != NULL) { \ + OsalAtomicSet(&obj->refCount, 0); \ + } \ + } + +#define INIT_SHARED_OBJ(OBJ_TYPE, obj, DestroyFunc) InitSharedObj##OBJ_TYPE(obj, DestroyFunc) +#define DEINIT_SHARED_OBJ(OBJ_TYPE, obj) DeinitSharedObj##OBJ_TYPE(obj) + + +#endif diff --git a/model/network/wifi/platform/src/message/sidecar.c b/model/network/wifi/platform/src/message/sidecar.c new file mode 100644 index 00000000..b49e9abd --- /dev/null +++ b/model/network/wifi/platform/src/message/sidecar.c @@ -0,0 +1,267 @@ +/* + * 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_base.h" +#include "securec.h" +#include "utils/hdf_log.h" +#include "sidecar.h" +#include "message_router.h" +#include "message_router_inner.h" + +#ifdef USERSPACE_CLIENT_SUPPORT +#define HDF_LOG_TAG UMsgEngine +#else +#define HDF_LOG_TAG KMsgEngine +#endif + +// Service has only one private data.The service ID of current service +typedef struct { + DispatcherId dispatcherId; + ServiceId serviceId; +} SideCarPrivateData; + +static ErrorCode MessageInputCheck(const Service *sideCar, ServiceId receiver, struct HdfSBuf *sendData) +{ + if (sideCar == NULL || sideCar->privateData == NULL) { + HDF_LOGE("%s:sideCar or sideCar.privateData is NULL", __func__); + return ME_ERROR_NULL_PTR; + } + + SideCarPrivateData *privateData = (SideCarPrivateData *)sideCar->privateData; + if (receiver >= MESSAGE_ENGINE_MAX_SERVICE || privateData->serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + return ME_ERROR_NO_SUCH_SERVICE; + } + return ME_SUCCESS; +} + +static MessageContext *CreateMessageContext(ServiceId sender, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *sendData) +{ + MessageContext *context = (MessageContext *)OsalMemCalloc(sizeof(MessageContext)); + if (context == NULL) { + return NULL; + } + + context->commandId = commandId; + context->senderId = sender; + context->receiverId = receiver; + context->reqData = sendData; + context->corssNode = false; + + return context; +} + +#define MESSAGE_CMD_BITS 16 +#define MESSAGE_CMD_MASK 0xffff + +inline static uint32_t GetServiceID(uint32_t id) +{ + return (id & ~((uint32_t)(MESSAGE_CMD_MASK))) >> MESSAGE_CMD_BITS; +} + +inline static uint32_t GetCmd(uint32_t id) +{ + return id & MESSAGE_CMD_MASK; +} + +int32_t DispatchToMessage(struct HdfDeviceIoClient *client, int id, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + ErrorCode errCode; + ServiceId serviceId = GetServiceID(id); + uint32_t cmd = GetCmd(id); + MessageContext *context = NULL; + + if (client == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (serviceId >= MESSAGE_ENGINE_MAX_SERVICE) { + return ME_ERROR_NO_SUCH_SERVICE; + } + context = CreateMessageContext(RESERVED_SERVICE_ID, serviceId, cmd, reqData); + if (context == NULL) { + return ME_ERROR_NULL_PTR; + } + context->rspData = rspData; + context->requestType = MESSAGE_TYPE_SYNC_REQ; + context->client = client; + RemoteService *targetService = NULL; + do { + targetService = RefRemoteService(serviceId); + if (targetService == NULL || targetService->SendMessage == NULL) { + HDF_LOGE("%s:Target service is NULL or has no SendMessage!", __func__); + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + + errCode = targetService->SendMessage(targetService, context); + } while (false); + if (targetService != NULL && targetService->Disref != NULL) { + targetService->Disref(targetService); + } + OsalMemFree(context); + return errCode; +} + +static ErrorCode SideCarSendSyncMessage(const Service *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *sendData, struct HdfSBuf *recvData) +{ + ErrorCode errCode = MessageInputCheck(sideCar, receiver, sendData); + if (errCode != ME_SUCCESS) { + return errCode; + } + SideCarPrivateData *privateData = (SideCarPrivateData *)sideCar->privateData; + MessageContext *context = CreateMessageContext(privateData->serviceId, receiver, commandId, sendData); + if (context == NULL) { + return ME_ERROR_NULL_PTR; + } + context->rspData = recvData; + context->requestType = MESSAGE_TYPE_SYNC_REQ; + RemoteService *targetService = NULL; + do { + targetService = RefRemoteService(receiver); + if (targetService == NULL || targetService->SendMessage == NULL) { + HDF_LOGE("Target service is NULL or has no SendMessage!"); + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + + errCode = targetService->SendMessage(targetService, context); + } while (false); + if (targetService != NULL && targetService->Disref != NULL) { + targetService->Disref(targetService); + } + OsalMemFree(context); + return errCode; +} + +static ErrorCode SideCarSendAsyncMessageInner(const Service *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *reqData, MessageCallBack callback) +{ + ErrorCode errCode = MessageInputCheck(sideCar, receiver, reqData); + if (errCode != ME_SUCCESS) { + return errCode; + } + + SideCarPrivateData *privateData = (SideCarPrivateData *)sideCar->privateData; + MessageContext *context = CreateMessageContext(privateData->serviceId, receiver, commandId, reqData); + if (context == NULL) { + return ME_ERROR_NULL_PTR; + } + struct HdfSBuf *rspData = HdfSBufObtainDefaultSize(); + if (rspData == NULL) { + OsalMemFree(context); + return HDF_FAILURE; + } + context->requestType = MESSAGE_TYPE_ASYNC_REQ; + context->callback = callback; + context->rspData = rspData; + + RemoteService *targetService = NULL; + do { + targetService = RefRemoteService(receiver); + if (targetService == NULL || targetService->SendMessage == NULL) { + HDF_LOGE("Target service is NULL or has no SendMessage!"); + errCode = ME_ERROR_NO_SUCH_SERVICE; + break; + } + + errCode = targetService->SendMessage(targetService, context); + } while (false); + if (targetService != NULL && targetService->Disref != NULL) { + targetService->Disref(targetService); + } + if (errCode != ME_SUCCESS) { + HdfSBufRecycle(rspData); + OsalMemFree(context); + } + return errCode; +} + +static ErrorCode SideCarSendAsyncMessage(const Service *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *reqData, MessageCallBack callback) +{ + if (callback == NULL) { + HDF_LOGE("%s:Callback function can not be NULL.Did you mean SendOnewayMessage?", __func__); + return ME_ERROR_PARA_WRONG; + } + return SideCarSendAsyncMessageInner(sideCar, receiver, commandId, reqData, callback); +} + +static ErrorCode SideCarSendOneWayMessage(const struct SideCar_ *sideCar, ServiceId receiver, uint32_t commandId, + struct HdfSBuf *reqData) +{ + return SideCarSendAsyncMessageInner(sideCar, receiver, commandId, reqData, NULL); +} + +static ErrorCode DestroyService(Service *service) +{ + if (service == NULL) { + return ME_ERROR_NULL_PTR; + } + + if (service->privateData == NULL) { + HDF_LOGE("%s:privateData is NULL!", __func__); + return ME_ERROR_PARA_WRONG; + } + SideCarPrivateData *data = (SideCarPrivateData *)service->privateData; + HDF_LOGE("Destroy service! id=%d", data->serviceId); + + ErrorCode errCode = UnregistLocalService(data->dispatcherId, data->serviceId); + if (errCode != ME_SUCCESS) { + HDF_LOGE("Unregist service failed!ret=%d", errCode); + return errCode; + } + + OsalMemFree(data); + service->privateData = NULL; + OsalMemFree(service); + return ME_SUCCESS; +} + +Service *InitService(struct ServiceDef *def, const ServiceCfg *cfg) +{ + if (cfg == NULL || def == NULL) { + return NULL; + } + + if (def->serviceId == RESERVED_SERVICE_ID) { + HDF_LOGE("%s:Init service with ID 0 is not allowed!", __func__); + return NULL; + } + + Service *service = (Service *)OsalMemCalloc(sizeof(Service)); + if (service == NULL) { + HDF_LOGE("%s:OsalMemAlloc return NULL!", __func__); + return NULL; + } + service->SendAsyncMessage = SideCarSendAsyncMessage; + service->SendSyncMessage = SideCarSendSyncMessage; + service->SendOneWayMessage = SideCarSendOneWayMessage; + service->Destroy = DestroyService; + + SideCarPrivateData *privateData = (SideCarPrivateData *)OsalMemCalloc(sizeof(SideCarPrivateData)); + if (privateData == NULL) { + OsalMemFree(service); + HDF_LOGE("%s:OsalMemAlloc return NULL!", __func__); + return NULL; + } + privateData->serviceId = def->serviceId; + privateData->dispatcherId = cfg->dispatcherId; + service->privateData = (void *)privateData; + privateData = NULL; + + ErrorCode errCode = RegistLocalService(cfg->dispatcherId, def); + if (errCode != ME_SUCCESS) { + OsalMemFree(service->privateData); + service->privateData = NULL; + OsalMemFree(service); + service = NULL; + HDF_LOGE("Regist 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 new file mode 100644 index 00000000..923598eb --- /dev/null +++ b/model/network/wifi/platform/src/qos/flow_control.c @@ -0,0 +1,398 @@ +/* + * 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 "flow_control.h" + +#include "flow_control_task.h" +#include "securec.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "net_device.h" +#include "net_device_adapter.h" + +#define HDF_LOG_TAG "WiFiFlowControl" +#define ETHER_TYPE_PROCESS_COUNT 8 +#define TOS_TO_ID_COUNT 6 +#define PROTOCOL_STANDARD_SHIFT_COUNT 2 +static FlowControlQueueID g_tosToIdHash[TOS_TO_ID_COUNT] = { + BE_QUEUE_ID, BK_QUEUE_ID, BK_QUEUE_ID, BE_QUEUE_ID, VI_QUEUE_ID, VI_QUEUE_ID +}; + +static FlowControlQueueID IpProcessFunc(const void *buff, uint32_t len); +static struct EtherProcessMap g_etherTypeProMap[ETHER_TYPE_PROCESS_COUNT] = { + {ETHER_TYPE_IP, IpProcessFunc}, + {ETHER_TYPE_IPV6, NULL}, + {ETHER_TYPE_PAE, NULL}, + {ETHER_TYPE_TDLS, NULL}, + {ETHER_TYPE_PPP_DISC, NULL}, + {ETHER_TYPE_PPP_SES, NULL}, + {ETHER_TYPE_WAI, NULL}, + {ETHER_TYPE_VLAN, NULL}, +}; + +static FlowControlQueueID TosToFcQueueId(uint8_t priority) +{ + if (priority >= TOS_TO_ID_COUNT) { + return VO_QUEUE_ID; + } + return g_tosToIdHash[priority]; +} + +static bool IsDhcpPort(struct UdpHeader *udpHdr, uint32_t len) +{ + if (udpHdr == NULL) { + HDF_LOGE("%s udpHdr: = null!", __func__); + return false; + } + if (len < sizeof(struct UdpHeader)) { + HDF_LOGE("%s len not right!", __func__); + return false; + } + if ((ntohs(udpHdr->dest) == DHCP_UDP_SRC_PORT) || (ntohs(udpHdr->dest) == DHCP_UDP_DES_PORT)) { + return true; + } + return false; +} + +/* TcpKeyFrame:ACK/SYN */ +static bool IsTcpKeyFrame(struct IpHeader *ipHeader, uint32_t len) +{ + struct TcpHeader *tcpHdr = NULL; + uint32_t ipPktLen; + uint32_t tcpHdrLen; + uint8_t ipHdrLen; + uint8_t *ip = NULL; + if (ipHeader == NULL) { + HDF_LOGE("IsTcpAck Fail ipHeader = null"); + return false; + } + if (len < sizeof(struct IpHeader)) { + HDF_LOGE("%s len not right!", __func__); + return false; + } + if ((len - sizeof(struct IpHeader)) < sizeof(struct TcpHeader)) { + HDF_LOGE("%s tcp hdr len not right!", __func__); + return false; + } + + tcpHdr = (struct TcpHeader *)(ipHeader + 1); + ip = (uint8_t *)(ipHeader); + ipPktLen = ntohs(ipHeader->totLen); + ipHdrLen = ((*ip) & 0x0F) << PROTOCOL_STANDARD_SHIFT_COUNT; + tcpHdrLen = (tcpHdr->offset & 0xF0) << PROTOCOL_STANDARD_SHIFT_COUNT; + if (tcpHdrLen + ipHdrLen == ipPktLen) { + return true; + } + return false; +} + +static FlowControlQueueID IpProcessFunc(const void *buff, uint32_t len) +{ + struct IpHeader *ipHeader = NULL; + struct UdpHeader *udpHdr = NULL; + FlowControlQueueID id = NORMAL_QUEUE_ID; + if (buff == NULL) { + HDF_LOGE("%s fail: buff = null!", __func__); + return QUEUE_ID_COUNT; + } + if (len < sizeof(struct IpHeader)) { + HDF_LOGE("%s fail: len not right!", __func__); + return QUEUE_ID_COUNT; + } + ipHeader = (struct IpHeader *)buff; + if (ipHeader->protocol == UDP_PROTOCOL) { + /* from IP TOS find priority */ + /* + * ---------------------------------------------------------------------- + * tos define + * ---------------------------------------------------------------------- + * | bit7~bit5 | bit4 | bit3 | bit2 | bit1 | bit0 | + * | priority | Delay | Throughput | reliability | Transmission cost | reserve | + * ---------------------------------------------------------------------- + */ + id = TosToFcQueueId(ipHeader->tos >> IP_PRI_SHIFT); + udpHdr = (struct UdpHeader *)(ipHeader + 1); + if (((ntohs(ipHeader->fragInfo) & 0x1FFF) == 0) && IsDhcpPort(udpHdr, len - sizeof(struct IpHeader))) { + id = VIP_QUEUE_ID; + } + } else if (ipHeader->protocol == TCP_PROTOCOL) { + if (IsTcpKeyFrame(ipHeader, len)) { + id = TCP_ACK_QUEUE_ID; + } else { + id = TCP_DATA_QUEUE_ID; + } + } + return id; +} + +static void FlowControlQueueInit(struct FlowControlModule *fcm) +{ + int32_t i, j; + if (fcm == NULL) { + HDF_LOGE("%s fail: fcm = null!", __func__); + return; + } + for (i = 0; i < FLOW_DIR_COUNT; i++) { + for (j = 0; j < QUEUE_ID_COUNT; j++) { + NetBufQueueInit(&fcm->fcmQueue[i].queues[j].dataQueue); + OsalSpinInit(&fcm->fcmQueue[i].queues[j].lock); + } + } +} + +static void FlowControlQueueDeinit(struct FlowControlModule *fcm) +{ + int32_t i, j; + if (fcm == NULL) { + HDF_LOGE("%s fcm already free!", __func__); + return; + } + + for (i = 0; i < FLOW_DIR_COUNT; i++) { + for (j = 0; j < QUEUE_ID_COUNT; j++) { + NetBufQueueClear(&fcm->fcmQueue[i].queues[j].dataQueue); + OsalSpinDestroy(&fcm->fcmQueue[i].queues[j].lock); + } + } + return; +} + +static int32_t SchedTransfer(struct FlowControlModule *fcm, FlowDir dir) +{ + if (fcm == NULL || dir >= FLOW_DIR_COUNT) { + HDF_LOGE("%s : fcm = null dir=%d!", __func__, dir); + return HDF_ERR_INVALID_PARAM; + } + OsalSemPost(&fcm->sem[dir]); + return HDF_SUCCESS; +} + +static int32_t RegisterFlowControlOp(struct FlowControlModule *fcm, struct FlowControlOp *op) +{ + if ((fcm == NULL) || (op == NULL)) { + HDF_LOGE("%s fail : fcm = null or op = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + fcm->op = op; + return HDF_SUCCESS; +} + +static bool IsValidSentToFCMPra(const struct FlowControlModule *fcm, uint32_t id, uint32_t dir) +{ + if (fcm == NULL) { + HDF_LOGE("%s fail : fcm = null or buff = null!", __func__); + return false; + } + if (id >= QUEUE_ID_COUNT || dir >= FLOW_DIR_COUNT) { + HDF_LOGE("%s fail : id or dir not right!", __func__); + return false; + } + return true; +} + +static int32_t SetQueueThreshold(struct FlowControlModule *fcm, uint32_t queueThreshold, uint32_t id, uint32_t dir) +{ + struct FlowControlQueue *fcmQueue = NULL; + if (!IsValidSentToFCMPra(fcm, id, dir)) { + HDF_LOGE("%s fail IsValidSentToFCMPra FALSE!", __func__); + return HDF_ERR_INVALID_PARAM; + } + fcmQueue = &fcm->fcmQueue[dir].queues[id]; + fcmQueue->queueThreshold = queueThreshold; + return HDF_SUCCESS; +} + +static void FcmQueuePreProcess(struct FlowControlQueue *fcmQueue) +{ + NetBufQueue *dataQ = &fcmQueue->dataQueue; + NetBuf *oldBuff = NULL; + uint32_t threshold = fcmQueue->queueThreshold; + uint32_t qLen = NetBufQueueSize(dataQ); + if (threshold > 0 && threshold < qLen) { + HDF_LOGE("%s abandon netbuff!", __func__); + oldBuff = NetBufQueueDequeue(dataQ); + if (oldBuff != NULL) { + NetBufFree(oldBuff); + } + } + return; +} + +static int32_t SendBuffToFCM(struct FlowControlModule *fcm, NetBuf *buff, uint32_t id, uint32_t dir) +{ + struct FlowControlQueue *fcmQueue = NULL; + NetBufQueue *dataQ = NULL; + if ((buff == NULL) || (NetBufGetDataLen(buff) == 0)) { + HDF_LOGE("%s fail : buff=null or len=0!", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!IsValidSentToFCMPra(fcm, id, dir)) { + HDF_LOGE("%s fail : IsValidSentToFCMPra FALSE!", __func__); + return HDF_ERR_INVALID_PARAM; + } + + fcmQueue = &fcm->fcmQueue[dir].queues[id]; + dataQ = &fcmQueue->dataQueue; + FcmQueuePreProcess(fcmQueue); + if (NetBufQueueIsEmpty(dataQ)) { + fcm->fcmQueue[dir].queues[id].pktCount = 0; + } + NetBufQueueEnqueue(dataQ, buff); + fcm->fcmQueue[dir].queues[id].pktCount++; + return HDF_SUCCESS; +} + +static FlowControlQueueID GetQueueIdByEtherBuff(const NetBuf *buff) +{ + uint32_t len; + struct EtherHeader *header = NULL; + int i; + uint16_t etherType = 0; + if (buff == NULL) { + HDF_LOGE("%s fail : buff = null!", __func__); + return QUEUE_ID_COUNT; + } + len = NetBufGetDataLen(buff); + if (len < sizeof(struct EtherHeader)) { + HDF_LOGE("%s fail : buff->data_len not right!", __func__); + return QUEUE_ID_COUNT; + } + header = (struct EtherHeader *)NetBufGetAddress(buff, E_DATA_BUF); + etherType = ntohs(header->etherType); + + /* if processFun = null return VIP_QUEUE_ID */ + for (i = 0; i < ETHER_TYPE_PROCESS_COUNT; i++) { + if (g_etherTypeProMap[i].etherType == etherType) { + if (g_etherTypeProMap[i].processFun != NULL) { + return g_etherTypeProMap[i].processFun((void *)(header + 1), len - sizeof(struct EtherHeader)); + } + return VIP_QUEUE_ID; + } + } + return NORMAL_QUEUE_ID; +} + +static struct FlowControlInterface g_fcInterface = { + .setQueueThreshold = SetQueueThreshold, + .getQueueIdByEtherBuff = GetQueueIdByEtherBuff, + .sendBuffToFCM = SendBuffToFCM, + .schedFCM = SchedTransfer, + .registerFlowControlOp = RegisterFlowControlOp, +}; + +static struct FlowControlModule *g_fcm = NULL; + +int32_t SendFlowControlQueue(struct FlowControlModule *fcm, uint32_t id, uint32_t dir) +{ + NetBufQueue *q = NULL; + int32_t fwPriorityId = 0; + int32_t rxPriorityId = 0; + if (!IsValidSentToFCMPra(fcm, id, dir)) { + HDF_LOGE("%s fail : IsValidSentToFCMPra FALSE!", __func__); + return HDF_ERR_INVALID_PARAM; + } + q = &fcm->fcmQueue[dir].queues[id].dataQueue; + if (NetBufQueueIsEmpty(q)) { + return HDF_SUCCESS; + } + if (dir == FLOW_TX) { + if (fcm->op != NULL && fcm->op->getTxPriorityId != NULL) { + fwPriorityId = fcm->op->getTxPriorityId(id); + } + if (fcm->op != NULL && fcm->op->txDataPacket != NULL) { + fcm->op->txDataPacket(q, fcm->fcmPriv, fwPriorityId); + } else { + HDF_LOGE("%s fail : fcm->op->txDataPacket = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + } + + if (dir == FLOW_RX) { + if (fcm->op != NULL && fcm->op->getRxPriorityId != NULL) { + rxPriorityId = fcm->op->getRxPriorityId(id); + } + if (fcm->op != NULL && fcm->op->rxDataPacket != NULL) { + fcm->op->rxDataPacket(q, fcm->fcmPriv, rxPriorityId); + } else { + HDF_LOGE("%s fail : fcm->op->txDataPacket = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + } + return HDF_SUCCESS; +} + +struct FlowControlModule *InitFlowControl(void *fcmPriv) +{ + struct FlowControlModule *fcm = NULL; + int i; + if (g_fcm != NULL) { + HDF_LOGE("%s already init", __func__); + return g_fcm; + } + fcm = (struct FlowControlModule *)OsalMemCalloc(sizeof(struct FlowControlModule)); + if (fcm == NULL) { + HDF_LOGE("%s fail: malloc fail!", __func__); + return NULL; + } + (void)memset_s(fcm, sizeof(struct FlowControlModule), 0, sizeof(struct FlowControlModule)); + + /* init queue */ + FlowControlQueueInit(fcm); + + /* init wait */ + for (i = 0; i < FLOW_DIR_COUNT; i++) { + if (OsalSemInit(&fcm->sem[i], 0) != HDF_SUCCESS) { + HDF_LOGE("%s init osalsem fail!", __func__); + if (i == FLOW_RX) { + OsalSemDestroy(&fcm->sem[FLOW_TX]); + } + OsalMemFree(fcm); + return NULL; + } + } + + /* init task */ + if (CreateFlowControlTask(fcm) != HDF_SUCCESS) { + HDF_LOGE("%s fail: CreateFlowControlTask fail!", __func__); + for (i = 0; i < FLOW_DIR_COUNT; i++) { + (void)OsalSemDestroy(&fcm->sem[i]); + } + OsalMemFree(fcm); + return NULL; + } + + /* register interface */ + fcm->interface = &g_fcInterface; + fcm->fcmPriv = fcmPriv; + g_fcm = fcm; + return fcm; +} + +void DeInitFlowControl(struct FlowControlModule *fcm) +{ + int i; + if (fcm == NULL) { + HDF_LOGE("%s fail : fcm already been free.", __func__); + return; + } + + /* 1:Detroy task. 2:Destroy osalwait. 3:free NetBuff. */ + DestroyFlowControlTask(fcm); + for (i = 0; i < FLOW_DIR_COUNT; i++) { + OsalSemDestroy(&fcm->sem[i]); + } + FlowControlQueueDeinit(fcm); + OsalMemFree(fcm); + g_fcm = NULL; + return; +} + +struct FlowControlModule *GetFlowControlModule() +{ + return g_fcm; +} diff --git a/model/network/wifi/platform/src/qos/flow_control_task.c b/model/network/wifi/platform/src/qos/flow_control_task.c new file mode 100644 index 00000000..b51209bd --- /dev/null +++ b/model/network/wifi/platform/src/qos/flow_control_task.c @@ -0,0 +1,209 @@ +/* + * 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 "flow_control_task.h" +#include "osal_time.h" +#include "hdf_log.h" +#include "flow_control.h" +#define HDF_LOG_TAG "WiFiFlowControl" +#define FLOW_CONTROL_MAP_SIZE 3 +struct FcPriority { + FlowDir dir; + FlowControlQueueID id; +}; + +static FlowControlQueueID g_staPriorityMapTx[QUEUE_ID_COUNT] = { + CTRL_QUEUE_ID, VIP_QUEUE_ID, NORMAL_QUEUE_ID, TCP_ACK_QUEUE_ID, TCP_DATA_QUEUE_ID, VO_QUEUE_ID, VI_QUEUE_ID, + BE_QUEUE_ID, BK_QUEUE_ID +}; + +static FlowControlQueueID g_staPriorityMapRx[QUEUE_ID_COUNT] = { + CTRL_QUEUE_ID, VIP_QUEUE_ID, NORMAL_QUEUE_ID, TCP_DATA_QUEUE_ID, TCP_ACK_QUEUE_ID, VO_QUEUE_ID, VI_QUEUE_ID, + BE_QUEUE_ID, BK_QUEUE_ID +}; + +static FlowControlQueueID g_priorityMapTx[QUEUE_ID_COUNT] = { + CTRL_QUEUE_ID, VIP_QUEUE_ID, NORMAL_QUEUE_ID, TCP_DATA_QUEUE_ID, TCP_ACK_QUEUE_ID, VO_QUEUE_ID, VI_QUEUE_ID, + BE_QUEUE_ID, BK_QUEUE_ID +}; + +static FlowControlQueueID g_priorityMapRx[QUEUE_ID_COUNT] = { + CTRL_QUEUE_ID, VIP_QUEUE_ID, NORMAL_QUEUE_ID, TCP_ACK_QUEUE_ID, TCP_DATA_QUEUE_ID, VO_QUEUE_ID, VI_QUEUE_ID, + BE_QUEUE_ID, BK_QUEUE_ID +}; + +static bool IsFcThreadNeedStop(struct FlowControlModule *fcm, FlowDir dir) +{ + if (fcm->threadStatus[dir] > THREAD_RUNNING) { + return true; + } + return false; +} + +static void FlowControlTxTreadProcess(struct FlowControlModule *fcm) +{ + bool isSta = false; + int i; + if (fcm->op != NULL && fcm->op->isDeviceStaOrP2PClient != NULL) { + isSta = fcm->op->isDeviceStaOrP2PClient(); + } + if (isSta) { + for (i = 0; i < FLOW_CONTROL_MAP_SIZE; i++) { + SendFlowControlQueue(fcm, g_staPriorityMapTx[i], FLOW_TX); + } + } else { + for (i = 0; i < FLOW_CONTROL_MAP_SIZE; i++) { + SendFlowControlQueue(fcm, g_priorityMapTx[i], FLOW_TX); + } + } +} + +static void FlowControlRxTreadProcess(struct FlowControlModule *fcm) +{ + bool isSta = false; + int i; + if (fcm->op != NULL && fcm->op->isDeviceStaOrP2PClient != NULL) { + isSta = fcm->op->isDeviceStaOrP2PClient(); + } + if (isSta) { + for (i = 0; i < QUEUE_ID_COUNT; i++) { + SendFlowControlQueue(fcm, g_staPriorityMapRx[i], FLOW_RX); + } + } else { + for (i = 0; i < QUEUE_ID_COUNT; i++) { + SendFlowControlQueue(fcm, g_priorityMapRx[i], FLOW_RX); + } + } +} + +static int32_t RunWiFiFlowControl(void *para, FlowDir dir) +{ + struct FlowControlModule *fcm = (struct FlowControlModule *)para; + if (para == NULL || dir >= FLOW_DIR_COUNT) { + HDF_LOGE("%s fail: para = null or dir=%d!", __func__, dir); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%s Enter flow control dir =%d!", __func__, dir); + fcm->threadStatus[dir] = THREAD_STARTING; + while (true) { + fcm->threadStatus[dir] = THREAD_WAITING; + if (OsalSemWait(&fcm->sem[dir], HDF_WAIT_FOREVER) != HDF_SUCCESS) { + HDF_LOGE("%s exit: OsalSemWait return false!", __func__); + continue; + } + if (IsFcThreadNeedStop(fcm, dir)) { + HDF_LOGE("%s exit: because threadStatus[%d] > THREAD_RUNNING!", __func__, dir); + break; + } + fcm->threadStatus[dir] = THREAD_RUNNING; + if (dir == FLOW_TX) { + FlowControlTxTreadProcess(fcm); + } else if (dir == FLOW_RX) { + FlowControlRxTreadProcess(fcm); + } + } + HDF_LOGE("%s Exit!", __func__); + fcm->threadStatus[dir] = THREAD_STOPPED; + return HDF_SUCCESS; +} + +static int32_t RunWiFiTxFlowControl(void *para) +{ + return RunWiFiFlowControl(para, FLOW_TX); +} + +static int32_t RunWiFiRxFlowControl(void *para) +{ + return RunWiFiFlowControl(para, FLOW_RX); +} + +static int32_t CreateTask(struct OsalThread *thread, char *taskName, OsalThreadEntry threadEntry, + struct OsalThreadParam *para, void *entryPara) +{ + int32_t status = OsalThreadCreate(thread, threadEntry, entryPara); + para->name = taskName; + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadCreate failed!status=%d", __func__, status); + return HDF_FAILURE; + } + status = OsalThreadStart(thread, para); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadStart failed!status=%d", __func__, status); + OsalThreadDestroy(thread); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static void DestroyTask(struct FlowControlModule *fcm, FlowDir dir) +{ + int count = 0; + if (fcm == NULL || dir >= FLOW_DIR_COUNT) { + HDF_LOGE("%s fail: fcm = null or dir not right!", __func__); + return; + } + if (fcm->threadStatus[dir] == THREAD_INIT_FAIL || fcm->threadStatus[dir] == THREAD_DESTROYED) { + HDF_LOGE("%s,delete thread not need!", __func__); + return; + } + fcm->threadStatus[dir] = THREAD_STOPPING; + OsalSemPost(&fcm->sem[dir]); + + /* wait until RunWiFiFlowControl exit */ + while ((fcm->threadStatus[dir] != THREAD_STOPPED) && (count < MAX_EXIT_THREAD_COUNT)) { + OsalMSleep(1); + count++; + } + if (dir == FLOW_TX) { + OsalThreadDestroy(&fcm->txTransferThread); + } else if (dir == FLOW_RX) { + OsalThreadDestroy(&fcm->rxTransferThread); + } + fcm->threadStatus[dir] = THREAD_DESTROYED; + HDF_LOGE("%s delete thread[%d] success!", __func__, dir); + return; +} + +int32_t CreateFlowControlTask(struct FlowControlModule *fcm) +{ + struct OsalThreadParam config = { + .priority = OSAL_THREAD_PRI_HIGHEST, + .stackSize = 0, + }; + + if (fcm == NULL) { + HDF_LOGE("%s fail: fcm = null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + + int32_t ret = CreateTask(&fcm->txTransferThread, RX_THREAD_NAME, RunWiFiTxFlowControl, &config, fcm); + if (ret == HDF_FAILURE) { + fcm->threadStatus[FLOW_TX] = THREAD_INIT_FAIL; + return HDF_FAILURE; + } + ret = CreateTask(&fcm->rxTransferThread, TX_THREAD_NAME, RunWiFiRxFlowControl, &config, fcm); + if (ret == HDF_FAILURE) { + fcm->threadStatus[FLOW_TX] = THREAD_INIT_FAIL; + fcm->threadStatus[FLOW_RX] = THREAD_INIT_FAIL; + DestroyTask(fcm, FLOW_TX); + } + fcm->threadStatus[FLOW_TX] = THREAD_INIT_SUCCESS; + fcm->threadStatus[FLOW_RX] = THREAD_INIT_SUCCESS; + return HDF_SUCCESS; +} + +void DestroyFlowControlTask(struct FlowControlModule *fcm) +{ + if (fcm == NULL) { + HDF_LOGE("%s fcm = null", __func__); + return; + } + DestroyTask(fcm, FLOW_TX); + DestroyTask(fcm, FLOW_RX); + return; +} \ No newline at end of file diff --git a/model/network/wifi/platform/src/qos/flow_control_task.h b/model/network/wifi/platform/src/qos/flow_control_task.h new file mode 100644 index 00000000..d4c26986 --- /dev/null +++ b/model/network/wifi/platform/src/qos/flow_control_task.h @@ -0,0 +1,19 @@ +/* + * 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 WIFI_FLOW_CONTROL_TASK_H +#define WIFI_FLOW_CONTROL_TASK_H +#include "flow_control.h" + +#define MAX_EXIT_THREAD_COUNT 10 /* 10MS */ +int32_t CreateFlowControlTask(struct FlowControlModule *fcm); +void DestroyFlowControlTask(struct FlowControlModule *fcm); + +#define TX_THREAD_NAME "hdf_wifi_tx" +#define RX_THREAD_NAME "hdf_wifi_rx" +#endif /* WIFI_FLOW_CONTROL_TASK_H */ \ No newline at end of file diff --git a/model/sensor/driver/accel/sensor_accel_driver.c b/model/sensor/driver/accel/sensor_accel_driver.c new file mode 100644 index 00000000..05bd9d4e --- /dev/null +++ b/model/sensor/driver/accel/sensor_accel_driver.c @@ -0,0 +1,371 @@ +/* + * 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 "securec.h" +#include "accel_bmi160.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_math.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "sensor_accel_driver.h" +#include "sensor_common.h" +#include "sensor_device_common.h" +#include "sensor_device_manager.h" + +#define HDF_LOG_TAG sensor_accel_driver_c + +static struct AccelDetectIfList g_accelDetectIfList[] = { + {ACCEL_CHIP_NAME_BMI160, DetectAccelBim160Chip}, +}; + +static struct AccelDrvData *AccelGetDrvData(void) +{ + static struct AccelDrvData accelDrvData = { + .threadStatus = SENSOR_THREAD_NONE, + .initStatus = false, + .detectFlag = false, + .interval = ACC_DEFAULT_SAMPLING_200_MS, + }; + + return &accelDrvData; +} + +static struct SensorRegCfgGroupNode *g_regCfgGroup[SENSOR_GROUP_MAX] = { NULL }; + +int32_t RegisterAccelChipOps(struct AccelOpsCall *ops) +{ + struct AccelDrvData *drvData = NULL; + + CHECK_NULL_PTR_RETURN_VALUE(ops, HDF_ERR_INVALID_PARAM); + + drvData = AccelGetDrvData(); + drvData->ops.Init = ops->Init; + drvData->ops.ReadData = ops->ReadData; + return HDF_SUCCESS; +} + +static int32_t ReadAccelDataThreadWorker(void *arg) +{ + (void)arg; + int64_t interval; + struct AccelDrvData *drvData = NULL; + + drvData = AccelGetDrvData(); + drvData->threadStatus = SENSOR_THREAD_START; + while (true) { + if (drvData->threadStatus == SENSOR_THREAD_RUNNING) { + if (drvData->ops.ReadData != NULL) { + (void)drvData->ops.ReadData(drvData->accelCfg); + } + + interval = OsalDivS64(drvData->interval, (SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT)); + OsalMSleep(interval); + } else if (drvData->threadStatus == SENSOR_THREAD_STOPPING) { + drvData->threadStatus = SENSOR_THREAD_STOPPED; + break; + } else { + OsalMSleep(ACC_DEFAULT_SAMPLING_200_MS / SENSOR_CONVERT_UNIT / SENSOR_CONVERT_UNIT); + } + + if ((!drvData->initStatus) || (drvData->interval < 0) || drvData->threadStatus != SENSOR_THREAD_RUNNING) { + continue; + } + } + + HDF_LOGD("%s: accel thread have exited", __func__); + return HDF_SUCCESS; +} + +static int32_t InitAccelConfig(void) +{ + struct AccelDrvData *drvData = AccelGetDrvData(); + int32_t ret; + + if (drvData->initStatus) { + return HDF_SUCCESS; + } + + if (drvData->threadStatus != SENSOR_THREAD_NONE && drvData->threadStatus != SENSOR_THREAD_DESTROY) { + HDF_LOGE("%s: accel thread have created", __func__); + return HDF_SUCCESS; + } + + ret = CreateSensorThread(&drvData->thread, ReadAccelDataThreadWorker, "hdf_sensor_accel", drvData); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: accel create thread failed", __func__); + drvData->threadStatus = SENSOR_THREAD_STOPPING; + return HDF_FAILURE; + } + + CHECK_NULL_PTR_RETURN_VALUE(drvData->ops.Init, HDF_ERR_INVALID_PARAM); + + ret = drvData->ops.Init(drvData->accelCfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: accel create thread failed", __func__); + drvData->threadStatus = SENSOR_THREAD_STOPPING; + return HDF_FAILURE; + } + drvData->initStatus = true; + + return HDF_SUCCESS; +} + +static int32_t SetAccelInfo(struct SensorBasicInfo *info) +{ + (void)info; + + return HDF_SUCCESS; +} + +static int32_t SetAccelEnable(void) +{ + int32_t ret; + struct AccelDrvData *drvData = AccelGetDrvData(); + + 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__); + return HDF_FAILURE; + } + + drvData->threadStatus = SENSOR_THREAD_RUNNING; + + return HDF_SUCCESS; +} + +static int32_t SetAccelDisable(void) +{ + int32_t ret; + struct AccelDrvData *drvData = AccelGetDrvData(); + + CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); + + ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: accel sensor disable config failed", __func__); + return HDF_FAILURE; + } + + drvData->threadStatus = SENSOR_THREAD_STOPPED; + + return HDF_SUCCESS; +} + +static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval) +{ + (void)interval; + + struct AccelDrvData *drvData = NULL; + + drvData = AccelGetDrvData(); + drvData->interval = samplingInterval; + + return HDF_SUCCESS; +} + +static int32_t SetAccelMode(int32_t mode) +{ + return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE; +} + +static int32_t SetAccelOption(uint32_t option) +{ + (void)option; + return HDF_SUCCESS; +} + +static int32_t DispatchAccel(struct HdfDeviceIoClient *client, + int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)client; + (void)cmd; + (void)data; + (void)reply; + + return HDF_SUCCESS; +} + +int32_t BindAccelDriver(struct HdfDeviceObject *device) +{ + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + static struct IDeviceIoService service = { + .object = {0}, + .Dispatch = DispatchAccel, + }; + device->service = &service; + + return HDF_SUCCESS; +} + +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; + deviceInfo->ops.SetBatch = SetAccelBatch; + deviceInfo->ops.SetMode = SetAccelMode; + deviceInfo->ops.SetOption = SetAccelOption; + + if (memcpy_s(&deviceInfo->sensorInfo, sizeof(deviceInfo->sensorInfo), + &drvData->accelCfg->sensorInfo, sizeof(drvData->accelCfg->sensorInfo)) != EOK) { + HDF_LOGE("%s: copy sensor info failed", __func__); + return HDF_FAILURE; + } + + drvData->accelCfg->sensorInfo.sensorTypeId = SENSOR_TAG_ACCELEROMETER; + drvData->accelCfg->sensorInfo.sensorId = SENSOR_TAG_ACCELEROMETER; + + return HDF_SUCCESS; +} + +static int32_t InitAccelAfterConfig(void) +{ + struct SensorDeviceInfo deviceInfo; + + if (InitAccelConfig() != HDF_SUCCESS) { + HDF_LOGE("%s: init accel config failed", __func__); + return HDF_FAILURE; + } + + if (InitAccelOps(&deviceInfo) != HDF_SUCCESS) { + HDF_LOGE("%s: init accel ops failed", __func__); + return HDF_FAILURE; + } + + if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) { + HDF_LOGE("%s: add accel device failed", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t DetectAccelChip(void) +{ + int32_t num; + int32_t ret; + int32_t loop; + struct AccelDrvData *drvData = AccelGetDrvData(); + CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); + + num = sizeof(g_accelDetectIfList) / sizeof(g_accelDetectIfList[0]); + for (loop = 0; loop < num; ++loop) { + if (g_accelDetectIfList[loop].DetectChip != NULL) { + ret = g_accelDetectIfList[loop].DetectChip(drvData->accelCfg); + if (ret == HDF_SUCCESS) { + drvData->detectFlag = true; + break; + } + } + } + + if (loop == num) { + HDF_LOGE("%s: detect accel device failed", __func__); + drvData->detectFlag = false; + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t InitAccelDriver(struct HdfDeviceObject *device) +{ + struct AccelDrvData *drvData = AccelGetDrvData(); + + if (drvData->detectFlag) { + HDF_LOGE("%s: accel sensor have detected", __func__); + return HDF_SUCCESS; + } + + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*drvData->accelCfg)); + if (drvData->accelCfg == NULL) { + HDF_LOGE("%s: malloc sensor config data failed", __func__); + return HDF_FAILURE; + } + + drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0]; + + if (GetSensorBaseConfigData(device->property, drvData->accelCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: get sensor base config failed", __func__); + goto BASE_CONFIG_EXIT; + } + + // if return failure, hdf framework go to next detect sensor + if (DetectAccelChip() != HDF_SUCCESS) { + HDF_LOGE("%s: accel sensor detect device no exist", __func__); + goto DETECT_CHIP_EXIT; + } + drvData->detectFlag = true; + + if (ParseSensorRegConfig(drvData->accelCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: detect sensor device failed", __func__); + goto REG_CONFIG_EXIT; + } + + if (InitAccelAfterConfig() != HDF_SUCCESS) { + HDF_LOGE("%s: init accel after config failed", __func__); + goto INIT_EXIT; + } + + HDF_LOGI("%s: init accel driver success", __func__); + return HDF_SUCCESS; + +INIT_EXIT: + DestroySensorThread(&drvData->thread, &drvData->threadStatus); + (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); +REG_CONFIG_EXIT: + ReleaseSensorAllRegConfig(drvData->accelCfg); + (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); +DETECT_CHIP_EXIT: + drvData->detectFlag = false; +BASE_CONFIG_EXIT: + drvData->accelCfg->root = NULL; + drvData->accelCfg->regCfgGroup = NULL; + OsalMemFree(drvData->accelCfg); + drvData->accelCfg = NULL; + return HDF_FAILURE; +} + +void ReleaseAccelDriver(struct HdfDeviceObject *device) +{ + (void)device; + struct AccelDrvData *drvData = NULL; + + drvData = AccelGetDrvData(); + (void)DestroySensorThread(&drvData->thread, &drvData->threadStatus); + (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); + drvData->detectFlag = false; + + if (drvData->accelCfg != NULL) { + drvData->accelCfg->root = NULL; + drvData->accelCfg->regCfgGroup = NULL; + ReleaseSensorAllRegConfig(drvData->accelCfg); + (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); + OsalMemFree(drvData->accelCfg); + drvData->accelCfg = NULL; + } + + drvData->initStatus = false; +} + +struct HdfDriverEntry g_sensorAccelDevEntry = { + .moduleVersion = 1, + .moduleName = "HDF_SENSOR_ACCEL", + .Bind = BindAccelDriver, + .Init = InitAccelDriver, + .Release = ReleaseAccelDriver, +}; + +HDF_INIT(g_sensorAccelDevEntry); diff --git a/model/sensor/driver/accel/sensor_accel_driver.h b/model/sensor/driver/accel/sensor_accel_driver.h new file mode 100644 index 00000000..e28b39ff --- /dev/null +++ b/model/sensor/driver/accel/sensor_accel_driver.h @@ -0,0 +1,64 @@ +/* + * 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 SENSOR_ACCEL_DRIVER_H +#define SENSOR_ACCEL_DRIVER_H + +#include "osal_thread.h" +#include "sensor_common.h" +#include "sensor_parser.h" + +#define ACC_DEFAULT_SAMPLING_200_MS 200000000 +#define ACCEL_CHIP_NAME_BMI160 "bmi160" + +enum AccelAxisNum { + ACCEL_X_AXIS = 0, + ACCEL_Y_AXIS = 1, + ACCEL_Z_AXIS = 2, + ACCEL_AXIS_NUM = 3, +}; + +enum AccelAxisPart { + ACCEL_X_AXIS_LSB = 0, + ACCEL_X_AXIS_MSB = 1, + ACCEL_Y_AXIS_LSB = 2, + ACCEL_Y_AXIS_MSB = 3, + ACCEL_Z_AXIS_LSB = 4, + ACCEL_Z_AXIS_MSB = 5, + ACCEL_AXIS_BUTT, +}; + +struct AccelData { + int32_t x; + int32_t y; + int32_t z; +}; + +struct AccelDetectIfList { + char *chipName; + int32_t (*DetectChip)(struct SensorCfgData *data); +}; + +struct AccelOpsCall { + int32_t (*Init)(struct SensorCfgData *data); + int32_t (*ReadData)(struct SensorCfgData *data); +}; + +struct AccelDrvData { + bool detectFlag; + uint8_t threadStatus; + uint8_t initStatus; + int64_t interval; + struct SensorCfgData *accelCfg; + struct OsalThread thread; + struct AccelOpsCall ops; +}; + +int32_t RegisterAccelChipOps(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 new file mode 100644 index 00000000..669dd0c7 --- /dev/null +++ b/model/sensor/driver/chipset/accel/accel_bmi160.c @@ -0,0 +1,163 @@ +/* + * 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 "securec.h" +#include "accel_bmi160.h" +#include "osal_time.h" +#include "sensor_accel_driver.h" +#include "sensor_device_common.h" +#include "sensor_device_manager.h" + +/* IO config for int-pin and I2C-pin */ +#define SENSOR_I2C6_DATA_REG_ADDR 0x114f004c +#define SENSOR_I2C6_CLK_REG_ADDR 0x114f0048 +#define SENSOR_I2C_REG_CFG 0x403 + +static int32_t ReadBmi160RawData(struct SensorCfgData *data, struct AccelData *rawData, int64_t *timestamp) +{ + uint8_t status = 0; + uint8_t reg[ACCEL_AXIS_BUTT]; + OsalTimespec time; + + (void)memset_s(&time, sizeof(time), 0, sizeof(time)); + (void)OsalGetTime(&time); + + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + *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)); + if (!(status & BMI160_ACCEL_DATA_READY_MASK) || (ret != HDF_SUCCESS)) { + return HDF_FAILURE; + } + + 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__); + } + + 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__); + } + + 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__); + } + + 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__); + } + + 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__); + } + + 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__); + } + + rawData->x = (int16_t)(SENSOR_DATA_SHIFT_LEFT(reg[ACCEL_X_AXIS_MSB], SENSOR_DATA_WIDTH_8_BIT) | + reg[ACCEL_X_AXIS_LSB]); + rawData->y = (int16_t)(SENSOR_DATA_SHIFT_LEFT(reg[ACCEL_Y_AXIS_MSB], SENSOR_DATA_WIDTH_8_BIT) | + reg[ACCEL_Y_AXIS_LSB]); + rawData->z = (int16_t)(SENSOR_DATA_SHIFT_LEFT(reg[ACCEL_Z_AXIS_MSB], SENSOR_DATA_WIDTH_8_BIT) | + reg[ACCEL_Z_AXIS_LSB]); + + return ret; +} + +int32_t ReadBmi160Data(struct SensorCfgData *data) +{ + int32_t ret; + struct AccelData rawData = { 0, 0, 0 }; + int32_t tmp[ACCEL_AXIS_NUM]; + struct SensorReportEvent event; + + (void)memset_s(&event, sizeof(event), 0, sizeof(event)); + + ret = ReadBmi160RawData(data, &rawData, &event.timestamp); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + + event.sensorId = SENSOR_TAG_ACCELEROMETER; + event.option = 0; + event.mode = SENSOR_WORK_MODE_REALTIME; + + rawData.x = rawData.x * BMI160_ACC_SENSITIVITY_2G; + rawData.y = rawData.y * BMI160_ACC_SENSITIVITY_2G; + rawData.z = rawData.z * BMI160_ACC_SENSITIVITY_2G; + + tmp[ACCEL_X_AXIS] = (rawData.x * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; + tmp[ACCEL_Y_AXIS] = (rawData.y * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; + tmp[ACCEL_Z_AXIS] = (rawData.z * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; + + event.dataLen = sizeof(tmp); + event.data = (uint8_t *)&tmp; + ret = ReportSensorEvent(&event); + return ret; +} + +static int32_t InitBmi160(struct SensorCfgData *data) +{ + int32_t ret; + + 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__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +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__); + 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__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +int32_t DetectAccelBim160Chip(struct SensorCfgData *data) +{ + int32_t ret; + struct AccelOpsCall ops; + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + + if (strcmp(ACCEL_CHIP_NAME_BMI160, data->sensorAttr.chipName) != 0) { + return HDF_SUCCESS; + } + ret = InitAccelPreConfig(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: init BMI160 bus mux config", __func__); + return HDF_FAILURE; + } + if (DetectSensorDevice(data) != HDF_SUCCESS) { + return HDF_FAILURE; + } + ops.Init = InitBmi160; + ops.ReadData = ReadBmi160Data; + ret = RegisterAccelChipOps(&ops); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: register BMI160 accel failed", __func__); + (void)ReleaseSensorBusHandle(&data->busCfg); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} diff --git a/model/sensor/driver/chipset/accel/accel_bmi160.h b/model/sensor/driver/chipset/accel/accel_bmi160.h new file mode 100644 index 00000000..4147f235 --- /dev/null +++ b/model/sensor/driver/chipset/accel/accel_bmi160.h @@ -0,0 +1,63 @@ +/* + * 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 ACCEL_BMI160_H +#define ACCEL_BMI160_H + +#include "sensor_parser.h" + +/* ACCEL DATA REGISTERS ADDR */ +#define BMI160_ACCEL_X_LSB_ADDR 0X12 +#define BMI160_ACCEL_X_MSB_ADDR 0X13 +#define BMI160_ACCEL_Y_LSB_ADDR 0X14 +#define BMI160_ACCEL_Y_MSB_ADDR 0X15 +#define BMI160_ACCEL_Z_LSB_ADDR 0X16 +#define BMI160_ACCEL_Z_MSB_ADDR 0X17 +#define BMI160_STATUS_ADDR 0X1B + +/* ACCEL ODR */ +#define BMI160_ACCEL_ODR_RESERVED 0x00 +#define BMI160_ACCEL_ODR_0_78HZ 0x01 +#define BMI160_ACCEL_ODR_1_56HZ 0x02 +#define BMI160_ACCEL_ODR_3_12HZ 0x03 +#define BMI160_ACCEL_ODR_6_25HZ 0x04 +#define BMI160_ACCEL_ODR_12_5HZ 0x05 +#define BMI160_ACCEL_ODR_25HZ 0x06 +#define BMI160_ACCEL_ODR_50HZ 0x07 +#define BMI160_ACCEL_ODR_100HZ 0x08 +#define BMI160_ACCEL_ODR_200HZ 0x09 +#define BMI160_ACCEL_ODR_400HZ 0x0A +#define BMI160_ACCEL_ODR_800HZ 0x0B +#define BMI160_ACCEL_ODR_1600HZ 0x0C +#define BMI160_ACCEL_ODR_RESERVED0 0x0D +#define BMI160_ACCEL_ODR_RESERVED1 0x0E +#define BMI160_ACCEL_ODR_RESERVED2 0x0F + +/* default HZ */ +#define BMI160_ACCEL_DEFAULT_ODR_100HZ 100 +#define BMI160_ACCEL_DEFAULT_ODR_25HZ 25 + +/* ACCEL RANGE */ +#define BMI160_ACCEL_RANGE_2G 0X03 +#define BMI160_ACCEL_RANGE_4G 0X05 +#define BMI160_ACCEL_RANGE_8G 0X08 +#define BMI160_ACCEL_RANGE_16G 0X0C + +/* ACC sensitivity */ +#define BMI160_ACC_SENSITIVITY_2G 61 +#define BMI160_ACC_SENSITIVITY_4G 122 +#define BMI160_ACC_SENSITIVITY_8G 244 +#define BMI160_ACC_SENSITIVITY_16G 488 + +/* ACCEL DATA READY */ +#define BMI160_ACCEL_DATA_READY_MASK 0x80 + +int32_t DetectAccelBim160Chip(struct SensorCfgData *data); +int32_t ReadBmi160Data(struct SensorCfgData *data); + +#endif /* ACCEL_BMI160_H */ diff --git a/model/sensor/driver/common/include/sensor_device_common.h b/model/sensor/driver/common/include/sensor_device_common.h new file mode 100644 index 00000000..deda542b --- /dev/null +++ b/model/sensor/driver/common/include/sensor_device_common.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 SENSOR_DEVICE_COMMON_H +#define SENSOR_DEVICE_COMMON_H + +#include "sensor_parser.h" + +enum SensorCalculateType { + SENSOR_CFG_CALC_TYPE_NONE = 0, + SENSOR_CFG_CALC_TYPE_SET = 1, // To Support:1.Bitwise AND "&" 2.Bitwise OR "|" + SENSOR_CFG_CALC_TYPE_REVERT = 2, // To Support:1.Bitwise REVERT '~' + SENSOR_CFG_CALC_TYPE_XOR = 3, // To Support:1.Bitwise XOR "^" + SENSOR_CFG_CALC_TYPE_LEFT_SHIFT = 4, // To Support:1.Left shift << + SENSOR_CFG_CALC_TYPE_RIGHT_SHIFT = 5, // To Support:1.Right shift >> +}; + +enum SensorOpsType { + SENSOR_OPS_TYPE_NOP = 0, + SENSOR_OPS_TYPE_READ = 1, + SENSOR_OPS_TYPE_WRITE = 2, + SENSOR_OPS_TYPE_READ_CHECK = 3, + SENSOR_OPS_TYPE_UPDATE_BITWISE = 4, +}; + +struct SensorOpsCall { + enum SensorOpsType type; + int32_t (*ops)(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem); +}; + +int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group); + +#endif /* SENSOR_DEVICE_COMMON_H */ diff --git a/model/sensor/driver/common/include/sensor_device_manager.h b/model/sensor/driver/common/include/sensor_device_manager.h new file mode 100644 index 00000000..c626ca2b --- /dev/null +++ b/model/sensor/driver/common/include/sensor_device_manager.h @@ -0,0 +1,63 @@ +/* + * 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 SENSOR_DEVICE_MANAGER_H +#define SENSOR_DEVICE_MANAGER_H + +#include "osal_mutex.h" +#include "sensor_driver_type.h" + +enum SensorMethodCmd { + SENSOR_CMD_GET_INFO_LIST = 0xFFFF, + SENSOR_CMD_ENABLE = 1, + SENSOR_CMD_DISABLE = 2, + SENSOR_CMD_SET_BATCH = 3, + SENSOR_CMD_SET_MODE = 4, + SENSOR_CMD_SET_OPTION = 5, + SENSOR_CMD_BUTT, +}; + +struct SensorOps { + int32_t (*GetInfo)(struct SensorBasicInfo *sensorInfo); + int32_t (*Enable)(void); + int32_t (*Disable)(void); + int32_t (*SetBatch)(int64_t samplingInterval, int64_t reportInterval); + int32_t (*SetMode)(int32_t mode); + int32_t (*SetOption)(uint32_t option); +}; + +struct SensorDeviceInfo { + struct SensorBasicInfo sensorInfo; + struct SensorOps ops; +}; + +struct SensorDevInfoNode { + struct SensorDeviceInfo devInfo; + struct DListHead node; +}; + +typedef int32_t (*SensorCmdHandle)(struct SensorDeviceInfo *info, struct HdfSBuf *reqData, struct HdfSBuf *reply); + +struct SensorCmdHandleList { + enum SensorMethodCmd cmd; + SensorCmdHandle func; +}; + +struct SensorDevMgrData { + struct IDeviceIoService ioService; + struct HdfDeviceObject *device; + struct DListHead sensorDevInfoHead; + struct OsalMutex mutex; + struct OsalMutex eventMutex; +}; + +int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo); +int32_t DeleteSensorDevice(int32_t sensorId); +int32_t ReportSensorEvent(const struct SensorReportEvent *events); + +#endif /* SENSOR_DEVICE_MANAGER_H */ diff --git a/model/sensor/driver/common/include/sensor_parser.h b/model/sensor/driver/common/include/sensor_parser.h new file mode 100644 index 00000000..f3950e37 --- /dev/null +++ b/model/sensor/driver/common/include/sensor_parser.h @@ -0,0 +1,105 @@ +/* + * 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 SENSOR_PARSER_H +#define SENSOR_PARSER_H + +#include "device_resource_if.h" +#include "hdf_device_desc.h" +#include "i2c_if.h" +#include "sensor_driver_type.h" +#include "spi_if.h" + +enum SensorBusType { + SENSOR_BUS_I2C = 0, + SENSOR_BUS_SPI = 1, +}; + +enum SensorRegOpsType { + SENSOR_INIT_GROUP = 0, + SENSOR_ENABLE_GROUP, + SENSOR_DISABLE_GROUP, + SENSOR_GROUP_MAX, +}; + +struct SensorI2cCfg { + DevHandle handle; + uint16_t busNum; + uint16_t devAddr; // Address of the I2C device + uint16_t regWidth; // length of the register address +}; + +struct SensorSpiCfg { + DevHandle handle; + uint32_t busNum; + uint32_t csNum; +}; + +struct SensorBusCfg { + uint8_t busType; // enum SensorBusType + uint8_t regBigEndian; + union { + struct SensorI2cCfg i2cCfg; + struct SensorSpiCfg spiCfg; + }; +}; + +struct SensorAttr { + const char *chipName; + uint16_t chipIdReg; + uint16_t chipIdValue; +}; + +enum SensorRegCfgIndex { + SENSOR_REG_CFG_ADDR_INDEX = 0, + SENSOR_REG_CFG_VALUE_INDEX, + SENSOR_REG_CFG_MASK_INDEX, + SENSOR_REG_CFG_LEN_INDEX, + SENSOR_REG_CFG_DELAY_INDEX, + SENSOR_REG_CFG_OPS_INDEX, + SENSOR_REG_CFG_CAL_INDEX, + SENSOR_REG_CFG_SHIFT_INDEX, + SENSOR_REG_CFG_DEBUG_INDEX, + SENSOR_REG_CFG_SAVE_INDEX, + SENSOR_REG_CFG_INDEX_MAX, +}; + +struct SensorRegCfg { + uint16_t regAddr; + uint16_t value; + uint16_t mask; + uint16_t len; + uint32_t delay : 12; + uint32_t opsType : 5; + uint32_t calType : 3; + uint32_t shiftNum : 4; + uint32_t debug : 1; + uint32_t save : 2; +}; + +struct SensorRegCfgGroupNode { + uint8_t itemNum; + struct SensorRegCfg *regCfgItem; +}; + +struct SensorCfgData { + struct SensorBusCfg busCfg; + struct SensorBasicInfo sensorInfo; + struct SensorAttr sensorAttr; + struct SensorRegCfgGroupNode **regCfgGroup; + const struct DeviceResourceNode *root; +}; + +int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config); +int32_t ParseSensorRegConfig(struct SensorCfgData *config); +void ReleaseSensorAllRegConfig(struct SensorCfgData *config); +int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg); +int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg); +int32_t DetectSensorDevice(struct SensorCfgData *config); + +#endif /* SENSOR_PARSER_H */ diff --git a/model/sensor/driver/common/src/sensor_common.c b/model/sensor/driver/common/src/sensor_common.c new file mode 100644 index 00000000..0c47fa03 --- /dev/null +++ b/model/sensor/driver/common/src/sensor_common.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 "securec.h" +#include "osal_io.h" +#include "osal_thread.h" +#include "osal_time.h" +#include "sensor_common.h" + +#define HDF_LOG_TAG sensor_common_operation_c + +#define I2C_READ_MSG_NUM 2 +#define I2C_READ_MSG_ADDR_IDX 0 +#define I2C_READ_MSG_VALUE_IDX 1 + +#define I2C_WRITE_MSG_NUM 1 +#define I2C_REG_BUF_LEN 4 +#define I2C_BYTE_MASK 0xFF +#define I2C_BYTE_OFFSET 8 + +#define SENSOR_STACK_SIZE 0x2000 // 4k buffer + +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]; + + CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_FAILURE); + + busType = busCfg->busType; + if (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; + msg[I2C_READ_MSG_ADDR_IDX].len = busCfg->i2cCfg.regWidth; + msg[I2C_READ_MSG_ADDR_IDX].buf = regBuf; + + if (busCfg->i2cCfg.regWidth == SENSOR_ADDR_WIDTH_1_BYTE) { + regBuf[index++] = regAddr & I2C_BYTE_MASK; + } 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; + } + + msg[I2C_READ_MSG_VALUE_IDX].addr = busCfg->i2cCfg.devAddr; + msg[I2C_READ_MSG_VALUE_IDX].flags = I2C_FLAG_READ; + msg[I2C_READ_MSG_VALUE_IDX].len = dataLen; + 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); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +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) { + 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; + msg[0].len = dataLen; + 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); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +int32_t SetSensorPinMux(uint32_t regAddr, int32_t regSize, uint32_t regValue) +{ + uint8_t *base = NULL; + if (regAddr == 0) { + HDF_LOGE("%s: regAddr invalid", __func__); + return HDF_FAILURE; + } + + base = OsalIoRemap(regAddr, regSize); + if (base == NULL) { + HDF_LOGE("%s: ioremap fail", __func__); + return HDF_FAILURE; + } + + OSAL_WRITEL(regValue, base); + OsalIoUnmap((void *)base); + + return HDF_SUCCESS; +} + +int32_t CreateSensorThread(struct OsalThread *thread, OsalThreadEntry threadEntry, char *name, void *entryPara) +{ + struct OsalThreadParam config = { + .name = name, + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = SENSOR_STACK_SIZE, + }; + + CHECK_NULL_PTR_RETURN_VALUE(thread, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(threadEntry, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(name, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(entryPara, HDF_ERR_INVALID_PARAM); + + int32_t status = OsalThreadCreate(thread, threadEntry, entryPara); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s: sensor create thread failed!status=%d", __func__, status); + return HDF_FAILURE; + } + + status = OsalThreadStart(thread, &config); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s: sensor start thread failed!status=%d", __func__, status); + OsalThreadDestroy(thread); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +void DestroySensorThread(struct OsalThread *thread, uint8_t *status) +{ + int count = 0; + CHECK_NULL_PTR_RETURN(thread); + CHECK_NULL_PTR_RETURN(status); + + if (*status == SENSOR_THREAD_NONE || *status == SENSOR_THREAD_DESTROY) { + HDF_LOGE("%s,delete thread not need!", __func__); + return; + } + + if (*status != SENSOR_THREAD_STOPPED) { + *status = SENSOR_THREAD_STOPPING; + /* wait until thread worker exit */ + while ((*status != SENSOR_THREAD_STOPPED) && (count < MAX_SENSOR_EXIT_THREAD_COUNT)) { + OsalMSleep(MAX_SENSOR_WAIT_THREAD_TIME); + count++; + } + } + + OsalThreadDestroy(thread); + *status = SENSOR_THREAD_DESTROY; +} diff --git a/model/sensor/driver/common/src/sensor_device_common.c b/model/sensor/driver/common/src/sensor_device_common.c new file mode 100644 index 00000000..7816aee9 --- /dev/null +++ b/model/sensor/driver/common/src/sensor_device_common.c @@ -0,0 +1,137 @@ +/* + * 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 "securec.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "sensor_common.h" +#include "sensor_device_common.h" + +#define HDF_LOG_TAG sensor_common_handler_c + +static int32_t SensorOpsNop(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) +{ + (void)busCfg; + (void)cfgItem; + return HDF_SUCCESS; +} + +static int32_t SensorOpsRead(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) +{ + uint16_t value = 0; + int32_t ret; + + ret = ReadSensor(busCfg, cfgItem->regAddr, (uint8_t *)&value, sizeof(value)); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "read i2c reg"); + + return value; +} + +static uint16_t GetSensorRegRealValueMask(struct SensorRegCfg *cfgItem, uint16_t *value, uint16_t busMask) +{ + uint16_t mask = cfgItem->mask & busMask; + *value = cfgItem->value & busMask; + + if (cfgItem->shiftNum != 0) { + if (cfgItem->calType == SENSOR_CFG_CALC_TYPE_RIGHT_SHIFT) { + *value = *value >> cfgItem->shiftNum; + mask = mask >> cfgItem->shiftNum; + } else { + *value = *value << cfgItem->shiftNum; + mask = mask << cfgItem->shiftNum; + } + } + + return mask; +} + +static int32_t SensorOpsWrite(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) +{ + uint8_t calType = cfgItem->calType; + uint8_t value[SENSOR_VALUE_BUTT]; + int32_t ret = HDF_FAILURE; + + value[SENSOR_ADDR_INDEX] = cfgItem->regAddr; + value[SENSOR_VALUE_INDEX] = cfgItem->value; + + switch (calType) { + case SENSOR_CFG_CALC_TYPE_NONE: + ret = WriteSensor(busCfg, value, sizeof(value)); + break; + case SENSOR_CFG_CALC_TYPE_SET: + case SENSOR_CFG_CALC_TYPE_REVERT: + case SENSOR_CFG_CALC_TYPE_XOR: + case SENSOR_CFG_CALC_TYPE_LEFT_SHIFT: + case SENSOR_CFG_CALC_TYPE_RIGHT_SHIFT: + default: + break; + } + + return ret; +} + +static int32_t SensorOpsReadCheck(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) +{ + uint16_t value = 0; + uint16_t originValue; + uint16_t mask; + uint16_t busMask = 0xffff; + int32_t ret; + uint8_t busType = busCfg->busType; + + if (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; + } + + mask = GetSensorRegRealValueMask(cfgItem, &originValue, busMask); + if ((value & mask) != (originValue & mask)) { + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t SensorOpsUpdateBitwise(struct SensorBusCfg *busCfg, struct SensorRegCfg *cfgItem) +{ + return HDF_SUCCESS; +} + +static struct SensorOpsCall g_doOpsCall[] = { + { SENSOR_OPS_TYPE_NOP, SensorOpsNop }, + { SENSOR_OPS_TYPE_READ, SensorOpsRead }, + { SENSOR_OPS_TYPE_WRITE, SensorOpsWrite }, + { SENSOR_OPS_TYPE_READ_CHECK, SensorOpsReadCheck }, + { SENSOR_OPS_TYPE_UPDATE_BITWISE, SensorOpsUpdateBitwise }, +}; + +int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group) +{ + int32_t num = 0; + struct SensorRegCfg *cfgItem = NULL; + + CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_FAILURE); + CHECK_NULL_PTR_RETURN_VALUE(group, HDF_FAILURE); + + while (num < group->itemNum) { + cfgItem = (group->regCfgItem + num); + 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__); + return HDF_FAILURE; + } + } + if (cfgItem->delay != 0) { + OsalMDelay(cfgItem->delay); + } + num++; + } + + return HDF_SUCCESS; +} diff --git a/model/sensor/driver/common/src/sensor_device_manager.c b/model/sensor/driver/common/src/sensor_device_manager.c new file mode 100644 index 00000000..94c3c950 --- /dev/null +++ b/model/sensor/driver/common/src/sensor_device_manager.c @@ -0,0 +1,352 @@ +/* + * 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 "asm/io.h" +#include "securec.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_mem.h" +#include "sensor_common.h" +#include "sensor_device_manager.h" + +#define HDF_LOG_TAG sensor_device_manager_c + +#define HDF_SENSOR_INFO_MAX_BUF (4 * 1024) // 4kB for all sensor info +#define HDF_SENSOR_EVENT_MAX_BUF (4 * 1024) // 4kB + +struct SensorDevMgrData *g_sensorDeviceManager = NULL; + +static struct SensorDevMgrData *GetSensorDeviceManager(void) +{ + return g_sensorDeviceManager; +} + +int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) +{ + bool existSensor = false; + struct SensorDevInfoNode *pos = NULL; + struct SensorDevInfoNode *tmp = NULL; + struct SensorDevInfoNode *devInfoNode = NULL; + struct SensorDevMgrData *manager = GetSensorDeviceManager(); + + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + + (void)OsalMutexLock(&manager->mutex); + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &manager->sensorDevInfoHead, struct SensorDevInfoNode, node) { + if (deviceInfo->sensorInfo.sensorId == pos->devInfo.sensorInfo.sensorId) { + HDF_LOGE("%s: sensor chip[0x%x] had existed", __func__, deviceInfo->sensorInfo.sensorId); + existSensor = true; + break; + } + } + + if (!existSensor) { + devInfoNode = (struct SensorDevInfoNode*)OsalMemCalloc(sizeof(*devInfoNode)); + if (memcpy_s(&devInfoNode->devInfo, sizeof(devInfoNode->devInfo), + (void *)deviceInfo, sizeof(*deviceInfo)) != EOK) { + HDF_LOGE("%s: copy sensor info failed", __func__); + OsalMemFree(devInfoNode); + (void)OsalMutexUnlock(&manager->mutex); + return HDF_FAILURE; + } + DListInsertTail(&devInfoNode->node, &manager->sensorDevInfoHead); + HDF_LOGI("%s: register sensor device name[%s] success", __func__, deviceInfo->sensorInfo.sensorName); + } + (void)OsalMutexUnlock(&manager->mutex); + + return HDF_SUCCESS; +} + +int32_t DeleteSensorDevice(int32_t sensorId) +{ + struct SensorDevInfoNode *pos = NULL; + struct SensorDevInfoNode *tmp = NULL; + struct SensorDevMgrData *manager = GetSensorDeviceManager(); + + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + (void)OsalMutexLock(&manager->mutex); + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &manager->sensorDevInfoHead, struct SensorDevInfoNode, node) { + if (sensorId == pos->devInfo.sensorInfo.sensorId) { + DListRemove(&pos->node); + OsalMemFree(pos); + break; + } + } + (void)OsalMutexUnlock(&manager->mutex); + + return HDF_SUCCESS; +} + +int32_t ReportSensorEvent(const struct SensorReportEvent *events) +{ + int32_t ret; + + CHECK_NULL_PTR_RETURN_VALUE(events, HDF_ERR_INVALID_PARAM); + + struct SensorDevMgrData *manager = GetSensorDeviceManager(); + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + + (void)OsalMutexLock(&manager->eventMutex); + struct HdfSBuf *msg = HdfSBufObtain(HDF_SENSOR_EVENT_MAX_BUF); + CHECK_NULL_PTR_RETURN_VALUE(msg, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufWriteBuffer(msg, events, sizeof(*events))) { + HDF_LOGE("%s: sbuf write event failed", __func__); + ret = HDF_FAILURE; + goto EXIT; + } + + if (!HdfSbufWriteBuffer(msg, events->data, events->dataLen)) { + HDF_LOGE("%s: sbuf write event data failed", __func__); + ret = HDF_FAILURE; + goto EXIT; + } + + if (HdfDeviceSendEvent(manager->device, 0, msg) != HDF_SUCCESS) { + HDF_LOGE("%s: send sensor data event failed", __func__); + ret = HDF_FAILURE; + goto EXIT; + } + ret = HDF_SUCCESS; + +EXIT: + HdfSBufRecycle(msg); + (void)OsalMutexUnlock(&manager->eventMutex); + return ret; +} + +static int32_t GetAllSensorInfo(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)data; + struct SensorDevInfoNode *pos = NULL; + struct SensorDevInfoNode *tmp = NULL; + struct SensorBasicInfo *sensorInfo = NULL; + struct SensorDevMgrData *manager = GetSensorDeviceManager(); + int32_t count = 0; + + CHECK_NULL_PTR_RETURN_VALUE(reply, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &manager->sensorDevInfoHead, struct SensorDevInfoNode, node) { + sensorInfo = &(pos->devInfo.sensorInfo); + if (!HdfSbufWriteBuffer(reply, sensorInfo, sizeof(*sensorInfo))) { + + HDF_LOGE("%s: write sbuf failed", __func__); + return HDF_FAILURE; + } + pos->devInfo.ops.GetInfo(NULL); + + count++; + if ((count + 1) * sizeof(*sensorInfo) > HDF_SENSOR_INFO_MAX_BUF) { + HDF_LOGE("%s: write sbuf exceed max buf, sensor count[%d]", __func__, count); + break; + } + } + + return HDF_SUCCESS; +} + +static int32_t Enable(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)data; + (void)reply; + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo->ops.Enable, HDF_ERR_INVALID_PARAM); + return deviceInfo->ops.Enable(); +} + +static int32_t Disable(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)data; + (void)reply; + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo->ops.Disable, HDF_ERR_INVALID_PARAM); + + return deviceInfo->ops.Disable(); +} + +static int32_t SetBatch(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int64_t samplingInterval; + int64_t reportInterval; + (void)reply; + + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo->ops.SetBatch, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufReadInt64(data, &samplingInterval) || !HdfSbufReadInt64(data, &reportInterval)) { + HDF_LOGE("%s: sbuf read interval failed", __func__); + return HDF_FAILURE; + } + + return deviceInfo->ops.SetBatch(samplingInterval, reportInterval); +} + +static int32_t SetMode(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t mode; + (void)reply; + + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo->ops.SetMode, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufReadInt32(data, &mode)) { + HDF_LOGE("%s: sbuf read mode failed", __func__); + return HDF_FAILURE; + } + + return deviceInfo->ops.SetMode(mode); +} + +static int32_t SetOption(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t option; + (void)reply; + + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(deviceInfo->ops.SetOption, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufReadUint32(data, &option)) { + HDF_LOGE("%s: sbuf read option failed", __func__); + return HDF_FAILURE; + } + + return deviceInfo->ops.SetOption(option); +} + +static struct SensorCmdHandleList g_sensorCmdHandle[] = { + {SENSOR_CMD_ENABLE, Enable}, // SENSOR_CMD_ENABLE + {SENSOR_CMD_DISABLE, Disable}, // SENSOR_CMD_DISABLE + {SENSOR_CMD_SET_BATCH, SetBatch}, // SENSOR_CMD_SET_BATCH + {SENSOR_CMD_SET_MODE, SetMode}, // SENSOR_CMD_SET_MODE + {SENSOR_CMD_SET_OPTION, SetOption}, // SENSOR_CMD_SET_OPTION +}; + +static int32_t DispatchCmdHandle(struct SensorDeviceInfo *deviceInfo, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t methodCmd; + int32_t loop; + + CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufReadInt32(data, &methodCmd)) { + HDF_LOGE("%s: sbuf read methodCmd failed", __func__); + return HDF_FAILURE; + } + + if (methodCmd >= SENSOR_CMD_BUTT || methodCmd <= 0) { + HDF_LOGE("%s: invalid cmd = %d", __func__, methodCmd); + return HDF_FAILURE; + } + + for (loop = 0; loop < sizeof(g_sensorCmdHandle) / sizeof(g_sensorCmdHandle[0]); ++loop) { + if ((methodCmd == g_sensorCmdHandle[loop].cmd) && (g_sensorCmdHandle[loop].func != NULL)) { + return g_sensorCmdHandle[loop].func(deviceInfo, data, reply); + } + } + + return HDF_FAILURE; +} + +#define SENSOR_ID_CMD_INFO_LIST 0xFFFF +static int32_t DispatchSensor(struct HdfDeviceIoClient *client, + int32_t cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct SensorDevMgrData *manager = GetSensorDeviceManager(); + struct SensorDevInfoNode *pos = NULL; + struct SensorDevInfoNode *tmp = NULL; + int32_t ret = HDF_FAILURE; + + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(client, HDF_ERR_INVALID_PARAM); + + if (cmd == SENSOR_ID_CMD_INFO_LIST) { + return GetAllSensorInfo(data, reply); + } + + (void)OsalMutexLock(&manager->mutex); + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &manager->sensorDevInfoHead, struct SensorDevInfoNode, node) { + if (cmd == pos->devInfo.sensorInfo.sensorId) { + ret = DispatchCmdHandle(&pos->devInfo, data, reply); + break; + } + } + (void)OsalMutexUnlock(&manager->mutex); + + return ret; +} + +int32_t BindSensorDevManager(struct HdfDeviceObject *device) +{ + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + struct SensorDevMgrData *manager = (struct SensorDevMgrData *)OsalMemCalloc(sizeof(*manager)); + if (manager == NULL) { + HDF_LOGE("%s: malloc manager fail!", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + manager->ioService.Dispatch = DispatchSensor; + manager->device = device; + device->service = &manager->ioService; + g_sensorDeviceManager = manager; + + return HDF_SUCCESS; +} + +int32_t InitSensorDevManager(struct HdfDeviceObject *device) +{ + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + struct SensorDevMgrData *manager = (struct SensorDevMgrData *)device->service; + CHECK_NULL_PTR_RETURN_VALUE(manager, HDF_ERR_INVALID_PARAM); + + DListHeadInit(&manager->sensorDevInfoHead); + OsalMutexInit(&manager->mutex); + OsalMutexInit(&manager->eventMutex); + + 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__); + return HDF_SUCCESS; +} + +void ReleaseSensorDevManager(struct HdfDeviceObject *device) +{ + CHECK_NULL_PTR_RETURN(device); + + struct SensorDevInfoNode *pos = NULL; + struct SensorDevInfoNode *tmp = NULL; + struct SensorDevMgrData *manager = (struct SensorDevMgrData *)device->service; + CHECK_NULL_PTR_RETURN(manager); + + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &manager->sensorDevInfoHead, struct SensorDevInfoNode, node) { + DListRemove(&pos->node); + OsalMemFree(pos); + } + + OsalMutexDestroy(&manager->mutex); + OsalMemFree(manager); + g_sensorDeviceManager = NULL; +} + +struct HdfDriverEntry g_sensorDevManagerEntry = { + .moduleVersion = 1, + .moduleName = "HDF_SENSOR_MGR_AP", + .Bind = BindSensorDevManager, + .Init = InitSensorDevManager, + .Release = ReleaseSensorDevManager, +}; + +HDF_INIT(g_sensorDevManagerEntry); diff --git a/model/sensor/driver/common/src/sensor_parser.c b/model/sensor/driver/common/src/sensor_parser.c new file mode 100644 index 00000000..96392aca --- /dev/null +++ b/model/sensor/driver/common/src/sensor_parser.c @@ -0,0 +1,382 @@ +/* + * 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 "securec.h" +#include "device_resource_if.h" +#include "osal_mem.h" +#include "sensor_common.h" +#include "sensor_parser.h" + +#define HDF_LOG_TAG sensor_config_parser_c + +static char *g_sensorRegGroupName[SENSOR_GROUP_MAX] = { + "initSeqConfig", + "enableSeqConfig", + "disableSeqConfig", +}; + +static uint32_t GetSensorRegGroupNameIndex(const char *name) +{ + uint32_t index = 0xFF; + + if (name == NULL) { + return index; + } + + for (index = 0; index < SENSOR_GROUP_MAX; ++index) { + if (strcmp(name, g_sensorRegGroupName[index]) == 0) { + break; + } + } + + if (index == SENSOR_GROUP_MAX) { + index = 0xFF; + } + + return index; +} + +void ReleaseSensorAllRegConfig(struct SensorCfgData *config) +{ + int32_t index; + + if (config == NULL || config->regCfgGroup == NULL) { + return; + } + + for (index = 0; index < SENSOR_GROUP_MAX; ++index) { + if (config->regCfgGroup[index] != NULL) { + if (config->regCfgGroup[index]->regCfgItem != NULL) { + OsalMemFree(config->regCfgGroup[index]->regCfgItem); + config->regCfgGroup[index]->regCfgItem = NULL; + } + OsalMemFree(config->regCfgGroup[index]); + config->regCfgGroup[index] = NULL; + } + } +} + +static int32_t ParseSensorRegItem(struct DeviceResourceIface *parser, const struct DeviceResourceNode *regNode, + const char *groupName, struct SensorRegCfgGroupNode *group) +{ + int32_t ret; + int32_t step; + int32_t index; + int32_t itemNum = group->itemNum; + + CHECK_NULL_PTR_RETURN_VALUE(group->regCfgItem, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(groupName, HDF_ERR_INVALID_PARAM); + + int32_t num = parser->GetElemNum(regNode, groupName); + uint16_t *buf = (uint16_t *)OsalMemCalloc(sizeof(uint16_t) * num); + CHECK_NULL_PTR_RETURN_VALUE(buf, HDF_ERR_MALLOC_FAIL); + + ret = parser->GetUint16Array(regNode, groupName, buf, num, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: parser %s reg array failed", __func__, groupName); + OsalMemFree(buf); + return HDF_SUCCESS; + } + + for (index = 0; index < itemNum; ++index) { + step = SENSOR_REG_CFG_INDEX_MAX * index; + if (step + SENSOR_REG_CFG_SAVE_INDEX >= num) { + break; + } + group->regCfgItem[index].regAddr = buf[step + SENSOR_REG_CFG_ADDR_INDEX]; + group->regCfgItem[index].value = buf[step + SENSOR_REG_CFG_VALUE_INDEX]; + group->regCfgItem[index].mask = buf[step + SENSOR_REG_CFG_MASK_INDEX]; + group->regCfgItem[index].len = buf[step + SENSOR_REG_CFG_LEN_INDEX]; + group->regCfgItem[index].delay = buf[step + SENSOR_REG_CFG_DELAY_INDEX]; + group->regCfgItem[index].opsType = buf[step + SENSOR_REG_CFG_OPS_INDEX]; + group->regCfgItem[index].calType = buf[step + SENSOR_REG_CFG_CAL_INDEX]; + group->regCfgItem[index].shiftNum = buf[step + SENSOR_REG_CFG_SHIFT_INDEX]; + group->regCfgItem[index].debug = buf[step + SENSOR_REG_CFG_DEBUG_INDEX]; + group->regCfgItem[index].save = buf[step + SENSOR_REG_CFG_SAVE_INDEX]; + } + OsalMemFree(buf); + + return HDF_SUCCESS; +} + +static int32_t ParseSensorRegGroup(struct DeviceResourceIface *parser, const struct DeviceResourceNode *regCfgNode, + const char *groupName, struct SensorRegCfgGroupNode **groupNode) +{ + struct SensorRegCfgGroupNode *group = NULL; + + CHECK_NULL_PTR_RETURN_VALUE(parser, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(regCfgNode, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(groupName, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(groupNode, HDF_ERR_INVALID_PARAM); + + int32_t num = parser->GetElemNum(regCfgNode, groupName); + group = *groupNode; + + if (num > 0) { + if (group != NULL) { + if (group->regCfgItem != NULL) { + OsalMemFree(group->regCfgItem); + } + OsalMemFree(group); + } + + group = (struct SensorRegCfgGroupNode*)OsalMemCalloc(sizeof(*group)); + if (group == NULL) { + HDF_LOGE("%s: malloc sensor reg config group failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + *groupNode = group; + group->itemNum = num / SENSOR_REG_CFG_INDEX_MAX; + group->itemNum = ((SENSOR_REG_CFG_INDEX_MAX * group->itemNum) < num) ? (group->itemNum + 1) : group->itemNum; + + group->regCfgItem = (struct SensorRegCfg*)OsalMemCalloc(group->itemNum * sizeof(*(group->regCfgItem))); + if (group->regCfgItem == NULL) { + HDF_LOGE("%s: malloc sensor reg config item failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + if (ParseSensorRegItem(parser, regCfgNode, groupName, group) != HDF_SUCCESS) { + HDF_LOGE("%s: malloc sensor reg config item data failed", __func__); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +int32_t ParseSensorRegConfig(struct SensorCfgData *config) +{ + int32_t index; + const struct DeviceResourceNode *regCfgNode = NULL; + struct DeviceResourceIface *parser = NULL; + const struct DeviceResourceAttr *regAttr = NULL; + + CHECK_NULL_PTR_RETURN_VALUE(config->root, HDF_ERR_INVALID_PARAM); + parser = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + CHECK_NULL_PTR_RETURN_VALUE(parser, HDF_ERR_INVALID_PARAM); + + regCfgNode = parser->GetChildNode(config->root, "accelRegConfig"); + CHECK_NULL_PTR_RETURN_VALUE(regCfgNode, HDF_ERR_INVALID_PARAM); + + DEV_RES_NODE_FOR_EACH_ATTR(regCfgNode, regAttr) { + if (regAttr == NULL || regAttr->name == NULL) { + HDF_LOGE("%s:sensor reg node attr is null", __func__); + break; + } + + index = GetSensorRegGroupNameIndex(regAttr->name); + if (index >= SENSOR_GROUP_MAX) { + HDF_LOGE("%s: get sensor register group index failed", __func__); + goto error; + } + + if (ParseSensorRegGroup(parser, regCfgNode, regAttr->name, &config->regCfgGroup[index]) != HDF_SUCCESS) { + HDF_LOGE("%s: parse sensor register group failed", __func__); + goto error; + } + } + return HDF_SUCCESS; + +error: + ReleaseSensorAllRegConfig(config); + HDF_LOGE("%s: parse sensor reg config failed", __func__); + return HDF_FAILURE; +} + +int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) +{ + CHECK_NULL_PTR_RETURN_VALUE(busCfg, HDF_ERR_INVALID_PARAM); + + 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; + } + } + + return HDF_SUCCESS; +} + +int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg) +{ + if (busCfg == NULL) { + return HDF_SUCCESS; + } + + if (busCfg->busType == SENSOR_BUS_I2C && busCfg->i2cCfg.handle != NULL) { + I2cClose(busCfg->i2cCfg.handle); + busCfg->i2cCfg.handle = NULL; + } + + return HDF_SUCCESS; +} + +int32_t DetectSensorDevice(struct SensorCfgData *config) +{ + uint8_t value = 0; + uint16_t chipIdReg; + uint16_t chipIdValue; + + CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM); + + chipIdReg = config->sensorAttr.chipIdReg; + chipIdValue = config->sensorAttr.chipIdValue; + + int32_t ret = GetSensorBusHandle(&config->busCfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get sensor bus handle failed", __func__); + (void)ReleaseSensorBusHandle(&config->busCfg); + return HDF_FAILURE; + } + + ret = ReadSensor(&config->busCfg, chipIdReg, &value, sizeof(value)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: i2c read chip id failed", __func__); + (void)ReleaseSensorBusHandle(&config->busCfg); + return HDF_FAILURE; + } + + if (value != chipIdValue) { + HDF_LOGE("%s: sensor chip[0x%x] id [0x%x] detect value[%d]", __func__, chipIdReg, chipIdValue, value); + (void)ReleaseSensorBusHandle(&config->busCfg); + return HDF_FAILURE; + } + + HDF_LOGD("%s: sensor [%s] detect chip success", __func__, config->sensorInfo.sensorName); + return HDF_SUCCESS; +} + +static int32_t ParseSensorInfo(struct DeviceResourceIface *parser, const struct DeviceResourceNode *infoNode, + struct SensorCfgData *config) +{ + int32_t ret; + const char *name = NULL; + + ret = parser->GetString(infoNode, "sensorName", &name, NULL); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "sensorName"); + if (strcpy_s(config->sensorInfo.sensorName, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { + HDF_LOGE("%s:copy sensorName failed!", __func__); + return HDF_FAILURE; + } + + ret = parser->GetString(infoNode, "vendorName", &name, NULL); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "vendorName"); + if (strcpy_s(config->sensorInfo.vendorName, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { + HDF_LOGE("%s:copy vendorName failed!", __func__); + return HDF_FAILURE; + } + + ret = parser->GetString(infoNode, "firmwareVersion", &name, NULL); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "firmwareVersion"); + if (strcpy_s(config->sensorInfo.firmwareVersion, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { + HDF_LOGE("%s:copy firmwareVersion failed!", __func__); + return HDF_FAILURE; + } + + ret = parser->GetString(infoNode, "hardwareVersion", &name, NULL); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "hardwareVersion"); + if (strcpy_s(config->sensorInfo.hardwareVersion, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { + HDF_LOGE("%s:copy hardwareVersion failed!", __func__); + return HDF_FAILURE; + } + + uint16_t id; + ret = parser->GetUint16(infoNode, "sensorTypeId", &id, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "sensorTypeId"); + config->sensorInfo.sensorTypeId = id; + ret = parser->GetUint16(infoNode, "sensorId", &id, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "sensorId"); + config->sensorInfo.sensorId = id; + + int32_t value; + ret = parser->GetUint32(infoNode, "maxRange", (uint32_t *)&value, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "maxRange"); + config->sensorInfo.maxRange = value; + ret = parser->GetUint32(infoNode, "accuracy", (uint32_t *)&value, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "accuracy"); + config->sensorInfo.accuracy = value; + ret = parser->GetUint32(infoNode, "power", (uint32_t *)&value, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "power"); + config->sensorInfo.power = value; + + return ret; +} + +static int32_t ParseSensorBus(struct DeviceResourceIface *parser, const struct DeviceResourceNode *busNode, + struct SensorCfgData *config) +{ + int32_t ret; + + ret = parser->GetUint8(busNode, "busType", &config->busCfg.busType, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "busType"); + ret = parser->GetUint8(busNode, "regBigEndian", &config->busCfg.regBigEndian, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "regBigEndian"); + + if (config->busCfg.busType == SENSOR_BUS_I2C) { + ret = parser->GetUint16(busNode, "busNum", &config->busCfg.i2cCfg.busNum, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "busNum"); + ret = parser->GetUint16(busNode, "busAddr", &config->busCfg.i2cCfg.devAddr, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "busAddr"); + ret = parser->GetUint16(busNode, "regWidth", &config->busCfg.i2cCfg.regWidth, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "regWidth"); + } else if (config->busCfg.busType == SENSOR_BUS_SPI) { + ret = parser->GetUint32(busNode, "busNum", &config->busCfg.spiCfg.busNum, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "busNum"); + ret = parser->GetUint32(busNode, "busAddr", &config->busCfg.spiCfg.csNum, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "busAddr"); + } + + return HDF_SUCCESS; +} + +static int32_t ParseSensorAttr(struct DeviceResourceIface *parser, const struct DeviceResourceNode *attrNode, + struct SensorCfgData *config) +{ + int32_t ret; + ret = parser->GetString(attrNode, "chipName", &config->sensorAttr.chipName, NULL); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "chipName"); + ret = parser->GetUint16(attrNode, "chipIdRegister", &config->sensorAttr.chipIdReg, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "chipIdRegister"); + ret = parser->GetUint16(attrNode, "chipIdValue", &config->sensorAttr.chipIdValue, 0); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "chipIdValue"); + + return ret; +} + +int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config) +{ + int32_t ret; + struct DeviceResourceIface *parser = NULL; + + CHECK_NULL_PTR_RETURN_VALUE(node, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM); + + parser = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + CHECK_NULL_PTR_RETURN_VALUE(parser, HDF_ERR_INVALID_PARAM); + + config->root = node; + CHECK_NULL_PTR_RETURN_VALUE(parser->GetChildNode, HDF_ERR_INVALID_PARAM); + const struct DeviceResourceNode *infoNode = parser->GetChildNode(node, "accelInfo"); + CHECK_NULL_PTR_RETURN_VALUE(infoNode, HDF_ERR_INVALID_PARAM); + const struct DeviceResourceNode *busNode = parser->GetChildNode(node, "accelBusConfig"); + CHECK_NULL_PTR_RETURN_VALUE(busNode, HDF_ERR_INVALID_PARAM); + const struct DeviceResourceNode *attrNode = parser->GetChildNode(node, "accelAttr"); + CHECK_NULL_PTR_RETURN_VALUE(attrNode, HDF_ERR_INVALID_PARAM); + ret = ParseSensorInfo(parser, infoNode, config); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "accelInfo"); + ret = ParseSensorBus(parser, busNode, config); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "accelBusConfig"); + ret = ParseSensorAttr(parser, attrNode, config); + CHECK_PARSER_RESULT_RETURN_VALUE(ret, "accelAttr"); + + return HDF_SUCCESS; +} diff --git a/model/sensor/driver/include/sensor_common.h b/model/sensor/driver/include/sensor_common.h new file mode 100644 index 00000000..406b856d --- /dev/null +++ b/model/sensor/driver/include/sensor_common.h @@ -0,0 +1,75 @@ +/* + * 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 SENSOR_COMMON_H +#define SENSOR_COMMON_H + +#include "hdf_log.h" +#include "i2c_if.h" +#include "osal_thread.h" +#include "sensor_parser.h" + +#define CHECK_NULL_PTR_RETURN_VALUE(ptr, ret) do { \ + if ((ptr) == NULL) { \ + HDF_LOGE("%s:line %d pointer is null and return ret", __func__, __LINE__); \ + return (ret); \ + } \ +} while (0) + +#define CHECK_NULL_PTR_RETURN(ptr) do { \ + if ((ptr) == NULL) { \ + HDF_LOGE("%s:line %d pointer is null and return", __func__, __LINE__); \ + return; \ + } \ +} while (0) + +#define CHECK_PARSER_RESULT_RETURN_VALUE(ret, str) do { \ + if (ret != HDF_SUCCESS) { \ + HDF_LOGE("%s:line %d %s fail, ret = %d!", __func__, __LINE__, str, ret); \ + return HDF_FAILURE; \ + } \ +} while (0) + +#define SENSOR_DATA_SHIFT_LEFT(d, s) ((d) << (s)) +#define SENSOR_DATA_SHIFT_RIGHT(d, s) ((d) >> (s)) + +#define SENSOR_ADDR_WIDTH_1_BYTE 1 // 8 bit +#define SENSOR_ADDR_WIDTH_2_BYTE 2 // 16 bit +#define SENSOR_ADDR_WIDTH_4_BYTE 4 // 16 bit +#define SENSOR_DATA_WIDTH_8_BIT 8 // 8 bit +#define SENSOR_CONVERT_UNIT 1000 +#define SENSOR_1K_UNIT 1024 +#define SENSOR_SECOND_CONVERT_NANOSECOND (SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT) + +#define MAX_SENSOR_EXIT_THREAD_COUNT 10 +#define MAX_SENSOR_WAIT_THREAD_TIME 100 // 100MS +typedef int (*sensorEntry)(void *); + +enum SensorThreadStatus { + SENSOR_THREAD_NONE = 0, + SENSOR_THREAD_START = 1, + SENSOR_THREAD_RUNNING = 2, + SENSOR_THREAD_STOPPING = 3, + SENSOR_THREAD_STOPPED = 4, + SENSOR_THREAD_DESTROY = 5, + SENSOR_THREAD_STATUS_BUT, +}; + +enum SENSORConfigValueIndex { + SENSOR_ADDR_INDEX, + SENSOR_VALUE_INDEX, + SENSOR_VALUE_BUTT, +}; + +int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen); +int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len); +int32_t SetSensorPinMux(uint32_t regAddr, int32_t regSize, uint32_t regValue); +int32_t CreateSensorThread(struct OsalThread *thread, OsalThreadEntry threadEntry, char *name, void *entryPara); +void DestroySensorThread(struct OsalThread *thread, uint8_t *status); + +#endif /* SENSOR_COMMON_H */ \ 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 new file mode 100644 index 00000000..ef2d3c70 --- /dev/null +++ b/model/sensor/driver/include/sensor_driver_type.h @@ -0,0 +1,102 @@ +/* + * 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 SENSOR_DRIVER_TYPE_H +#define SENSOR_DRIVER_TYPE_H + +#include "hdf_base.h" + +#define SENSOR_INFO_NAME_MAX_LEN 16 + +enum SensorAccuracyMode { + SENSOR_ACCURACY_NO = 0, + SENSOR_ACCURACY_LOW = 1, + SENSOR_ACCURACY_MEDIUM = 2, + SENSOR_ACCURACY_HIGH = 3, + SENSOR_ACCURACY_MAX, +}; + +enum SensorRangeLevel { + SENSOR_RANGE_LEVEL_1 = 0, + SENSOR_RANGE_LEVEL_2 = 1, + SENSOR_RANGE_LEVEL_3 = 2, +}; + +enum SensorWorkMode { + SENSOR_WORK_MODE_DEFAULT = 0, + SENSOR_WORK_MODE_REALTIME = 1, + SENSOR_WORK_MODE_ON_CHANGE = 2, + SENSOR_WORK_MODE_ONE_SHOT = 3, + SENSOR_WORK_MODE_FIFO = 4, + SENSOR_WORK_MODE_MAX, +}; + +enum SensorTag { + 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 */ + SENSOR_TAG_ELECTROCARDIOGRAPH = 4, /**< Electrocardiogram sensor */ + SENSOR_TAG_AMBIENT_LIGHT = 5, /**< Ambient light sensor */ + SENSOR_TAG_MAGNETIC_FIELD = 6, /**< Magnetic field sensor */ + SENSOR_TAG_CAPACITIVE = 7, /**< Capacitance sensor */ + SENSOR_TAG_BAROMETER = 8, /**< Barometric pressure sensor */ + SENSOR_TAG_TEMPERATURE = 9, /**< Temperature sensor */ + SENSOR_TAG_HALL = 10, /**< Hall effect sensor */ + SENSOR_TAG_GESTURE = 11, /**< Gesture sensor */ + SENSOR_TAG_PROXIMITY = 12, /**< Proximity sensor */ + SENSOR_TAG_HUMIDITY = 13, /**< Humidity sensor */ + SENSOR_TAG_PHYSICAL_MAX = 255, /**< Maximum type of a physical sensor */ + SENSOR_TAG_ORIENTATION = 256, /**< Orientation sensor */ + SENSOR_TAG_GRAVITY = 257, /**< Gravity sensor */ + SENSOR_TAG_LINEAR_ACCELERATION = 258, /**< Linear acceleration sensor */ + SENSOR_TAG_ROTATION_VECTOR = 259, /**< Rotation vector sensor */ + SENSOR_TAG_AMBIENT_TEMPERATURE = 260, /**< Ambient temperature sensor */ + SENSOR_TAG_MAGNETIC_FIELD_UNCALIBRATED = 261, /**< Uncalibrated magnetic field sensor */ + SENSOR_TAG_GAME_ROTATION_VECTOR = 262, /**< Game rotation vector sensor */ + SENSOR_TAG_GYROSCOPE_UNCALIBRATED = 263, /**< Uncalibrated gyroscope sensor */ + SENSOR_TAG_SIGNIFICANT_MOTION = 264, /**< Significant motion sensor */ + SENSOR_TAG_PEDOMETER_DETECTION = 265, /**< Pedometer detection sensor */ + SENSOR_TAG_PEDOMETER = 266, /**< Pedometer sensor */ + SENSOR_TAG_GEOMAGNETIC_ROTATION_VECTOR = 277, /**< Geomagnetic rotation vector sensor */ + SENSOR_TAG_HEART_RATE = 278, /**< Heart rate sensor */ + SENSOR_TAG_DEVICE_ORIENTATION = 279, /**< Device orientation sensor */ + SENSOR_TAG_WEAR_DETECTION = 280, /**< Wear detection sensor */ + SENSOR_TAG_ACCELEROMETER_UNCALIBRATED = 281, /**< Uncalibrated acceleration sensor */ + SENSOR_TAG_MAX = 0xFFF, /**< Maximum number of sensor types */ +}; + +/** + * @brief Defines the basic description of a sensor. + * + * The basic description of the sensor includes its vendor, version, type, ID, + * measurement range, accuracy, and power consumption. + */ +struct SensorBasicInfo { + char sensorName[SENSOR_INFO_NAME_MAX_LEN]; /**< Sensor name */ + char vendorName[SENSOR_INFO_NAME_MAX_LEN]; /**< Sensor vendor */ + char firmwareVersion[SENSOR_INFO_NAME_MAX_LEN]; /**< Sensor firmware version */ + char hardwareVersion[SENSOR_INFO_NAME_MAX_LEN]; /**< Sensor hardware version */ + int32_t sensorTypeId; /**< Sensor type ID (described in {@link SensorTypeTag}) */ + int32_t sensorId; /**< Sensor ID, defined by the sensor driver developer */ + int32_t maxRange; /**< Maximum measurement range of the sensor */ + int32_t accuracy; /**< Sensor accuracy */ + int32_t power; /**< Sensor power */ +}; + +struct SensorReportEvent { + int32_t sensorId; /**< Sensor ID */ + int32_t version; /**< Sensor algorithm version */ + int64_t timestamp; /**< Time when sensor data was generated */ + uint32_t option; /**< Sensor data options, including the measurement range and accuracy */ + int32_t mode; /**< Sensor data reporting mode */ + uint8_t *data; /**< Sensor data address */ + uint32_t dataLen; /**< Sensor data length */ +}; + +#endif /* SENSOR_DRIVER_TYPE_H */ diff --git a/readme.md b/readme.md deleted file mode 100755 index 7637b005..00000000 --- a/readme.md +++ /dev/null @@ -1,3 +0,0 @@ -详见:https://gitee.com/openharmony/docs/blob/master/readme/驱动子系统README.md - -see: https://gitee.com/openharmony/docs/blob/master/docs-en/readme/driver-subsystem.md diff --git a/support/platform/include/dmac_core.h b/support/platform/include/dmac_core.h new file mode 100644 index 00000000..4e4eab4a --- /dev/null +++ b/support/platform/include/dmac_core.h @@ -0,0 +1,141 @@ +/* + * 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 DMAC_CORE_H +#define DMAC_CORE_H + +#include "hdf_base.h" +#include "hdf_device.h" +#include "hdf_device_desc.h" +#include "hdf_object.h" +#include "osal_mutex.h" +#include "osal_spinlock.h" +#include "los_event.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +typedef void DmacCallback(void *callbackData, int status); +typedef EVENT_CB_S DmacEvent; + +#define DmaEventInit(event) LOS_EventInit(event) +#define DmaEventSignal(event, bit) LOS_EventWrite(event, bit) +#define DmaEventWait(event, bit, timeout) LOS_EventRead(event, bit, LOS_WAITMODE_OR + LOS_WAITMODE_CLR, timeout) + +/* definition for the return value */ +#define DMAC_ERROR_BASE 0x100 +#define DMAC_CHANNEL_INVALID ((DMAC_ERROR_BASE) + 1) +#define DMAC_TRXFERSIZE_INVALID ((DMAC_ERROR_BASE) + 2) +#define DMAC_SOURCE_ADDRESS_INVALID ((DMAC_ERROR_BASE) + 3) +#define DMAC_DESTINATION_ADDRESS_INVALID ((DMAC_ERROR_BASE) + 4) +#define DMAC_MEMORY_ADDRESS_INVALID ((DMAC_ERROR_BASE) + 5) +#define DMAC_PERIPHERAL_ID_INVALID ((DMAC_ERROR_BASE) + 6) +#define DMAC_DIRECTION_ERROR ((DMAC_ERROR_BASE) + 7) +#define DMAC_TRXFER_ERROR ((DMAC_ERROR_BASE) + 8) +#define DMAC_LLIHEAD_ERROR ((DMAC_ERROR_BASE) + 9) +#define DMAC_SWIDTH_ERROR ((DMAC_ERROR_BASE) + 0xa) +#define DMAC_LLI_ADDRESS_INVALID ((DMAC_ERROR_BASE) + 0xb) +#define DMAC_TRANS_CONTROL_INVALID ((DMAC_ERROR_BASE) + 0xc) +#define DMAC_MEMORY_ALLOCATE_ERROR ((DMAC_ERROR_BASE) + 0xd) +#define DMAC_NOT_FINISHED ((DMAC_ERROR_BASE) + 0xe) +#define DMAC_TIMEOUT ((DMAC_ERROR_BASE) + 0xf) +#define DMAC_CHN_SUCCESS ((DMAC_ERROR_BASE) + 0x10) +#define DMAC_CHN_ERROR ((DMAC_ERROR_BASE) + 0x11) +#define DMAC_CHN_TIMEOUT ((DMAC_ERROR_BASE) + 0x12) +#define DMAC_CHN_ALLOCAT ((DMAC_ERROR_BASE) + 0x13) +#define DMAC_CHN_VACANCY ((DMAC_ERROR_BASE) + 0x14) + +#define DMA_EVENT_WAIT_DEF_TIME ((LOSCFG_BASE_CORE_TICK_PER_SECOND) * 5) +#define DMAC_EVENT_DONE 0x1 +#define DMAC_EVENT_ERROR 0x2 + +#define TRASFER_TYPE_M2M 0x0 +#define TRASFER_TYPE_P2M 0x1 +#define TRASFER_TYPE_M2P 0x2 +#define PERIPHERALID_INVILD 0xfff + +#define DMAC_CHAN_NUM_MAX 100 + +struct DmacMsg { + UINTPTR srcAddr; + UINTPTR destAddr; + unsigned int transferSize; + unsigned int direct; /* 0: mem to mem; 1: periph to mem; 2:mem to periph */ + DmacCallback *cb; + void *para; +}; + +/* structure for LLI */ +struct DmacLli { + /* must be 64Byte aligned */ + long long nextLli; + unsigned int reserved[5]; + unsigned int count; + long long srcAddr; + long long destAddr; + unsigned int config; + unsigned int pad[51]; +}; + +struct DmacChanInfo { + unsigned int channel; + unsigned int status; + unsigned int useStatus; + unsigned int transferType; + unsigned int width; + unsigned int config; + long long lliEnFlag; + DmacEvent waitEvent; + DmacCallback *callback; + void *callbackData; + unsigned int lliCnt; + struct DmacLli *lli; +}; + +struct DmaCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + unsigned int index; + unsigned int irq; + unsigned int phyBase; + char *remapBase; + unsigned int regSize; + unsigned int maxTransSize; + unsigned int channelNum; + OsalSpinlock lock; + struct DmacChanInfo *channelList; + int (*getChanInfo)(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo, unsigned int periphAddr); + int (*dmaChanEnable)(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo); + int (*dmaM2mChanEnable)(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo, + UINTPTR src, UINTPTR dest, unsigned int length); + void (*dmacChanDisable)(struct DmaCntlr *cntlr, unsigned int channel); + void (*dmacCacheInv)(UINTPTR addr, UINTPTR end); + void (*dmacCacheFlush)(UINTPTR addr, UINTPTR end); + void *(*dmacPaddrToVaddr)(long long paddr); + unsigned long (*dmacVaddrToPaddr)(void *vaddr); + unsigned int (*dmacGetChanStatus)(struct DmaCntlr *cntlr, unsigned int chan); + unsigned int (*dmacGetCurrDestAddr)(struct DmaCntlr *cntlr, unsigned int chan); + void *private; +}; + +struct DmaCntlr *DmaCntlrCreate(struct HdfDeviceObject *dev); +void DmaCntlrDestroy(struct DmaCntlr *cntlr); +int32_t DmaCntlrTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg); +int DmacInit(struct DmaCntlr *cntlr); +unsigned int DmaGetCurrChanDestAddr(struct DmaCntlr *cntlr, unsigned int chan); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* DMAC_CORE_H */ diff --git a/support/platform/include/emmc_core.h b/support/platform/include/emmc_core.h new file mode 100644 index 00000000..55f835f2 --- /dev/null +++ b/support/platform/include/emmc_core.h @@ -0,0 +1,126 @@ +/* + * 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 emmc_CORE_H +#define emmc_CORE_H + +#include "emmc_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct EmmcMethod; + +enum EmmcIoCmd { + EMMC_IO_GET_CID = 0, +}; + +struct EmmcConfigData { + uint32_t hostId; +}; + +struct EmmcCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct EmmcConfigData configData; + void *priv; + struct EmmcMethod *method; +}; + +/** + * @brief emmc host device operations. + * These methods need to be filled up by specific paltform. + */ +struct EmmcMethod { + int32_t (*getCid)(struct EmmcCntlr *, uint8_t *, uint32_t); + int32_t (*findHost)(struct EmmcCntlr *, struct EmmcConfigData *); +}; + +int32_t EmmcCntlrFindHost(struct EmmcCntlr *cntlr); + +/** + * @brief Create a new EmmcCntlr struct, and bind it to a HdfDeviceObject. + * + * @param device The HdfDeviceObject of this EmmcCntlr. + * + * @return Retrns the pointer of the EmmcCntlr struct on success; returns NULL otherwise. + * @since 1.0 + */ +struct EmmcCntlr *EmmcCntlrCreateAndBind(struct HdfDeviceObject *device); + +/** + * @brief Destroy a EmmcCntlr struct, you should always destroy it with this function. + * + * @param cntlr Indicates the emmc cntlr device. + * + * @since 1.0 + */ +void EmmcCntlrDestroy(struct EmmcCntlr *cntlr); + +/** + * @brief Fill config data for an EmmcCntlr. + * + * @param device The HdfDeviceObject of this EmmcCntlr. + * @param configData The config data of this EmmcCntlr. + * + * @return Retrns zero on success; returns negative errno otherwise. + * @since 1.0 + */ +int32_t EmmcFillConfigData(struct HdfDeviceObject *device, struct EmmcConfigData *configData); + +/** + * @brief Turn EmmcCntlr to a HdfDeviceObject. + * + * @param cntlr Indicates the emmc cntlr device. + * + * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct HdfDeviceObject *EmmcCntlrToDevice(struct EmmcCntlr *cntlr) +{ + return (cntlr == NULL) ? NULL : cntlr->device; +} + +/** + * @brief Turn HdfDeviceObject to an EmmcCntlr. + * + * @param device Indicates a HdfDeviceObject. + * + * @return Retrns the pointer of the EmmcCntlr on success; returns NULL otherwise. + * @since 1.0 + */ +static inline struct EmmcCntlr *EmmcCntlrFromDevice(struct HdfDeviceObject *device) +{ + return (device == NULL) ? NULL : (struct EmmcCntlr *)device->service; +} + +/** + * @brief Get The CID of EMMC device. + * + * @param cntlr Indicates the emmc cntlr device. + * @param cid Indicates the pointer to the CID to read. + * @param size Indicates the length of the CID. + * + * @return Returns 0 if the operation is successful; returns a negative value if the operation fails. + * + * @since 1.0 + */ +int32_t EmmcCntlrGetCid(struct EmmcCntlr *cntlr, uint8_t *cid, uint32_t size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* EMMC_CORE_H */ diff --git a/support/platform/include/gpio_core.h b/support/platform/include/gpio_core.h old mode 100755 new mode 100644 index 62439e99..6e1a0dc4 --- a/support/platform/include/gpio_core.h +++ b/support/platform/include/gpio_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 GPIO_CORE_H @@ -34,7 +11,9 @@ #include "hdf_base.h" #include "hdf_device_desc.h" +#include "hdf_dlist.h" #include "gpio_if.h" +#include "osal_spinlock.h" #ifdef __cplusplus #if __cplusplus @@ -44,26 +23,65 @@ extern "C" { struct GpioCntlr; struct GpioMethod; +struct GpioInfo; +#define GPIO_NUM_DEFAULT 200 + +/** + * @brief Defines the struct which represent a hardware GPIO controller. + * + * @since 1.0 + */ struct GpioCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; - void *priv; struct GpioMethod *ops; + struct DListHead list; + OsalSpinlock spin; + uint16_t start; + uint16_t count; + struct GpioInfo *ginfos; + void *priv; }; +/** + * @brief Defines the struct which represent a hardware GPIO pin. + * + * @since 1.0 + */ +struct GpioInfo { + GpioIrqFunc irqFunc; + void *irqData; +}; + +/** + * @brief Defines the struct which contains the hooks which a GPIO driver need to implement. + * + * @since 1.0 + */ struct GpioMethod { - int32_t (*request)(struct GpioCntlr *cntlr, uint16_t gpio); - int32_t (*release)(struct GpioCntlr *cntlr, uint16_t gpio); - int32_t (*write)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val); - int32_t (*read)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val); - int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir); - int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir); - int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq); - int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); - int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t gpio); - int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t gpio); - int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t gpio); + /** request exclusive access to an GPIO pin, optional */ + int32_t (*request)(struct GpioCntlr *cntlr, uint16_t local); + /** release exclusive access to an GPIO pin, optional */ + int32_t (*release)(struct GpioCntlr *cntlr, uint16_t local); + /** write the level value into a GPIO pin */ + int32_t (*write)(struct GpioCntlr *cntlr, uint16_t local, uint16_t val); + /** read the level value of a GPIO pin */ + int32_t (*read)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val); + /** set the direction for a GPIO pin */ + int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir); + /** get the direction of a GPIO pin */ + int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir); + /** get the irq number of a GPIO pin, optional */ + int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq); + /** set the ISR function for a GPIO pin */ + int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg); + /** unset the ISR function for a GPIO pin */ + int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t local); + /** enable a GPIO pin interrupt */ + int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t local); + /** disable a GPIO pin interrupt */ + int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t local); }; /** @@ -98,23 +116,32 @@ static inline struct GpioCntlr *GpioCntlrFromDevice(struct HdfDeviceObject *devi return (device == NULL) ? NULL : (struct GpioCntlr *)device->service; } -int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val); +int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t local, uint16_t val); -int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val); +int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val); -int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir); +int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir); -int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir); +int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir); -int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq); +int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq); -int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); +int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg); -int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t gpio); +int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t local); -int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t gpio); +int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t local); -int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t gpio); +int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t local); + +void GpioCntlrIrqCallback(struct GpioCntlr *cntlr, uint16_t local); + +struct GpioCntlr *GpioGetCntlr(uint16_t gpio); + +static inline uint16_t GpioGetLocalNumber(struct GpioCntlr *cntlr, uint16_t gpio) +{ + return (cntlr == NULL) ? gpio : (gpio - cntlr->start); +} #ifdef __cplusplus #if __cplusplus diff --git a/support/platform/include/i2c_core.h b/support/platform/include/i2c_core.h old mode 100755 new mode 100644 index a881b1c1..81208c18 --- a/support/platform/include/i2c_core.h +++ b/support/platform/include/i2c_core.h @@ -1,40 +1,17 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 I2C_CORE_H #define I2C_CORE_H #include "hdf_base.h" -#include "hdf_device_desc.h" #include "i2c_if.h" +#include "osal_atomic.h" #include "osal_mutex.h" #ifdef __cplusplus @@ -43,21 +20,25 @@ extern "C" { #endif #endif /* __cplusplus */ +#define I2C_BUS_MAX 16 + struct I2cCntlr; struct I2cMethod; +struct I2cLockMethod; struct I2cCntlr { - struct IDeviceIoService service; - struct HdfDeviceObject *device; struct OsalMutex lock; + OsalAtomic atom; + void *owner; int16_t busId; void *priv; - struct I2cMethod *ops; + const struct I2cMethod *ops; + const struct I2cLockMethod *lockOps; }; struct I2cMethod { /** - * @brief Execute one or more I2C messages. + * @brief Execute one or more I2C messages, which is implemented by a specific vendor driver. * * @param cntlr Indicates the I2C controller device. * @param msgs Indicates the {@link I2cMsg} message array. @@ -71,6 +52,32 @@ struct I2cMethod { int32_t (*transfer)(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); }; +struct I2cLockMethod { + /** + * @brief Get exclusive access to an I2C controller. + * + * @param cntlr Indicates the I2C controller to access. + * + * @return Returns 0 on success; returns a negative value otherwise. + * @since 1.0 + */ + int32_t (*lock)(struct I2cCntlr *cntlr); + /** + * @brief Release exclusive access to an I2C controller. + * + * @param cntlr Indicates the I2C controller to release. + * + * @since 1.0 + */ + void (*unlock)(struct I2cCntlr *cntlr); +}; + +enum I2cIoCmd { + I2C_IO_TRANSFER = 0, + I2C_IO_OPEN = 1, + I2C_IO_CLOSE = 2, +}; + /** * @brief Bind to a HdfDeviceObject, and do some necessary check * @@ -92,31 +99,35 @@ int32_t I2cCntlrAdd(struct I2cCntlr *cntlr); void I2cCntlrRemove(struct I2cCntlr *cntlr); /** - * @brief Turn I2cCntlr to a HdfDeviceObject. + * @brief Find and return an i2c controller by number, with ref count. * - * @param cntlr Indicates the I2C controller device. + * @param number Indicates the I2C controller to get. * - * @return Retrns the pointer of the HdfDeviceObject on success; returns NULL otherwise. * @since 1.0 */ -static inline struct HdfDeviceObject *I2cCntlrToDevice(struct I2cCntlr *cntlr) -{ - return (cntlr == NULL) ? NULL : cntlr->device; -} +struct I2cCntlr *I2cCntlrGet(int16_t number); /** - * @brief Turn HdfDeviceObject to an I2cCntlr. + * @brief Find and return an i2c controller by number, with ref count. * - * @param device Indicates a HdfDeviceObject. + * @param number Indicates the I2C controller to get. * - * @return Retrns the pointer of the I2cCntlr on success; returns NULL otherwise. * @since 1.0 */ -static inline struct I2cCntlr *I2cCntlrFromDevice(struct HdfDeviceObject *device) -{ - return (device == NULL) ? NULL : (struct I2cCntlr *)device->service; -} +void I2cCntlrPut(struct I2cCntlr *cntlr); +/** + * @brief Execute one or more I2C messages. + * + * @param cntlr Indicates the I2C controller device. + * @param msgs Indicates the {@link I2cMsg} message array. + * @param count Indicates the length of the message array. + * + * @return Returns the number of transferred message structures if the operation is successful; + * returns a negative value otherwise. + * @see I2cMsg + * @since 1.0 + */ int32_t I2cCntlrTransfer(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); #ifdef __cplusplus diff --git a/support/platform/include/mipi_dsi_core.h b/support/platform/include/mipi_dsi_core.h new file mode 100644 index 00000000..268c6d17 --- /dev/null +++ b/support/platform/include/mipi_dsi_core.h @@ -0,0 +1,60 @@ +/* + * 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 MIPI_DSI_CORE_H +#define MIPI_DSI_CORE_H + +#include "osal_mutex.h" +#include "hdf_base.h" +#include "hdf_device.h" +#include "hdf_device_desc.h" +#include "hdf_object.h" +#include "mipi_dsi_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + + +#define MAX_CNTLR_CNT 4 + +struct MipiDsiCntlr { + unsigned int devNo; /* device number */ + enum DsiLane lane; + enum DsiMode mode; + enum DsiBurstMode burstMode; + enum DsiOutFormat format; + struct DsiTimingInfo timing; + unsigned int phyDataRate; /* mbps */ + unsigned int pixelClk; /* KHz */ + int32_t (*setCntlrCfg)(struct MipiDsiCntlr *cntlr); + int32_t (*setCmd)(struct MipiDsiCntlr *cntlr, struct DsiCmdDesc *cmd); + int32_t (*getCmd)(struct MipiDsiCntlr *cntlr, struct DsiCmdDesc *cmd, uint32_t readLen, uint8_t *out); + void (*toHs)(struct MipiDsiCntlr *cntlr); + void (*toLp)(struct MipiDsiCntlr *cntlr); + void (*enterUlps)(struct MipiDsiCntlr *cntlr); + void (*exitUlps)(struct MipiDsiCntlr *cntlr); + int32_t (*powerControl)(struct MipiDsiCntlr *cntlr, uint8_t enable); +}; + +struct MipiDsiHandle { + struct MipiDsiCntlr *cntlr; + struct OsalMutex lock; +}; + +int32_t MipiDsiRegisterCntlr(struct MipiDsiCntlr *); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif diff --git a/support/platform/include/plat_common.h b/support/platform/include/plat_common.h new file mode 100644 index 00000000..e10234ec --- /dev/null +++ b/support/platform/include/plat_common.h @@ -0,0 +1,16 @@ +/* + * 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" + +bool PlatInIrqContext(void); + +#endif diff --git a/support/platform/include/plat_log.h b/support/platform/include/plat_log.h new file mode 100644 index 00000000..4de73d19 --- /dev/null +++ b/support/platform/include/plat_log.h @@ -0,0 +1,20 @@ +/* + * 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_LOG_H +#define PLATFORM_LOG_H + +#include "hdf_log.h" + +#if defined(__LITEOS__) +#define PLAT_LOGV(fmt, arg...) +#else +#define PLAT_LOGV(fmt, arg...) HDF_LOGV(fmt, ##arg) +#endif + +#endif diff --git a/support/platform/include/pwm_core.h b/support/platform/include/pwm_core.h new file mode 100644 index 00000000..7da216c9 --- /dev/null +++ b/support/platform/include/pwm_core.h @@ -0,0 +1,54 @@ +/* + * 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 PWM_CORE_H +#define PWM_CORE_H + +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_spinlock.h" +#include "pwm_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct PwmMethod; +struct PwmDev; + +struct PwmMethod { + int32_t (*setConfig)(struct PwmDev *pwm, struct PwmConfig *config); + int32_t (*open)(struct PwmDev *pwm); + int32_t (*close)(struct PwmDev *pwm); +}; + +struct PwmDev { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct PwmConfig cfg; + struct PwmMethod *method; + bool busy; + uint32_t num; + OsalSpinlock lock; + void *priv; +}; + +void *PwmGetPriv(struct PwmDev *pwm); +int32_t PwmSetPriv(struct PwmDev *pwm, void *priv); +int32_t PwmDeviceAdd(struct HdfDeviceObject *obj, struct PwmDev *pwm); +void PwmDeviceRemove(struct HdfDeviceObject *obj, struct PwmDev *pwm); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* PWM_CORE_H */ diff --git a/support/platform/include/rtc_base.h b/support/platform/include/rtc_base.h old mode 100755 new mode 100644 index 6b720efd..ebc7b1fb --- a/support/platform/include/rtc_base.h +++ b/support/platform/include/rtc_base.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_RTC_BASE_H @@ -91,8 +68,10 @@ uint8_t RtcGetMonthDays(const uint8_t isLeapYear, const uint8_t month); uint8_t RtcIsInvalidDay(const uint8_t day, const uint8_t month, const uint16_t year); uint8_t RtcIsInvalid(const struct RtcTime *time); uint8_t RtcGetWeekDay(const struct RtcTime *time); +#ifndef __KERNEL__ uint64_t RtcTimeToTimestamp(const struct RtcTime *time); void TimestampToRtcTime(struct RtcTime *time, const uint64_t seconds); +#endif #ifdef __cplusplus #if __cplusplus diff --git a/support/platform/include/rtc_core.h b/support/platform/include/rtc_core.h old mode 100755 new mode 100644 index 7545a22e..6ca9d7c9 --- a/support/platform/include/rtc_core.h +++ b/support/platform/include/rtc_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 RTC_CORE_H diff --git a/support/platform/include/sdio_core.h b/support/platform/include/sdio_core.h old mode 100755 new mode 100644 index d5039892..92a8d7cb --- a/support/platform/include/sdio_core.h +++ b/support/platform/include/sdio_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 SDIO_CORE_H diff --git a/support/platform/include/spi_core.h b/support/platform/include/spi_core.h old mode 100755 new mode 100644 index a3051809..0e002101 --- a/support/platform/include/spi_core.h +++ b/support/platform/include/spi_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 SPI_CORE_H @@ -45,26 +22,28 @@ struct SpiCntlrMethod { int32_t (*GetCfg)(struct SpiCntlr *, struct SpiCfg *); int32_t (*SetCfg)(struct SpiCntlr *, struct SpiCfg *); int32_t (*Transfer)(struct SpiCntlr *, struct SpiMsg *, uint32_t); + int32_t (*Open)(struct SpiCntlr *); + int32_t (*Close)(struct SpiCntlr *); }; struct SpiCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; uint32_t busNum; + uint32_t numCs; uint32_t curCs; struct OsalMutex lock; struct SpiCntlrMethod *method; + struct DListHead list; void *priv; }; struct SpiDev { struct SpiCntlr *cntlr; struct DListHead list; + struct SpiCfg cfg; uint32_t csNum; - uint32_t maxSpeedHz; - uint16_t mode; - uint8_t bitsPerWord; - uint8_t transferMode; + void *priv; }; struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device); @@ -99,5 +78,7 @@ static inline struct SpiCntlr *SpiCntlrFromDevice(struct HdfDeviceObject *device int32_t SpiCntlrTransfer(struct SpiCntlr *, uint32_t, struct SpiMsg *, uint32_t); int32_t SpiCntlrSetCfg(struct SpiCntlr *, uint32_t, struct SpiCfg *); int32_t SpiCntlrGetCfg(struct SpiCntlr *, uint32_t, struct SpiCfg *); +int32_t SpiCntlrOpen(struct SpiCntlr *, uint32_t); +int32_t SpiCntlrClose(struct SpiCntlr *, uint32_t); #endif /* SPI_CORE_H */ diff --git a/support/platform/include/uart_core.h b/support/platform/include/uart_core.h old mode 100755 new mode 100644 index 10246b32..2757d759 --- a/support/platform/include/uart_core.h +++ b/support/platform/include/uart_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 UART_CORE_H @@ -34,6 +11,7 @@ #include "hdf_base.h" #include "hdf_device_desc.h" +#include "osal_atomic.h" #include "uart_if.h" #ifdef __cplusplus @@ -49,6 +27,7 @@ struct UartHost { struct IDeviceIoService service; struct HdfDeviceObject *device; uint32_t num; + OsalAtomic atom; void *priv; struct UartHostMethod *method; }; @@ -94,27 +73,9 @@ static inline struct UartHost *UartHostFromDevice(struct HdfDeviceObject *device return (device == NULL) ? NULL : (struct UartHost *)device->service; } -static inline int32_t UartHostInit(struct UartHost *host) -{ - if (host == NULL || host->method == NULL) { - return HDF_ERR_INVALID_PARAM; - } - if (host->method->Init != NULL) { - return host->method->Init(host); - } - return HDF_SUCCESS; -} +int32_t UartHostInit(struct UartHost *host); -static inline int32_t UartHostDeinit(struct UartHost *host) -{ - if (host == NULL || host->method == NULL) { - return HDF_ERR_INVALID_PARAM; - } - if (host->method->Deinit != NULL) { - return host->method->Deinit(host); - } - return HDF_SUCCESS; -} +int32_t UartHostDeinit(struct UartHost *host); static inline int32_t UartHostRead(struct UartHost *host, uint8_t *data, uint32_t size) { diff --git a/support/platform/include/watchdog_core.h b/support/platform/include/watchdog_core.h old mode 100755 new mode 100644 index 2450acca..43bb1de6 --- a/support/platform/include/watchdog_core.h +++ b/support/platform/include/watchdog_core.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 WATCHDOG_CORE_H @@ -61,6 +38,8 @@ struct WatchdogMethod { int32_t (*start)(struct WatchdogCntlr *wdt); int32_t (*stop)(struct WatchdogCntlr *wdt); int32_t (*feed)(struct WatchdogCntlr *wdt); + int32_t (*getPriv)(struct WatchdogCntlr *wdt); + void (*releasePriv)(struct WatchdogCntlr *wdt); }; /** @@ -121,6 +100,9 @@ int32_t WatchdogCntlrGetTimeout(struct WatchdogCntlr *cntlr, uint32_t *seconds); int32_t WatchdogCntlrFeed(struct WatchdogCntlr *cntlr); +void WatchdogGetPrivData(struct WatchdogCntlr *cntlr); + +void WatchdogReleasePriv(struct WatchdogCntlr *cntlr); #ifdef __cplusplus #if __cplusplus diff --git a/support/platform/src/dmac_core.c b/support/platform/src/dmac_core.c new file mode 100644 index 00000000..320fcf5c --- /dev/null +++ b/support/platform/src/dmac_core.c @@ -0,0 +1,484 @@ +/* + * 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_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 + +static int DmacCheck(struct DmaCntlr *cntlr) +{ + if (cntlr == NULL || + cntlr->channelNum == 0 || + cntlr->dmacGetChanStatus == NULL || + cntlr->dmacCacheFlush == NULL || + cntlr->dmacCacheInv == NULL || + cntlr->dmaM2mChanEnable == NULL || + cntlr->dmacPaddrToVaddr == NULL || + cntlr->dmaChanEnable == NULL || + cntlr->dmacVaddrToPaddr == NULL || + cntlr->getChanInfo == NULL || + cntlr->dmacChanDisable == NULL || + cntlr->dmacGetCurrDestAddr == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +struct DmaCntlr *DmaCntlrCreate(struct HdfDeviceObject *device) +{ + struct DmaCntlr *cntlr = NULL; + + if (device == NULL) { + return NULL; + } + cntlr = (struct DmaCntlr *)OsalMemCalloc(sizeof(struct DmaCntlr)); + if (cntlr == NULL) { + HDF_LOGE("service malloc fail!\n"); + return NULL; + } + cntlr->device = device; + return cntlr; +} + +static void DmacFreeLli(struct DmacChanInfo *chanInfo) +{ + if (chanInfo->lli != NULL) { + OsalMemFree(chanInfo->lli); + chanInfo->lli = NULL; + chanInfo->lliCnt = 0; + } +} + +/* + * If private is allocated, release private before calling this function + */ +void DmaCntlrDestroy(struct DmaCntlr *cntlr) +{ + int i; + + if (cntlr == NULL || cntlr->channelNum > DMAC_CHAN_NUM_MAX) { + HDF_LOGE("%s: cntlr null or channel invalid!", __func__); + return; + } + if (cntlr->channelList != NULL) { + for (i = 0; i < cntlr->channelNum; i++) { + DmacFreeLli(&(cntlr->channelList[i])); + } + OsalMemFree(cntlr->channelList); + cntlr->channelList = NULL; + cntlr->channelNum = 0; + } + /* Private is released by the caller */ + cntlr->private = NULL; + OsalMemFree(cntlr); +} + +static void DmacEventCallback(struct DmacChanInfo *chanInfo) +{ + if (chanInfo->status == DMAC_CHN_ERROR) { + DmaEventSignal(&chanInfo->waitEvent, DMAC_EVENT_ERROR); + } else { + DmaEventSignal(&chanInfo->waitEvent, DMAC_EVENT_DONE); + } +} + +static void DmacCallbackHandle(struct DmacChanInfo *chanInfo) +{ + if (chanInfo->transferType == TRASFER_TYPE_M2M) { + DmacEventCallback(chanInfo); + return; + } + if (chanInfo->callback != NULL) { + chanInfo->callback(chanInfo->callbackData, chanInfo->status); + } +} + +static int DmacWaitM2mSendComplete(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo) +{ + unsigned int ret; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + ret = DmaEventWait(&chanInfo->waitEvent, DMAC_EVENT_DONE | DMAC_EVENT_ERROR, DMA_EVENT_WAIT_DEF_TIME); + if (ret == DMAC_EVENT_ERROR) { + HDF_LOGE("wait event error!"); + return DMAC_CHN_ERROR; + } else if (ret == LOS_ERRNO_EVENT_READ_TIMEOUT) { + HDF_LOGE("wait event timeout!"); + return DMAC_CHN_TIMEOUT; + } + + cntlr->dmacChanDisable(cntlr, chanInfo->channel); + HDF_LOGD("event finish!"); + return DMAC_CHN_SUCCESS; +} + +static int DmacAllocateChannel(struct DmaCntlr *cntlr) +{ + unsigned int flags; + int i; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + OsalSpinLockIrqSave(&cntlr->lock, &flags); + for (i = 0; i < cntlr->channelNum; i++) { + if (cntlr->channelList[i].useStatus == DMAC_CHN_VACANCY) { + cntlr->channelList[i].useStatus = DMAC_CHN_ALLOCAT; + OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return i; + } + } + OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); + return HDF_FAILURE; +} + +static void DmacFreeChannel(struct DmaCntlr *cntlr, unsigned int channel) +{ + uint32_t flags; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return; + } + + OsalSpinLockIrqSave(&cntlr->lock, &flags); + cntlr->channelList[channel].useStatus = DMAC_CHN_VACANCY; + OsalSpinUnlockIrqRestore(&cntlr->lock, &flags); +} + +static struct DmacChanInfo *DmacRequestChannel(struct DmaCntlr *cntlr, + int type, unsigned int periphAddr) +{ + int ret; + struct DmacChanInfo *chanInfo = NULL; + int chan; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return NULL; + } + + chan = DmacAllocateChannel(cntlr); + if (chan < 0) { + HDF_LOGE("%s: getChannel is NULL", __func__); + return NULL; + } + chanInfo = &(cntlr->channelList[chan]); + chanInfo->channel = (unsigned int)chan; + chanInfo->transferType = type; + ret = cntlr->getChanInfo(cntlr, chanInfo, periphAddr); + if (ret < 0) { + DmacFreeChannel(cntlr, chan); + 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", + ret, chanInfo->transferType, chanInfo->width, chanInfo->config, chanInfo->lliEnFlag); + return chanInfo; +} + +static int DmacFillLli(struct DmaCntlr *cntlr, struct DmacChanInfo *chanInfo, + UINTPTR srcaddr, UINTPTR dstaddr, unsigned int length) +{ + unsigned int i; + struct DmacLli *plli = NULL; + unsigned int lliNum; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + plli = chanInfo->lli; + if (plli == NULL) { + HDF_LOGE("lli is NULL!\n"); + return HDF_FAILURE; + } + lliNum = chanInfo->lliCnt; + for (i = 0; i < lliNum; i++) { + plli->nextLli = (long long)cntlr->dmacVaddrToPaddr((void *)plli) + (long long)(i + 1) * sizeof(struct DmacLli); + if (i < lliNum - 1) { + plli->nextLli += chanInfo->lliEnFlag; + plli->count = cntlr->maxTransSize; + } else { + plli->nextLli = 0; + plli->count = (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) { + srcaddr += plli->count; + } + plli++; + } + 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)); + return HDF_SUCCESS; +} + +int DmacAllocLli(struct DmacChanInfo *chanInfo, unsigned int length, unsigned int maxSize) +{ + unsigned int lliNum; + unsigned int allocLength; + unsigned long *allocAddr = NULL; + + if (maxSize == 0 || chanInfo == NULL) { + return HDF_FAILURE; + } + lliNum = length / maxSize; + if ((length % maxSize) > 0) { + lliNum++; + } + if (lliNum > 2048) { /* 2048: lliNum is not more than 2048 */ + HDF_LOGE("lliNum %u is bigger than 2048", lliNum); + return HDF_FAILURE; + } + allocLength = lliNum * sizeof(struct DmacLli); + allocLength = ALIGN(allocLength, CACHE_ALIGNED_SIZE); + allocAddr = (unsigned long *)OsalMemAllocAlign(DMA_ALIGN_SIZE, allocLength); + if (allocAddr == NULL) { + HDF_LOGE("can't malloc llimem for dma!\n "); + return HDF_FAILURE; + } + if (memset_s(allocAddr, allocLength, 0, allocLength) != EOK) { + HDF_LOGE("memset_s fail"); + OsalMemFree(allocAddr); + return HDF_FAILURE; + } + + chanInfo->lliCnt = lliNum; + chanInfo->lli = (struct DmacLli *)allocAddr; + return HDF_SUCCESS; +} + +static int32_t DmacPeriphTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg, unsigned int periphAddr) +{ + int ret; + struct DmacChanInfo *chanInfo = NULL; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + chanInfo = DmacRequestChannel(cntlr, msg->direct, periphAddr); + if (chanInfo == NULL) { + HDF_LOGE("allocate dma channel fail"); + return HDF_FAILURE; + } + chanInfo->callbackData = msg->para; + chanInfo->callback = (DmacCallback *)msg->cb; + ret = DmacAllocLli(chanInfo, msg->transferSize, cntlr->maxTransSize); + if (ret != HDF_SUCCESS) { + HDF_LOGE("malloc dmalli space failed"); + DmacFreeChannel(cntlr, chanInfo->channel); + return HDF_FAILURE; + } + ret = DmacFillLli(cntlr, chanInfo, msg->srcAddr, msg->destAddr, msg->transferSize); + if (ret != HDF_SUCCESS) { + HDF_LOGE("build edmalli failed"); + DmacFreeLli(chanInfo); + DmacFreeChannel(cntlr, chanInfo->channel); + return HDF_FAILURE; + } + ret = cntlr->dmaChanEnable(cntlr, chanInfo); + if (ret != HDF_SUCCESS) { + HDF_LOGE("start edma failed!"); + DmacFreeLli(chanInfo); + DmacFreeChannel(cntlr, chanInfo->channel); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int DmacM2mTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg) +{ + struct DmacChanInfo *chanInfo = NULL; + unsigned int leftSize; + unsigned int dmaCount = 0; + unsigned int dmaSize; + int ret; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + chanInfo = DmacRequestChannel(cntlr, TRASFER_TYPE_M2M, PERIPHERALID_INVILD); + if (chanInfo == NULL) { + HDF_LOGE("allocate channel fail\n"); + return -1; + } + chanInfo->callback = msg->cb; + chanInfo->callbackData = msg->para; + cntlr->dmacCacheFlush((UINTPTR)msg->srcAddr, (UINTPTR)(msg->srcAddr + msg->transferSize)); + cntlr->dmacCacheInv((UINTPTR)msg->destAddr, (UINTPTR)(msg->destAddr + msg->transferSize)); + leftSize = msg->transferSize; + while (leftSize > 0) { + if (leftSize >= cntlr->maxTransSize) { + dmaSize = cntlr->maxTransSize; + } else { + dmaSize = leftSize; + } + ret = cntlr->dmaM2mChanEnable(cntlr, chanInfo, msg->srcAddr + dmaCount * cntlr->maxTransSize, + msg->destAddr + dmaCount * cntlr->maxTransSize, dmaSize); + if (ret != 0) { + HDF_LOGE("HiedmacStartM2m error"); + DmacFreeChannel(cntlr, chanInfo->channel); + if (chanInfo->callback != NULL) { + chanInfo->callback(chanInfo->callbackData, DMAC_CHN_ERROR); + } + return HDF_FAILURE; + } + ret = DmacWaitM2mSendComplete(cntlr, chanInfo); + if (ret != DMAC_CHN_SUCCESS) { + HDF_LOGE("dma transfer error"); + DmacFreeChannel(cntlr, chanInfo->channel); + if (chanInfo->callback != NULL) { + chanInfo->callback(chanInfo->callbackData, ret); + } + return HDF_FAILURE; + } + if (dmaSize == 0) { + return HDF_FAILURE; + } + leftSize -= dmaSize; + dmaCount++; + } + DmacFreeChannel(cntlr, chanInfo->channel); + if (chanInfo->callback != NULL) { + chanInfo->callback(chanInfo->callbackData, DMAC_CHN_SUCCESS); + } + return HDF_SUCCESS; +} + +int32_t DmaCntlrTransfer(struct DmaCntlr *cntlr, struct DmacMsg *msg) +{ + unsigned int periphAddr; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + if (msg == NULL) { + return HDF_FAILURE; + } + if (msg->direct == TRASFER_TYPE_P2M) { + periphAddr = msg->srcAddr; + cntlr->dmacCacheInv((UINTPTR)cntlr->dmacPaddrToVaddr((paddr_t)msg->destAddr), + (UINTPTR)cntlr->dmacPaddrToVaddr((paddr_t)msg->destAddr) + msg->transferSize); + } else if (msg->direct == TRASFER_TYPE_M2P) { + periphAddr = msg->destAddr; + cntlr->dmacCacheFlush((UINTPTR)cntlr->dmacPaddrToVaddr((paddr_t)msg->srcAddr), + (UINTPTR)cntlr->dmacPaddrToVaddr((paddr_t)msg->srcAddr) + msg->transferSize); + } else if (msg->direct == TRASFER_TYPE_M2M) { + return DmacM2mTransfer(cntlr, msg); + } else { + HDF_LOGE("%s: invalid direct %d", __func__, msg->direct); + return HDF_FAILURE; + } + return DmacPeriphTransfer(cntlr, msg, periphAddr); +} + +unsigned int DmaGetCurrChanDestAddr(struct DmaCntlr *cntlr, unsigned int chan) +{ + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + return cntlr->dmacGetCurrDestAddr(cntlr, chan); +} + +static uint32_t DmacIsr(int irq, void *dev) +{ + struct DmaCntlr *cntlr = (struct DmaCntlr *)dev; + unsigned int channelStatus; + unsigned int i; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + + if (irq != cntlr->irq || cntlr->channelNum > DMAC_CHAN_NUM_MAX) { + HDF_LOGE("%s: cntlr parm err! irq:%d, channel:%u", + __func__, cntlr->irq, cntlr->channelNum); + return HDF_SUCCESS; + } + for (i = 0; i < cntlr->channelNum; i++) { + channelStatus = cntlr->dmacGetChanStatus(cntlr, i); + if (channelStatus == DMAC_CHN_SUCCESS || channelStatus == DMAC_CHN_ERROR) { + cntlr->channelList[i].status = channelStatus; + DmacCallbackHandle(&(cntlr->channelList[i])); + DmacFreeChannel(cntlr, cntlr->channelList[i].channel); + } + } + return HDF_SUCCESS; +} + +int DmacInit(struct DmaCntlr *cntlr) +{ + int i; + int ret; + + if (DmacCheck(cntlr) != HDF_SUCCESS) { + HDF_LOGE("check fail"); + return HDF_FAILURE; + } + if (cntlr->channelNum > DMAC_CHAN_NUM_MAX) { + HDF_LOGE("%s: invalid channel:%d", __func__, cntlr->channelNum); + return HDF_FAILURE; + } + cntlr->remapBase = (char *)OsalIoRemap((unsigned long)cntlr->phyBase, (unsigned long)cntlr->regSize); + OsalSpinInit(&cntlr->lock); + cntlr->channelList = (struct DmacChanInfo *)OsalMemCalloc(sizeof(struct DmacChanInfo) * cntlr->channelNum); + if (cntlr->channelList == NULL) { + HDF_LOGE("channel list malloc fail"); + OsalIoUnmap((void *)cntlr->remapBase); + return HDF_FAILURE; + } + for (i = 0; i < cntlr->channelNum; i++) { + cntlr->dmacChanDisable(cntlr, i); + DmaEventInit(&(cntlr->channelList[i].waitEvent)); + cntlr->channelList[i].useStatus = DMAC_CHN_VACANCY; + } + 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); + OsalMemFree(cntlr->channelList); + cntlr->channelList = NULL; + OsalIoUnmap((void *)cntlr->remapBase); + } + return ret; +} + diff --git a/support/platform/src/emmc_core.c b/support/platform/src/emmc_core.c new file mode 100644 index 00000000..b30cc433 --- /dev/null +++ b/support/platform/src/emmc_core.c @@ -0,0 +1,165 @@ +/* + * 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 "emmc_core.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG emmc_core_c + +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!"); + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->method->findHost(cntlr, &(cntlr->configData)) != HDF_SUCCESS) { + HDF_LOGE("EmmcCntlrFindHost: findHost fail!"); + return HDF_ERR_INVALID_OBJECT; + } + return HDF_SUCCESS; +} + +int32_t EmmcCntlrGetCid(struct EmmcCntlr *cntlr, uint8_t *cid, uint32_t size) +{ + if (cntlr == NULL) { + HDF_LOGE("EmmcCntlrGetCid: cntlr is null"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->method == NULL || cntlr->method->getCid == NULL) { + HDF_LOGE("EmmcCntlrGetCid: ops or getCid is null"); + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->method->getCid(cntlr, cid, 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!"); + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t EmmcGetCidDispatch(struct EmmcCntlr *cntlr, struct HdfSBuf *reply) +{ + int32_t ret; + uint8_t cid[EMMC_CID_LEN] = {0}; + + ret = EmmcCntlrGetCid(cntlr, cid, EMMC_CID_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("EmmcGetCidDispatch: EmmcCntlrGetCid fail!"); + return ret; + } + return EmmcGetCidWriteBackReply(reply, cid, EMMC_CID_LEN); +} + +static int32_t EmmcIoDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + struct EmmcCntlr *cntlr = NULL; + (void)data; + + if (client == NULL || client->device == NULL) { + HDF_LOGE("EmmcIoDispatch: client or client->device is NULL"); + return HDF_ERR_INVALID_OBJECT; + } + + if (reply == 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"); + return HDF_ERR_INVALID_OBJECT; + } + if (cntlr->priv == NULL) { + if (EmmcCntlrFindHost(cntlr) != HDF_SUCCESS) { + HDF_LOGE("EmmcIoDispatch: find host fail!"); + return HDF_ERR_INVALID_OBJECT; + } + } + + switch (cmd) { + case EMMC_IO_GET_CID: + ret = EmmcGetCidDispatch(cntlr, reply); + break; + default: + ret = HDF_ERR_NOT_SUPPORT; + break; + } + + return ret; +} + +struct EmmcCntlr *EmmcCntlrCreateAndBind(struct HdfDeviceObject *device) +{ + struct EmmcCntlr *cntlr = NULL; + + if (device == NULL) { + HDF_LOGE("EmmcCntlrCreateAndBind: device is NULL!"); + return NULL; + } + + cntlr = (struct EmmcCntlr *)OsalMemCalloc(sizeof(*cntlr)); + if (cntlr == NULL) { + HDF_LOGE("EmmcCntlrCreateAndBind: malloc host fail!"); + return NULL; + } + cntlr->device = device; + device->service = &cntlr->service; + cntlr->device->service->Dispatch = EmmcIoDispatch; + return cntlr; +} + +void EmmcCntlrDestroy(struct EmmcCntlr *cntlr) +{ + if (cntlr != NULL) { + cntlr->device = NULL; + cntlr->priv = NULL; + cntlr->method = NULL; + OsalMemFree(cntlr); + } +} + +int32_t EmmcFillConfigData(struct HdfDeviceObject *device, struct EmmcConfigData *configData) +{ + const struct DeviceResourceNode *node = NULL; + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + + if (device == NULL || configData == NULL) { + HDF_LOGE("EmmcFillConfigData: input para is NULL."); + return HDF_FAILURE; + } + + node = device->property; + if (node == 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!"); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "hostId", &(configData->hostId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("EmmcFillConfigData: read funcNum fail!"); + return ret; + } + + HDF_LOGD("EmmcFillConfigData: Success! hostId = %d.", configData->hostId); + return HDF_SUCCESS; +} diff --git a/support/platform/src/emmc_if.c b/support/platform/src/emmc_if.c new file mode 100644 index 00000000..1010af75 --- /dev/null +++ b/support/platform/src/emmc_if.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 +#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" +#endif +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" + +#define HDF_LOG_TAG emmc_if_c + +#define EMMC_NAME_LEN 32 + +static void *EmmcCntlrObjGetByNumber(int16_t busNum) +{ + void *object = NULL; + char *serviceName = NULL; + + if (busNum < 0) { + HDF_LOGE("EmmcCntlrObjGetByNumber: invalid bus:%d", busNum); + return NULL; + } + serviceName = OsalMemCalloc(EMMC_NAME_LEN + 1); + if (serviceName == NULL) { + HDF_LOGE("EmmcCntlrObjGetByNumber: OsalMemCalloc fail!"); + return NULL; + } + if (snprintf_s(serviceName, EMMC_NAME_LEN + 1, EMMC_NAME_LEN, + "HDF_PLATFORM_EMMC_%d", busNum) < 0) { + HDF_LOGE("EmmcCntlrObjGetByNumber: format service name fail!"); + goto __ERR; + } + +#ifdef __USER__ + object = (void *)HdfIoServiceBind(serviceName); + HDF_LOGD("EmmcCntlrObjGetByNumber: user status"); +#else + object = (void *)DevSvcManagerClntGetService(serviceName); + HDF_LOGD("EmmcCntlrObjGetByNumber: kernel status"); +#endif + if (object == NULL) { + HDF_LOGE("EmmcCntlrObjGetByNumber: get service fail!"); + goto __ERR; + } + +#ifndef __USER__ + struct EmmcCntlr *cntlr = (struct EmmcCntlr *)object; + if (cntlr->priv == NULL && EmmcCntlrFindHost(cntlr) != HDF_SUCCESS) { + HDF_LOGE("EmmcCntlrObjGetByNumber: EmmcCntlrFindHost fail!"); + goto __ERR; + } +#endif + + HDF_LOGD("EmmcCntlrObjGetByNumber: success"); + OsalMemFree(serviceName); + return object; +__ERR: + OsalMemFree(serviceName); + return NULL; +} + +DevHandle EmmcOpen(int16_t busNum) +{ + return (DevHandle)EmmcCntlrObjGetByNumber(busNum); +} + +void EmmcClose(DevHandle handle) +{ + if (handle != NULL) { +#ifdef __USER__ + HdfIoServiceRecycle((struct HdfIoService *)handle); +#endif + } +} + +#ifdef __USER__ +enum EmmcIoCmd { + EMMC_IO_GET_CID = 0, +}; + +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; + } + HDF_LOGD("EmmcGetCidReadReplyData: success"); + 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_IO_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; +} +#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 + return EmmcCntlrGetCid((struct EmmcCntlr *)handle, cid, size); +#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/gpio_core.c b/support/platform/src/gpio_core.c old mode 100755 new mode 100644 index e060637f..eaca5907 --- a/support/platform/src/gpio_core.c +++ b/support/platform/src/gpio_core.c @@ -1,49 +1,65 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "gpio_core.h" -#include #include "hdf_log.h" #include "osal_mem.h" +#include "osal_sem.h" +#include "osal_thread.h" +#include "plat_log.h" +#include "securec.h" #define HDF_LOG_TAG gpio_core -static struct GpioCntlr *g_cntlr; +#define MAX_CNT_PER_CNTLR 1024 +#define GPIO_IRQ_STACK_SIZE 10000 +#define GPIO_IRQ_THREAD_NAME_LEN 32 + +struct GpioIrqBridge { + uint16_t local; + GpioIrqFunc func; + void *data; + struct OsalThread thread; + char name[GPIO_IRQ_THREAD_NAME_LEN]; + OsalSpinlock spin; + struct OsalSem sem; + struct GpioCntlr *cntlr; + bool stop; +}; + +static struct DListHead g_cntlrList; +static OsalSpinlock g_listLock; +static uint32_t g_irqFlags; + +static struct DListHead *GpioCntlrListGet(void) +{ + static struct DListHead *list = NULL; + uint32_t flags; + + if (list == NULL) { + list = &g_cntlrList; + DListHeadInit(list); + OsalSpinInit(&g_listLock); + } + while (OsalSpinLockIrqSave(&g_listLock, &flags) != HDF_SUCCESS); + g_irqFlags = flags; + return list; +} + +static void GpioCntlrListPut(void) +{ + (void)OsalSpinUnlockIrqRestore(&g_listLock, &g_irqFlags); +} int32_t GpioCntlrAdd(struct GpioCntlr *cntlr) { - if (g_cntlr != NULL) { - HDF_LOGE("GpioCntlrAdd: already has a gpio controller!"); - return HDF_ERR_NOT_SUPPORT; - } + struct GpioCntlr *last = NULL; + struct DListHead *list = NULL; if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -59,8 +75,32 @@ int32_t GpioCntlrAdd(struct GpioCntlr *cntlr) return HDF_ERR_INVALID_OBJECT; } - cntlr->device->service = &cntlr->service; - g_cntlr = cntlr; + if (cntlr->count >= MAX_CNT_PER_CNTLR) { + HDF_LOGE("GpioCntlrAdd: invalid gpio count:%u", cntlr->count); + return HDF_ERR_INVALID_PARAM; + } + + if (cntlr->ginfos == NULL) { + cntlr->ginfos = OsalMemCalloc(sizeof(*cntlr->ginfos) * cntlr->count); + if (cntlr->ginfos == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + } + + OsalSpinInit(&cntlr->spin); + + list = GpioCntlrListGet(); + if (DListIsEmpty(list)) { + cntlr->start = 0; + } else { + last = DLIST_LAST_ENTRY(list, struct GpioCntlr, list); + cntlr->start = last->start + last->count; + } + DListHeadInit(&cntlr->list); + DListInsertTail(&cntlr->list, list); + GpioCntlrListPut(); + HDF_LOGI("GpioCntlrAdd: start:%u count:%u", cntlr->start, cntlr->count); + return HDF_SUCCESS; } @@ -76,10 +116,35 @@ void GpioCntlrRemove(struct GpioCntlr *cntlr) } cntlr->device->service = NULL; - g_cntlr = NULL; + (void)GpioCntlrListGet(); + DListRemove(&cntlr->list); + GpioCntlrListPut(); + if (cntlr->ginfos != NULL) { + OsalMemFree(cntlr->ginfos); + cntlr->ginfos = NULL; + } + (void)OsalSpinDestroy(&cntlr->spin); } -int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val) +struct GpioCntlr *GpioGetCntlr(uint16_t gpio) +{ + struct DListHead *list = NULL; + struct GpioCntlr *cntlr = NULL; + struct GpioCntlr *tmp = NULL; + + list = GpioCntlrListGet(); + DLIST_FOR_EACH_ENTRY_SAFE(cntlr, tmp, list, struct GpioCntlr, list) { + if (gpio >= cntlr->start && gpio <= (cntlr->start + cntlr->count)) { + GpioCntlrListPut(); + return cntlr; + } + } + GpioCntlrListPut(); + HDF_LOGE("GpioGetCntlr: gpio %u not in any controllers!", gpio); + return NULL; +} + +int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t local, uint16_t val) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -87,10 +152,10 @@ int32_t GpioCntlrWrite(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t val) if (cntlr->ops == NULL || cntlr->ops->write == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->write(cntlr, gpio, val); + return cntlr->ops->write(cntlr, local, val); } -int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val) +int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -101,10 +166,10 @@ int32_t GpioCntlrRead(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *val) if (val == NULL) { return HDF_ERR_INVALID_PARAM; } - return cntlr->ops->read(cntlr, gpio, val); + return cntlr->ops->read(cntlr, local, val); } -int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir) +int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -112,10 +177,10 @@ int32_t GpioCntlrSetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t dir) if (cntlr->ops == NULL || cntlr->ops->setDir == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->setDir(cntlr, gpio, dir); + return cntlr->ops->setDir(cntlr, local, dir); } -int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir) +int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -126,10 +191,10 @@ int32_t GpioCntlrGetDir(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *dir) if (dir == NULL) { return HDF_ERR_INVALID_PARAM; } - return cntlr->ops->getDir(cntlr, gpio, dir); + return cntlr->ops->getDir(cntlr, local, dir); } -int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq) +int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -137,32 +202,236 @@ int32_t GpioCntlrToIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t *irq) if (cntlr->ops == NULL || cntlr->ops->toIrq == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->toIrq(cntlr, gpio, irq); + return cntlr->ops->toIrq(cntlr, local, irq); } -int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg) +static int32_t GpioIrqBridgeFunc(uint16_t local, void *data) { - if (cntlr == NULL) { + uint32_t flags; + struct GpioIrqBridge *bridge = (struct GpioIrqBridge *)data; + + (void)local; + (void)OsalSpinLockIrqSave(&bridge->spin, &flags); + if (bridge->stop == false) { + (void)OsalSemPost(&bridge->sem); + } + (void)OsalSpinUnlockIrqRestore(&bridge->spin, &flags); + return HDF_SUCCESS; +} + +#ifndef __KERNEL__ +static int GpioIrqThreadWorker(void *data) +{ + int32_t ret; + struct GpioIrqBridge *bridge = (struct GpioIrqBridge *)data; + + while (true) { + ret = OsalSemWait(&bridge->sem, HDF_WAIT_FOREVER); + if (ret != HDF_SUCCESS) { + continue; + } + if (bridge->stop == true) { + break; + } + PLAT_LOGV("GpioIrqThreadWorker: enter! gpio:%u-%u", bridge->cntlr->start, bridge->local); + (void)bridge->func(bridge->local, bridge->data); + } + /* it's the bridge struct we create before, so release it ourself */ + (void)OsalSemDestroy(&bridge->sem); + (void)OsalSpinDestroy(&bridge->spin); + OsalMemFree(bridge); + HDF_LOGI("GpioIrqThreadWorker: normal exit!"); + return HDF_SUCCESS; +} + +static struct GpioIrqBridge *GpioIrqBridgeCreate(struct GpioCntlr *cntlr, + uint16_t local, GpioIrqFunc func, void *arg) +{ + int32_t ret; + struct OsalThreadParam cfg; + struct GpioIrqBridge *bridge = NULL; + + bridge = (struct GpioIrqBridge *)OsalMemCalloc(sizeof(*bridge)); + if (bridge == NULL) { + return NULL; + } + + bridge->local = local; + bridge->func = func; + bridge->data = arg; + bridge->cntlr = cntlr; + bridge->stop = false; + + if (snprintf_s(bridge->name, GPIO_IRQ_THREAD_NAME_LEN, GPIO_IRQ_THREAD_NAME_LEN - 1, + "GPIO_IRQ_TSK_%d_%d", bridge->cntlr->start, bridge->local) < 0) { + HDF_LOGE("GpioIrqBridgeCreate: format thread name fail!"); + goto __ERR_FORMAT_NAME; + } + + if (OsalSpinInit(&bridge->spin) != HDF_SUCCESS) { + HDF_LOGE("GpioIrqBridgeCreate: init spin fail!"); + goto __ERR_INIT_SPIN; + } + + if (OsalSemInit(&bridge->sem, 0) != HDF_SUCCESS) { + HDF_LOGE("GpioIrqBridgeCreate: init sem fail!"); + goto __ERR_INIT_SEM; + } + + ret = OsalThreadCreate(&bridge->thread, (OsalThreadEntry)GpioIrqThreadWorker, (void *)bridge); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioIrqBridgeCreate: create irq fail!"); + goto __ERR_CREATE_THREAD; + } + + cfg.name = bridge->name; + cfg.priority = OSAL_THREAD_PRI_HIGH; + cfg.stackSize = GPIO_IRQ_STACK_SIZE; + if (OsalThreadStart(&bridge->thread, &cfg) != HDF_SUCCESS) { + HDF_LOGE("GpioIrqBridgeCreate: start irq thread fail:%d", ret); + goto __ERR_START_THREAD; + } + return bridge; +__ERR_START_THREAD: + (void)OsalThreadDestroy(&bridge->thread); +__ERR_CREATE_THREAD: + (void)OsalSemDestroy(&bridge->sem); +__ERR_INIT_SEM: + (void)OsalSpinDestroy(&bridge->spin); +__ERR_INIT_SPIN: +__ERR_FORMAT_NAME: + OsalMemFree(bridge); + return NULL; +} +#else +static struct GpioIrqBridge *GpioIrqBridgeCreate(struct GpioCntlr *cntlr, + uint16_t local, GpioIrqFunc func, void *arg) +{ + (void)cntlr; + (void)local; + (void)func; + (void)arg; + return NULL; +} +#endif + +static void GpioIrqBridgeDestroy(struct GpioIrqBridge *bridge) +{ +#ifndef __KERNEL__ + uint32_t flags; + (void)OsalSpinLockIrqSave(&bridge->spin, &flags); + if (bridge->stop == false) { + bridge->stop = true; + (void)OsalSemPost(&bridge->sem); + } + (void)OsalSpinUnlockIrqRestore(&bridge->spin, &flags); +#else + (void)bridge; +#endif +} + +void GpioCntlrIrqCallback(struct GpioCntlr *cntlr, uint16_t local) +{ + struct GpioInfo *ginfo = NULL; + + if (cntlr != NULL && local < cntlr->count && cntlr->ginfos != NULL) { + ginfo = &cntlr->ginfos[local]; + if (ginfo != NULL && ginfo->irqFunc != NULL) { + (void)ginfo->irqFunc(local, ginfo->irqData); + } else { + HDF_LOGW("GpioCntlrIrqCallback: ginfo or irqFunc is NULL!"); + } + } else { + HDF_LOGW("GpioCntlrIrqCallback: invalid cntlr(ginfos) or loal num!"); + } +} + +int32_t GpioCntlrSetIrq(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg) +{ + int32_t ret; + uint32_t flags; + GpioIrqFunc theFunc = func; + void *theData = arg; + struct GpioIrqBridge *bridge = NULL; + void *oldFunc = NULL; + void *oldData = NULL; + + if (cntlr == NULL || cntlr->ginfos == NULL) { return HDF_ERR_INVALID_OBJECT; } + if (local >= cntlr->count) { + return HDF_ERR_INVALID_PARAM; + } if (cntlr->ops == NULL || cntlr->ops->setIrq == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->setIrq(cntlr, gpio, mode, func, arg); + + if ((mode & GPIO_IRQ_USING_THREAD) != 0) { + bridge = GpioIrqBridgeCreate(cntlr, local, func, arg); + if (bridge != NULL) { + theData = bridge; + theFunc = GpioIrqBridgeFunc; + } +#ifndef __KERNEL__ + if (bridge == NULL) { + return HDF_FAILURE; + } +#endif + } + + (void)OsalSpinLockIrqSave(&cntlr->spin, &flags); + oldFunc = cntlr->ginfos[local].irqFunc; + oldData = cntlr->ginfos[local].irqData; + cntlr->ginfos[local].irqFunc = theFunc; + cntlr->ginfos[local].irqData = theData; + ret = cntlr->ops->setIrq(cntlr, local, mode, theFunc, theData); + if (ret == HDF_SUCCESS) { + if (oldFunc == GpioIrqBridgeFunc) { + GpioIrqBridgeDestroy((struct GpioIrqBridge *)oldData); + } + } else { + cntlr->ginfos[local].irqFunc = oldFunc; + cntlr->ginfos[local].irqData = oldData; + if (bridge != NULL) { + GpioIrqBridgeDestroy(bridge); + bridge = NULL; + } + } + (void)OsalSpinUnlockIrqRestore(&cntlr->spin, &flags); + return ret; } -int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t gpio) +int32_t GpioCntlrUnsetIrq(struct GpioCntlr *cntlr, uint16_t local) { - if (cntlr == NULL) { + int32_t ret; + uint32_t flags; + struct GpioIrqBridge *bridge = NULL; + + if (cntlr == NULL || cntlr->ginfos == NULL) { return HDF_ERR_INVALID_OBJECT; } + if (local >= cntlr->count) { + return HDF_ERR_INVALID_PARAM; + } if (cntlr->ops == NULL || cntlr->ops->unsetIrq == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->unsetIrq(cntlr, gpio); + + (void)OsalSpinLockIrqSave(&cntlr->spin, &flags); + ret = cntlr->ops->unsetIrq(cntlr, local); + if (ret == HDF_SUCCESS) { + if (cntlr->ginfos[local].irqFunc == GpioIrqBridgeFunc) { + bridge = (struct GpioIrqBridge *)cntlr->ginfos[local].irqData; + GpioIrqBridgeDestroy(bridge); + } + cntlr->ginfos[local].irqFunc = NULL; + cntlr->ginfos[local].irqData = NULL; + } + (void)OsalSpinUnlockIrqRestore(&cntlr->spin, &flags); + return ret; } -int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t gpio) +int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t local) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -170,10 +439,10 @@ int32_t GpioCntlrEnableIrq(struct GpioCntlr *cntlr, uint16_t gpio) if (cntlr->ops == NULL || cntlr->ops->enableIrq == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->enableIrq(cntlr, gpio); + return cntlr->ops->enableIrq(cntlr, local); } -int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t gpio) +int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t local) { if (cntlr == NULL) { return HDF_ERR_INVALID_OBJECT; @@ -181,5 +450,5 @@ int32_t GpioCntlrDisableIrq(struct GpioCntlr *cntlr, uint16_t gpio) if (cntlr->ops == NULL || cntlr->ops->disableIrq == NULL) { return HDF_ERR_NOT_SUPPORT; } - return cntlr->ops->disableIrq(cntlr, gpio); + return cntlr->ops->disableIrq(cntlr, local); } diff --git a/support/platform/src/gpio_if.c b/support/platform/src/gpio_if.c old mode 100755 new mode 100644 index ed8b2b72..444fdfe3 --- a/support/platform/src/gpio_if.c +++ b/support/platform/src/gpio_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "gpio_if.h" @@ -37,98 +14,42 @@ #define HDF_LOG_TAG gpio_if -static struct GpioCntlr *GpioGetCntlr(void) -{ - static struct GpioCntlr *service = NULL; - - if (service != NULL) { - return service; - } - service = (struct GpioCntlr*)DevSvcManagerClntGetService("HDF_PLATFORM_GPIO"); - if (service == NULL) { - HDF_LOGE("GpioGetCntlr: get service fail!"); - } - return service; -} - - int32_t GpioRead(uint16_t gpio, uint16_t *val) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - - return GpioCntlrRead(cntlr, gpio, val); + return GpioCntlrRead(GpioGetCntlr(gpio), gpio, val); } int32_t GpioWrite(uint16_t gpio, uint16_t val) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrWrite(cntlr, gpio, val); + return GpioCntlrWrite(GpioGetCntlr(gpio), gpio, val); } int32_t GpioSetDir(uint16_t gpio, uint16_t dir) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrSetDir(cntlr, gpio, dir); + return GpioCntlrSetDir(GpioGetCntlr(gpio), gpio, dir); } int32_t GpioGetDir(uint16_t gpio, uint16_t *dir) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrGetDir(cntlr, gpio, dir); + return GpioCntlrGetDir(GpioGetCntlr(gpio), gpio, dir); } int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrSetIrq(cntlr, gpio, mode, func, arg); + return GpioCntlrSetIrq(GpioGetCntlr(gpio), gpio, mode, func, arg); } int32_t GpioUnSetIrq(uint16_t gpio) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrUnsetIrq(cntlr, gpio); + return GpioCntlrUnsetIrq(GpioGetCntlr(gpio), gpio); } int32_t GpioEnableIrq(uint16_t gpio) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrEnableIrq(cntlr, gpio); + return GpioCntlrEnableIrq(GpioGetCntlr(gpio), gpio); } int32_t GpioDisableIrq(uint16_t gpio) { - struct GpioCntlr *cntlr = GpioGetCntlr(); - - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; - } - return GpioCntlrDisableIrq(cntlr, gpio); + return GpioCntlrDisableIrq(GpioGetCntlr(gpio), gpio); } diff --git a/support/platform/src/i2c_core.c b/support/platform/src/i2c_core.c old mode 100755 new mode 100644 index 3c4c7925..0ee4f3bd --- a/support/platform/src/i2c_core.c +++ b/support/platform/src/i2c_core.c @@ -1,40 +1,216 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "i2c_core.h" -#include +#include "hdf_device_desc.h" #include "hdf_log.h" #include "osal_mem.h" +#include "osal_time.h" +#include "plat_common.h" +#include "plat_log.h" #define HDF_LOG_TAG i2c_core +#define LOCK_WAIT_SECONDS_M 1 +#define I2C_HANDLE_SHIFT ((uintptr_t)(-1) << 16) + +struct I2cManager { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct I2cCntlr *cntlrs[I2C_BUS_MAX]; + struct OsalMutex lock; +}; + +static struct I2cManager *g_i2cManager = NULL; + +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; +} + +static void I2cCntlrUnlockDefault(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + + OsalAtomicInc(&cntlr->atom); +} + +static const struct I2cLockMethod g_i2cLockOpsDefault = { + .lock = I2cCntlrLockDefault, + .unlock = I2cCntlrUnlockDefault, +}; + +static int32_t I2cManagerAddCntlr(struct I2cCntlr *cntlr) +{ + int32_t ret; + struct I2cManager *manager = g_i2cManager; + + if (cntlr->busId >= I2C_BUS_MAX) { + HDF_LOGE("I2cManagerAddCntlr: busId:%d exceed!", cntlr->busId); + return HDF_ERR_INVALID_PARAM; + } + + if (manager == NULL) { + HDF_LOGE("I2cManagerAddCntlr: get i2c manager fail!"); + return HDF_ERR_NOT_SUPPORT; + } + if (OsalMutexLock(&manager->lock) != HDF_SUCCESS) { + HDF_LOGE("I2cManagerAddCntlr: lock i2c manager fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + if (manager->cntlrs[cntlr->busId] != NULL) { + HDF_LOGE("I2cManagerAddCntlr: cntlr of bus:%d already exits!", cntlr->busId); + ret = HDF_FAILURE; + } else { + manager->cntlrs[cntlr->busId] = cntlr; + ret = HDF_SUCCESS; + } + + (void)OsalMutexUnlock(&manager->lock); + return ret; +} + +static void I2cManagerRemoveCntlr(struct I2cCntlr *cntlr) +{ + struct I2cManager *manager = g_i2cManager; + + if (cntlr->busId < 0 || cntlr->busId >= I2C_BUS_MAX) { + HDF_LOGE("I2cManagerRemoveCntlr: invalid busId:%d!", cntlr->busId); + return; + } + + if (manager == NULL) { + HDF_LOGE("I2cManagerRemoveCntlr: get i2c manager fail!"); + return; + } + if (OsalMutexLock(&manager->lock) != HDF_SUCCESS) { + HDF_LOGE("I2cManagerRemoveCntlr: lock i2c manager fail!"); + return; + } + + if (manager->cntlrs[cntlr->busId] != cntlr) { + HDF_LOGE("I2cManagerRemoveCntlr: cntlr(%d) not in manager!", cntlr->busId); + } else { + manager->cntlrs[cntlr->busId] = NULL; + } + + (void)OsalMutexUnlock(&manager->lock); +} + +/* + * Find an i2c cntroller by bus number, without ref count + */ +static struct I2cCntlr *I2cManagerFindCntlr(int16_t number) +{ + struct I2cCntlr *cntlr = NULL; + struct I2cManager *manager = g_i2cManager; + + if (number < 0 || number >= I2C_BUS_MAX) { + HDF_LOGE("I2cManagerFindCntlr: invalid busId:%d!", number); + return NULL; + } + + if (manager == NULL) { + HDF_LOGE("I2cManagerFindCntlr: get i2c manager fail!"); + return NULL; + } + + if (OsalMutexLock(&manager->lock) != HDF_SUCCESS) { + HDF_LOGE("I2cManagerFindCntlr: lock i2c manager fail!"); + return NULL; + } + cntlr = manager->cntlrs[number]; + (void)OsalMutexUnlock(&manager->lock); + return cntlr; +} + +/* + * Find and return an i2c controller by number, with ref count(TO DO ...) + */ +struct I2cCntlr *I2cCntlrGet(int16_t number) +{ + return I2cManagerFindCntlr(number); +} + +/* + * Put back the i2c controller, with ref count(TO DO ...) + */ +void I2cCntlrPut(struct I2cCntlr *cntlr) +{ + (void)cntlr; +} + +int32_t I2cCntlrAdd(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->ops == NULL) { + HDF_LOGE("I2cCntlrAdd: no ops supplied!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (cntlr->lockOps == NULL) { + HDF_LOGI("I2cCntlrAdd: use default lock methods!"); + cntlr->lockOps = &g_i2cLockOpsDefault; + } + + if (OsalMutexInit(&cntlr->lock) != HDF_SUCCESS) { + HDF_LOGE("I2cCntlrAdd: init lock fail!"); + return HDF_FAILURE; + } + OsalAtomicSet(&cntlr->atom, 1); + + return I2cManagerAddCntlr(cntlr); +} + +void I2cCntlrRemove(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + I2cManagerRemoveCntlr(cntlr); + (void)OsalMutexDestroy(&cntlr->lock); +} + +static inline int32_t I2cCntlrLock(struct I2cCntlr *cntlr) +{ + if (cntlr->lockOps == NULL || cntlr->lockOps->lock == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + return cntlr->lockOps->lock(cntlr); +} + +static inline void I2cCntlrUnlock(struct I2cCntlr *cntlr) +{ + if (cntlr->lockOps != NULL && cntlr->lockOps->unlock != NULL) { + cntlr->lockOps->unlock(cntlr); + } +} int32_t I2cCntlrTransfer(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count) { @@ -50,44 +226,238 @@ int32_t I2cCntlrTransfer(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t co return HDF_ERR_NOT_SUPPORT; } + if (I2cCntlrLock(cntlr) != HDF_SUCCESS) { + HDF_LOGE("I2cCntlrTransfer: lock controller fail!"); + return HDF_ERR_DEVICE_BUSY; + } ret = cntlr->ops->transfer(cntlr, msgs, count); + I2cCntlrUnlock(cntlr); return ret; } -int32_t I2cCntlrAdd(struct I2cCntlr *cntlr) +static int32_t I2cTransferRebuildMsgs(struct HdfSBuf *data, struct I2cMsg **ppmsgs, int16_t *pcount, uint8_t **ppbuf) { - if (cntlr == NULL) { - return HDF_ERR_INVALID_OBJECT; + int16_t count, i; + uint32_t len; + uint32_t lenReply = 0; + uint8_t *buf = NULL; + uint8_t *bufReply = NULL; + struct I2cMsg *msgs = NULL; + + if (!HdfSbufReadBuffer(data, (const void **)&msgs, &len)) { + HDF_LOGE("I2cTransferRebuildMsgs: read msgs fail!"); + return HDF_ERR_IO; } - if (cntlr->device == NULL) { - HDF_LOGE("I2cCntlrAdd: no device associated!"); - return HDF_ERR_INVALID_OBJECT; + count = len / sizeof(*msgs); + PLAT_LOGV("I2cTransferRebuildMsgs: count:%u, len:%u, sizeof(*msgs):%u", + count, len, sizeof(*msgs)); + for (i = 0; i < count; i++) { + if ((msgs[i].flags & I2C_FLAG_READ) != 0) { + lenReply += msgs[i].len; + } else if (!HdfSbufReadBuffer(data, (const void **)&buf, &len)) { + HDF_LOGE("I2cTransferRebuildMsgs: read msg[%d] buf fail!", i); + } else { + msgs[i].buf = buf; + msgs[i].len = len; + } } - if (cntlr->ops == NULL) { - HDF_LOGE("I2cCntlrAdd: no ops supplied!"); - return HDF_ERR_INVALID_OBJECT; + if (lenReply > 0) { + bufReply = OsalMemCalloc(lenReply); + if (bufReply == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + for (i = 0, buf = bufReply; i < count && buf < (bufReply + lenReply); i++) { + if ((msgs[i].flags & I2C_FLAG_READ) != 0) { + msgs[i].buf = buf; + buf += msgs[i].len; + } + } } - if (OsalMutexInit(&cntlr->lock) != HDF_SUCCESS) { - HDF_LOGE("I2cCntlrAdd: init lock fail!"); - return HDF_FAILURE; - } - cntlr->device->service = &cntlr->service; + + *ppmsgs = msgs; + *pcount = count; + *ppbuf = bufReply; return HDF_SUCCESS; } -void I2cCntlrRemove(struct I2cCntlr *cntlr) +static int32_t I2cTransferWriteBackMsgs(struct HdfSBuf *reply, struct I2cMsg *msgs, int16_t count) { - if (cntlr == NULL) { - return; + int16_t i; + + for (i = 0; i < count; i++) { + if ((msgs[i].flags & I2C_FLAG_READ) == 0) { + continue; + } + if (!HdfSbufWriteBuffer(reply, msgs[i].buf, msgs[i].len)) { + HDF_LOGE("I2cTransferWriteBackMsgs: write msg[%d] reply fail!", i); + return HDF_ERR_IO; + } } - if (cntlr->device == NULL) { - HDF_LOGE("I2cCntlrBind: no device associated!"); - return; - } - - cntlr->device->service = NULL; - (void)OsalMutexDestroy(&cntlr->lock); + return HDF_SUCCESS; } + +static int32_t I2cManagerIoTransfer(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + int16_t count; + int16_t number; + uint32_t handle; + uint8_t *bufReply = NULL; + struct I2cMsg *msgs = NULL; + + if (data == NULL || reply == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &handle)) { + HDF_LOGE("I2cManagerIoTransfer: read handle fail!"); + return HDF_ERR_IO; + } + number = (int16_t)(handle - I2C_HANDLE_SHIFT); + + ret = I2cTransferRebuildMsgs(data, &msgs, &count, &bufReply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cManagerIoTransfer: rebuild msgs fail:%d", ret); + return ret; + } + + ret = I2cCntlrTransfer(I2cManagerFindCntlr(number), msgs, count); + if (ret != count) { + goto __EXIT__; + } + + ret = I2cTransferWriteBackMsgs(reply, msgs, count); + +__EXIT__: + if (bufReply != NULL) { + OsalMemFree(bufReply); + } + return ret; +} + +static int32_t I2cManagerIoOpen(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int16_t number; + uint32_t handle; + + if (!HdfSbufReadUint16(data, (uint16_t *)&number)) { + return HDF_ERR_IO; + } + + if (number < 0 || number >= I2C_BUS_MAX || reply == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (I2cCntlrGet(number) == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + handle = (uint32_t)(number + I2C_HANDLE_SHIFT); + if (!HdfSbufWriteUint32(reply, handle)) { + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t I2cManagerIoClose(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int16_t number; + uint32_t handle; + + if (!HdfSbufReadUint32(data, &handle)) { + return HDF_ERR_IO; + } + + number = (int16_t)(handle - I2C_HANDLE_SHIFT); + if (number < 0 || number >= I2C_BUS_MAX) { + return HDF_ERR_INVALID_PARAM; + } + I2cCntlrPut(I2cManagerFindCntlr(number)); + return HDF_SUCCESS; +} + +static int32_t I2cManagerDispatch(struct HdfDeviceIoClient *client, int cmd, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret; + + switch (cmd) { + case I2C_IO_OPEN: + return I2cManagerIoOpen(data, reply); + case I2C_IO_CLOSE: + return I2cManagerIoClose(data, reply); + case I2C_IO_TRANSFER: + return I2cManagerIoTransfer(data, reply); + default: + ret = HDF_ERR_NOT_SUPPORT; + break; + } + return ret; +} + +static int32_t I2cManagerBind(struct HdfDeviceObject *device) +{ + int32_t ret; + struct I2cManager *manager = NULL; + + HDF_LOGI("I2cManagerBind: Enter!"); + if (device == NULL) { + HDF_LOGE("I2cManagerBind: device is NULL"); + return HDF_ERR_INVALID_OBJECT; + } + + manager = (struct I2cManager *)OsalMemCalloc(sizeof(*manager)); + if (manager == NULL) { + HDF_LOGE("I2cManagerBind: malloc manager fail!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = OsalMutexInit(&manager->lock); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cManagerBind: mutex init fail:%d", ret); + OsalMemFree(manager); + return HDF_FAILURE; + } + + manager->device = device; + device->service = &manager->service; + device->service->Dispatch = I2cManagerDispatch; + g_i2cManager = manager; + return HDF_SUCCESS; +} + +static int32_t I2cManagerInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static void I2cManagerRelease(struct HdfDeviceObject *device) +{ + struct I2cManager *manager = NULL; + + HDF_LOGI("I2cManagerRelease: enter"); + if (device == NULL) { + HDF_LOGI("I2cManagerRelease: device is null"); + return; + } + manager = (struct I2cManager *)device->service; + if (manager == NULL) { + HDF_LOGI("I2cManagerRelease: no service binded!"); + return; + } + g_i2cManager = NULL; + OsalMemFree(manager); +} + +struct HdfDriverEntry g_i2cManagerEntry = { + .moduleVersion = 1, + .Bind = I2cManagerBind, + .Init = I2cManagerInit, + .Release = I2cManagerRelease, + .moduleName = "HDF_PLATFORM_I2C_MANAGER", +}; +HDF_INIT(g_i2cManagerEntry); diff --git a/support/platform/src/i2c_if.c b/support/platform/src/i2c_if.c old mode 100755 new mode 100644 index 66f9b479..2da22446 --- a/support/platform/src/i2c_if.c +++ b/support/platform/src/i2c_if.c @@ -1,104 +1,281 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "i2c_if.h" +#ifndef __USER__ #include "devsvc_manager_clnt.h" +#endif #include "hdf_base.h" +#ifdef __USER__ +#include "hdf_io_service_if.h" +#endif #include "hdf_log.h" +#ifndef __USER__ #include "i2c_core.h" +#endif #include "osal_mem.h" #include "securec.h" #define HDF_LOG_TAG i2c_if -#define SERVICE_NAME_LEN 32 -#define I2C_BUS_MAX 8 +#define I2C_SERVICE_NAME "HDF_PLATFORM_I2C_MANAGER" -static struct I2cCntlr *I2cCntlrGetByNumber(int16_t num) +#ifdef __USER__ +enum I2cIoCmd { + I2C_IO_TRANSFER = 0, + I2C_IO_OPEN = 1, + I2C_IO_CLOSE = 2, +}; + +static void *I2cManagerGetService(void) { - struct I2cCntlr *cntlr = NULL; - char *cntlrName = NULL; + static void *manager = NULL; - if (num < 0 || num >= I2C_BUS_MAX) { - HDF_LOGE("I2cCntlrGetByNumber: invalid num:%d", num); + if (manager != NULL) { + return manager; + } + manager = (void *)HdfIoServiceBind(I2C_SERVICE_NAME); + if (manager == NULL) { + HDF_LOGE("I2cManagerGetService: fail to get i2c manager!"); + } + return manager; +} +#endif + +DevHandle I2cOpen(int16_t number) +{ +#ifdef __USER__ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + uint32_t handle; + + service = (struct HdfIoService *)I2cManagerGetService(); + if (service == NULL) { return NULL; } - cntlrName = OsalMemCalloc(SERVICE_NAME_LEN + 1); - if (cntlrName == NULL) { + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { return NULL; } - if (snprintf_s(cntlrName, SERVICE_NAME_LEN + 1, SERVICE_NAME_LEN, - "HDF_PLATFORM_I2C_%d", num) < 0) { - HDF_LOGE("I2cCntlrGetByNumber: format cntlr name fail!"); - OsalMemFree(cntlrName); + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + HdfSBufRecycle(data); return NULL; } - cntlr = (struct I2cCntlr *)DevSvcManagerClntGetService(cntlrName); - if (cntlr == NULL) { - HDF_LOGE("I2cCntlrGetByNumber: get cntlr fail!"); + + if (!HdfSbufWriteUint16(data, (uint16_t)number)) { + HDF_LOGE("I2cOpen: write number fail!"); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return NULL; } - OsalMemFree(cntlrName); - return cntlr; + + ret = service->dispatcher->Dispatch(&service->object, I2C_IO_OPEN, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cOpen: service call open fail:%d", ret); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return NULL; + } + + if (!HdfSbufReadUint32(reply, &handle)) { + HDF_LOGE("I2cOpen: read handle fail!"); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return NULL; + } + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return (DevHandle)(uintptr_t)handle; +#else + return (DevHandle)I2cCntlrGet(number); +#endif } -struct DevHandle *I2cOpen(int16_t number) +void I2cClose(DevHandle handle) { - struct DevHandle *handle = NULL; - struct I2cCntlr *cntlr = NULL; +#ifdef __USER__ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; - cntlr = I2cCntlrGetByNumber(number); - if (cntlr == NULL) { - return NULL; + service = (struct HdfIoService *)I2cManagerGetService(); + if (service == NULL) { + return; } - handle = OsalMemCalloc(sizeof(*handle)); + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + return; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("I2cClose: write handle fail!"); + HdfSBufRecycle(data); + return; + } + + ret = service->dispatcher->Dispatch(&service->object, I2C_IO_CLOSE, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cClose: close handle fail:%d", ret); + } + HdfSBufRecycle(data); +#else + I2cCntlrPut((struct I2cCntlr *)handle); +#endif +} + +#ifdef __USER__ +static int32_t I2cMsgWriteArray(DevHandle handle, struct HdfSBuf *data, struct I2cMsg *msgs, int16_t count) +{ + int16_t i; + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("I2cMsgWriteArray: write handle fail!"); + return HDF_ERR_IO; + } + + if (!HdfSbufWriteBuffer(data, (uint8_t *)msgs, sizeof(*msgs) * count)) { + HDF_LOGE("I2cMsgWriteArray: write msgs array fail!"); + return HDF_ERR_IO; + } + + for (i = 0; i < count; i++) { + if ((msgs[i].flags & I2C_FLAG_READ) != 0) { + continue; + } + if (!HdfSbufWriteBuffer(data, (uint8_t *)msgs[i].buf, msgs[i].len)) { + HDF_LOGE("I2cMsgWriteArray: write msg[%d] buf fail!", i); + return HDF_ERR_IO; + } + } + + return HDF_SUCCESS; +} + +static int32_t I2cMsgReadBack(struct HdfSBuf *data, struct I2cMsg *msg) +{ + uint32_t rLen; + const void *rBuf = NULL; + + if ((msg->flags & I2C_FLAG_READ) == 0) { + return HDF_SUCCESS; /* write msg no need to read back */ + } + + if (!HdfSbufReadBuffer(data, &rBuf, &rLen)) { + HDF_LOGE("I2cMsgReadBack: read rBuf fail!"); + return HDF_ERR_IO; + } + if (msg->len != rLen) { + HDF_LOGE("I2cMsgReadBack: err len:%u, rLen:%u", msg->len, rLen); + if (rLen > msg->len) { + rLen = msg->len; + } + } + if (memcpy_s(msg->buf, msg->len, rBuf, rLen) != EOK) { + HDF_LOGE("I2cMsgReadBack: memcpy rBuf fail!"); + return HDF_ERR_IO; + } + + return HDF_SUCCESS; +} + +static inline int32_t I2cMsgReadArray(struct HdfSBuf *reply, struct I2cMsg *msgs, int16_t count) +{ + int16_t i; + int32_t ret; + + for (i = 0; i < count; i++) { + ret = I2cMsgReadBack(reply, &msgs[i]); + if (ret != HDF_SUCCESS) { + return ret; + } + } + return HDF_SUCCESS; +} + +static int32_t I2cServiceTransfer(DevHandle handle, struct I2cMsg *msgs, int16_t count) +{ + int16_t i; + int32_t ret; + uint32_t recvLen = 0; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("I2cServiceTransfer: failed to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = I2cMsgWriteArray(handle, data, msgs, count); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cServiceTransfer: failed to write msgs!"); + goto __EXIT; + } + + for (i = 0; i < count; i++) { + recvLen += ((msgs[i].flags & I2C_FLAG_READ) == 0) ? 0 : (msgs[i].len + sizeof(uint64_t)); + } + reply = (recvLen == 0) ? HdfSBufObtainDefaultSize() : HdfSBufObtain(recvLen); + if (reply == NULL) { + HDF_LOGE("I2cServiceTransfer: failed to obtain reply!"); + ret = HDF_ERR_MALLOC_FAIL; + goto __EXIT; + } + + service = I2cManagerGetService(); + if (service == NULL) { + ret = HDF_ERR_NOT_SUPPORT; + goto __EXIT; + } + ret = service->dispatcher->Dispatch(&service->object, I2C_IO_TRANSFER, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cServiceTransfer: failed to send service call:%d", ret); + goto __EXIT; + } + + ret = I2cMsgReadArray(reply, msgs, count); + if (ret != HDF_SUCCESS) { + goto __EXIT; + } + + ret = count; +__EXIT: + if (data != NULL) { + HdfSBufRecycle(data); + } + if (reply != NULL) { + HdfSBufRecycle(reply); + } + return ret; +} +#endif + +int32_t I2cTransfer(DevHandle handle, struct I2cMsg *msgs, int16_t count) +{ if (handle == NULL) { - return NULL; - } - handle->object = cntlr; - return handle; -} - -void I2cClose(struct DevHandle *handle) -{ - if (handle != NULL) { - handle->object = NULL; - OsalMemFree(handle); - } -} - -int32_t I2cTransfer(struct DevHandle *handle, struct I2cMsg *msgs, int16_t count) -{ - if (handle == NULL || handle->object == NULL) { return HDF_ERR_INVALID_OBJECT; } - return I2cCntlrTransfer((struct I2cCntlr *)handle->object, msgs, count); + if (msgs == NULL || count <= 0) { + HDF_LOGE("I2cTransfer: err parms! msgs:%s, count:%d", + (msgs == NULL) ? "0" : "x", count); + return HDF_ERR_INVALID_PARAM; + } + +#ifdef __USER__ + return I2cServiceTransfer(handle, msgs, count); +#else + return I2cCntlrTransfer((struct I2cCntlr *)handle, msgs, count); +#endif } + diff --git a/support/platform/src/mipi_dsi_core.c b/support/platform/src/mipi_dsi_core.c new file mode 100644 index 00000000..0e2c74cb --- /dev/null +++ b/support/platform/src/mipi_dsi_core.c @@ -0,0 +1,228 @@ +/* + * 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_time.h" +#include "osal_mem.h" +#include "hdf_log.h" +#include "mipi_dsi_core.h" + +#define HDF_LOG_TAG mipi_dsi_core + +static struct MipiDsiHandle g_mipiDsihandle[MAX_CNTLR_CNT]; + +int32_t MipiDsiRegisterCntlr(struct MipiDsiCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->devNo >= MAX_CNTLR_CNT) { + return HDF_ERR_INVALID_PARAM; + } + if (g_mipiDsihandle[cntlr->devNo].cntlr == NULL) { + g_mipiDsihandle[cntlr->devNo].cntlr = cntlr; + if (OsalMutexInit(&g_mipiDsihandle[cntlr->devNo].lock) != HDF_SUCCESS) { + HDF_LOGE("%s: init lock fail!", __func__); + g_mipiDsihandle[cntlr->devNo].cntlr = NULL; + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + HDF_LOGE("cntlr is not NULL"); + return HDF_FAILURE; +} + +DevHandle MipiDsiOpen(uint8_t id) +{ + if (id >= MAX_CNTLR_CNT) { + HDF_LOGE("id invalid"); + return NULL; + } + if (g_mipiDsihandle[id].cntlr == NULL) { + HDF_LOGE("no mipi_dsi %d cntlr", id); + return NULL; + } + if (OsalMutexLock(&(g_mipiDsihandle[id].lock)) != HDF_SUCCESS) { + HDF_LOGE("mutex lock fail"); + return NULL; + } + return (DevHandle)(&(g_mipiDsihandle[id])); +} + +void MipiDsiClose(DevHandle handle) +{ + struct MipiDsiHandle *mipiHandle = (struct MipiDsiHandle *)handle; + + if (mipiHandle != NULL) { + (void)OsalMutexUnlock(&(mipiHandle->lock)); + } +} + +static int32_t MipiDsiSetDevCfg(struct MipiDsiCntlr *cntlr) +{ + /* set controler config */ + if (cntlr->setCntlrCfg == NULL) { + HDF_LOGE("setCntlrCfg is NULL"); + return HDF_FAILURE; + } + return cntlr->setCntlrCfg(cntlr); +} + +static struct MipiDsiCntlr *GetCntlr(DevHandle handle) +{ + struct MipiDsiHandle *mipiHandle = (struct MipiDsiHandle *)handle; + + return (mipiHandle == NULL) ? NULL : mipiHandle->cntlr; +} + +int32_t MipiDsiSetCfg(DevHandle handle, struct MipiCfg *cfg) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL || cfg == NULL) { + return HDF_FAILURE; + } + cntlr->phyDataRate = cfg->phyDataRate; + cntlr->pixelClk = cfg->pixelClk; + cntlr->timing = cfg->timing; + cntlr->mode = cfg->mode; + cntlr->burstMode = cfg->burstMode; + cntlr->format = cfg->format; + cntlr->lane = cfg->lane; + return MipiDsiSetDevCfg(cntlr); +} + +int32_t MipiDsiGetCfg(DevHandle handle, struct MipiCfg *cfg) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL || cfg == NULL) { + return HDF_FAILURE; + } + cfg->phyDataRate = cntlr->phyDataRate; + cfg->pixelClk = cntlr->pixelClk; + cfg->timing.xPixels = cntlr->timing.xPixels; + cfg->timing.hsaPixels = cntlr->timing.hsaPixels; + cfg->timing.hbpPixels = cntlr->timing.hbpPixels; + cfg->timing.hlinePixels = cntlr->timing.hlinePixels; + cfg->timing.vsaLines = cntlr->timing.vsaLines; + cfg->timing.vbpLines = cntlr->timing.vbpLines; + cfg->timing.vfpLines = cntlr->timing.vfpLines; + cfg->timing.ylines = cntlr->timing.ylines; + cfg->timing.edpiCmdSize = cntlr->timing.edpiCmdSize; + cfg->mode = cntlr->mode; + cfg->burstMode = cntlr->burstMode; + cfg->format = cntlr->format; + cfg->lane = cntlr->lane; + return HDF_SUCCESS; +} + +void MipiDsiSetLpMode(DevHandle handle) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL) { + return; + } + if (cntlr->toLp != NULL) { + cntlr->toLp(cntlr); + } else { + HDF_LOGI("toLp not support!"); + } +} +void MipiDsiSetHsMode(DevHandle handle) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL) { + return; + } + if (cntlr->toHs != NULL) { + cntlr->toHs(cntlr); + } else { + HDF_LOGI("toHs not support!"); + } +} +void MipiDsiEnterUlps(DevHandle handle) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL) { + return; + } + if (cntlr->enterUlps != NULL) { + cntlr->enterUlps(cntlr); + } else { + HDF_LOGI("enterUlps not support!"); + } +} +void MipiDsiExitUlps(DevHandle handle) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL) { + return; + } + if (cntlr->exitUlps != NULL) { + cntlr->exitUlps(cntlr); + } else { + HDF_LOGI("exitUlps not support!"); + } +} + +int32_t MipiDsiTx(DevHandle handle, struct DsiCmdDesc *cmd) +{ + struct MipiDsiCntlr *cntlr = NULL; + int32_t ret; + + cntlr = GetCntlr(handle); + if (cntlr == NULL || cmd == NULL) { + return HDF_FAILURE; + } + if (cntlr->setCmd != NULL) { + ret = cntlr->setCmd(cntlr, cmd); + if (cmd->delay > 0) { + OsalMSleep(cmd->delay); + } + return ret; + } + return HDF_ERR_NOT_SUPPORT; +} + +int32_t MipiDsiRx(DevHandle handle, struct DsiCmdDesc *cmd, int32_t readLen, uint8_t *out) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL || cmd == NULL) { + return HDF_FAILURE; + } + if (cntlr->getCmd != NULL) { + return cntlr->getCmd(cntlr, cmd, readLen, out); + } + return HDF_ERR_NOT_SUPPORT; +} + +int32_t MipiDsiPowerControl(DevHandle handle, uint8_t enable) +{ + struct MipiDsiCntlr *cntlr = NULL; + + cntlr = GetCntlr(handle); + if (cntlr == NULL) { + return HDF_FAILURE; + } + if (cntlr->powerControl != NULL) { + return cntlr->powerControl(cntlr, enable); + } + return HDF_ERR_NOT_SUPPORT; +} diff --git a/support/platform/src/pwm_core.c b/support/platform/src/pwm_core.c new file mode 100644 index 00000000..98b2347b --- /dev/null +++ b/support/platform/src/pwm_core.c @@ -0,0 +1,241 @@ +/* + * 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 "pwm_core.h" +#include "pwm_if.h" +#include "securec.h" + +#define HDF_LOG_TAG PWM_CORE +#define PWM_NAME_LEN 32 + +static struct PwmDev *PwmGetDevByNum(uint32_t num) +{ + int ret; + char *name = NULL; + struct PwmDev *pwm = NULL; + + name = (char *)OsalMemCalloc(PWM_NAME_LEN + 1); + if (name == NULL) { + return NULL; + } + ret = snprintf_s(name, PWM_NAME_LEN + 1, PWM_NAME_LEN, "HDF_PLATFORM_PWM_%u", num); + if (ret < 0) { + HDF_LOGE("%s: snprintf_s failed", __func__); + OsalMemFree(name); + return NULL; + } + pwm = (struct PwmDev *)DevSvcManagerClntGetService(name); + OsalMemFree(name); + return pwm; +} + +DevHandle PwmOpen(uint32_t num) +{ + int32_t ret; + struct PwmDev *pwm = PwmGetDevByNum(num); + + if (pwm == NULL) { + HDF_LOGE("%s: dev is null", __func__); + return NULL; + } + (void)OsalSpinLock(&(pwm->lock)); + if (pwm->busy) { + (void)OsalSpinUnlock(&(pwm->lock)); + HDF_LOGE("%s: pwm%u is busy", __func__, num); + return NULL; + } + if (pwm->method != NULL && pwm->method->open != NULL) { + ret = pwm->method->open(pwm); + if (ret != HDF_SUCCESS) { + (void)OsalSpinUnlock(&(pwm->lock)); + HDF_LOGE("%s: open failed, ret %d", __func__, ret); + return NULL; + } + } + pwm->busy = true; + (void)OsalSpinUnlock(&(pwm->lock)); + return (DevHandle)pwm; +} + +void PwmClose(DevHandle handle) +{ + int32_t ret; + struct PwmDev *pwm = (struct PwmDev *)handle; + + if (pwm == NULL) { + HDF_LOGE("%s: dev is null", __func__); + return; + } + + if (pwm->method != NULL && pwm->method->close != NULL) { + ret = pwm->method->close(pwm); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: close failed, ret %d", __func__, ret); + return; + } + } + (void)OsalSpinLock(&(pwm->lock)); + pwm->busy = false; + (void)OsalSpinUnlock(&(pwm->lock)); +} + +int32_t PwmSetConfig(DevHandle handle, struct PwmConfig *config) +{ + int32_t ret; + struct PwmDev *pwm = NULL; + + if (handle == NULL) { + HDF_LOGE("%s: handle is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + if (config == NULL) { + HDF_LOGE("%s: config is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + pwm = (struct PwmDev *)handle; + if (memcmp(config, &(pwm->cfg), sizeof(*config)) == 0) { + HDF_LOGE("%s: do not need to set config", __func__); + return HDF_SUCCESS; + } + if (pwm->method == NULL || pwm->method->setConfig == NULL) { + HDF_LOGE("%s: setConfig is not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + ret = pwm->method->setConfig(pwm, config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed, ret %d", __func__, ret); + return ret; + } + pwm->cfg = *config; + return HDF_SUCCESS; +} + +int32_t PwmGetConfig(DevHandle handle, struct PwmConfig *config) +{ + struct PwmDev *pwm = NULL; + + if (handle == NULL) { + HDF_LOGE("%s: handle is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + if (config == NULL) { + HDF_LOGE("%s: config is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + pwm = (struct PwmDev *)handle; + *config = pwm->cfg; + + return HDF_SUCCESS; +} + +int32_t PwmEnable(DevHandle handle) +{ + struct PwmConfig config; + + if (PwmGetConfig(handle, &config) != HDF_SUCCESS) { + return HDF_FAILURE; + } + config.status = PWM_ENABLE_STATUS; + return PwmSetConfig(handle, &config); +} + +int32_t PwmDisable(DevHandle handle) +{ + struct PwmConfig config; + + if (PwmGetConfig(handle, &config) != HDF_SUCCESS) { + return HDF_FAILURE; + } + config.status = PWM_DISABLE_STATUS; + return PwmSetConfig(handle, &config); +} + +int32_t PwmSetPeriod(DevHandle handle, uint32_t period) +{ + struct PwmConfig config; + + if (PwmGetConfig(handle, &config) != HDF_SUCCESS) { + return HDF_FAILURE; + } + config.period = period; + return PwmSetConfig(handle, &config); +} + +int32_t PwmSetDuty(DevHandle handle, uint32_t duty) +{ + struct PwmConfig config; + + if (PwmGetConfig(handle, &config) != HDF_SUCCESS) { + return HDF_FAILURE; + } + config.duty = duty; + return PwmSetConfig(handle, &config); +} + +int32_t PwmSetPolarity(DevHandle handle, uint8_t polarity) +{ + struct PwmConfig config; + + if (PwmGetConfig(handle, &config) != HDF_SUCCESS) { + return HDF_FAILURE; + } + config.polarity = polarity; + config.duty = config.period - config.duty; + return PwmSetConfig(handle, &config); +} + +int32_t PwmSetPriv(struct PwmDev *pwm, void *priv) +{ + if (pwm == NULL) { + HDF_LOGE("%s: pwm is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + pwm->priv = priv; + return HDF_SUCCESS; +} + +void *PwmGetPriv(struct PwmDev *pwm) +{ + if (pwm == NULL) { + HDF_LOGE("%s: pwm is null", __func__); + return NULL; + } + return pwm->priv; +} + +int32_t PwmDeviceAdd(struct HdfDeviceObject *obj, struct PwmDev *pwm) +{ + if (obj == NULL || pwm == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (pwm->method == NULL || pwm->method->setConfig == NULL) { + HDF_LOGE("%s: setConfig is null", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (OsalSpinInit(&(pwm->lock)) != HDF_SUCCESS) { + HDF_LOGE("%s: init spinlock fail", __func__); + return HDF_FAILURE; + } + pwm->device = obj; + obj->service = &(pwm->service); + return HDF_SUCCESS; +} + +void PwmDeviceRemove(struct HdfDeviceObject *obj, struct PwmDev *pwm) +{ + if (obj == NULL || pwm == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return; + } + (void)OsalSpinDestroy(&(pwm->lock)); + pwm->device = NULL; + obj->service = NULL; +} diff --git a/support/platform/src/rtc_base.c b/support/platform/src/rtc_base.c old mode 100755 new mode 100644 index 00084299..9b63c970 --- a/support/platform/src/rtc_base.c +++ b/support/platform/src/rtc_base.c @@ -1,35 +1,13 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "plat_log.h" #include "rtc_base.h" #define HDF_LOG_TAG rtc_base @@ -46,7 +24,7 @@ uint8_t RtcGetMonthDays(const uint8_t isLeapYear, const uint8_t month) if (RTC_FEBRUARY == month) { days = RTC_TWO_MONTH_DAY + isLeapYear; } else { - oddMonth = (month > RTC_AUGUST) ? (month - RTC_UNIT_DIFF) : month; + oddMonth = (month >= RTC_AUGUST) ? (month - RTC_UNIT_DIFF) : month; days = (oddMonth & RTC_ODD_MONTH_MASK) ? RTC_GREAT_MONTH_DAY : RTC_SMALL_MONTH_DAY; } return days; @@ -99,6 +77,7 @@ uint8_t RtcGetWeekDay(const struct RtcTime *time) return ((RTC_BEGIN_WEEKDAY + days - RTC_UNIT_DIFF) % RTC_MAX_WEEKDAY + RTC_UNIT_DIFF); } +#ifndef __KERNEL__ uint64_t RtcTimeToTimestamp(const struct RtcTime *time) { uint64_t seconds; @@ -110,7 +89,7 @@ uint64_t RtcTimeToTimestamp(const struct RtcTime *time) HDF_LOGE("RtcTimeToTimestamp: time null"); return RTC_FALSE; } - HDF_LOGD("RtcToTimestamp:year-month-day hour:min:second ms %04u-%02u-%02u %02u:%02u:%02u .%03u", + PLAT_LOGV("RtcToTimestamp:year-month-day hour:min:second ms %04u-%02u-%02u %02u:%02u:%02u .%03u", time->year, time->month, time->day, time->hour, time->minute, time->second, time->millisecond); if (RtcIsInvalid(time) == RTC_TRUE) { HDF_LOGE("RtcTimeToTimestamp: time invalid"); @@ -164,6 +143,7 @@ void TimestampToRtcTime(struct RtcTime *time, const uint64_t seconds) time->month += RTC_UNIT_DIFF; time->day += RTC_UNIT_DIFF; time->weekday = RtcGetWeekDay(time); - HDF_LOGD("TimestampToRtc:year-month-day weekday hour:min:second ms %04u-%02u-%02u %u %02u:%02u:%02u .%03u", + PLAT_LOGV("TimestampToRtc:year-month-day weekday hour:min:second ms %04u-%02u-%02u %u %02u:%02u:%02u .%03u", time->year, time->month, time->day, time->weekday, time->hour, time->minute, time->second, time->millisecond); } +#endif diff --git a/support/platform/src/rtc_core.c b/support/platform/src/rtc_core.c old mode 100755 new mode 100644 index c1865e56..3df837d3 --- a/support/platform/src/rtc_core.c +++ b/support/platform/src/rtc_core.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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" diff --git a/support/platform/src/rtc_if.c b/support/platform/src/rtc_if.c old mode 100755 new mode 100644 index 82a47662..232126ca --- a/support/platform/src/rtc_if.c +++ b/support/platform/src/rtc_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_base.h" @@ -41,9 +18,8 @@ static char *g_rtcServiceName = "HDF_PLATFORM_RTC"; -struct DevHandle *RtcOpen() +DevHandle RtcOpen() { - struct DevHandle *handle = NULL; struct RtcHost *host = NULL; host = (struct RtcHost *)DevSvcManagerClntGetService(g_rtcServiceName); @@ -51,42 +27,34 @@ struct DevHandle *RtcOpen() HDF_LOGE("rtc get service name failed"); return NULL; } - handle = OsalMemCalloc(sizeof(*handle)); - if (handle == NULL) { - return NULL; - } - handle->object = host; - return handle; + return (DevHandle)host; } -void RtcClose(struct DevHandle *handle) +void RtcClose(DevHandle handle) { - if (handle != NULL) { - handle->object = NULL; - OsalMemFree(handle); - } + (void)handle; } -int32_t RtcReadTime(struct DevHandle *handle, struct RtcTime *time) +int32_t RtcReadTime(DevHandle handle, struct RtcTime *time) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcReadTime: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->ReadTime == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->ReadTime(host, time); } -int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time) +int32_t RtcWriteTime(DevHandle handle, const struct RtcTime *time) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcWriteTime: handle is null"); return HDF_ERR_INVALID_OBJECT; } @@ -96,34 +64,34 @@ int32_t RtcWriteTime(struct DevHandle *handle, const struct RtcTime *time) return HDF_ERR_INVALID_PARAM; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->WriteTime == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->WriteTime(host, time); } -int32_t RtcReadAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time) +int32_t RtcReadAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime *time) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcReadAlarm: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->ReadAlarm == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->ReadAlarm(host, alarmIndex, time); } -int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time) +int32_t RtcWriteAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime *time) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcWriteAlarm: handle is null"); return HDF_ERR_INVALID_OBJECT; } @@ -133,52 +101,52 @@ int32_t RtcWriteAlarm(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, c return HDF_ERR_INVALID_PARAM; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->WriteAlarm == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->WriteAlarm(host, alarmIndex, time); } -int32_t RtcRegisterAlarmCallback(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb) +int32_t RtcRegisterAlarmCallback(DevHandle handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcRegisterAlarmCallback: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->RegisterAlarmCallback == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->RegisterAlarmCallback(host, alarmIndex, cb); } -int32_t RtcAlarmInterruptEnable(struct DevHandle *handle, enum RtcAlarmIndex alarmIndex, uint8_t enable) +int32_t RtcAlarmInterruptEnable(DevHandle handle, enum RtcAlarmIndex alarmIndex, uint8_t enable) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcAlarmInterruptEnable: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->AlarmInterruptEnable == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->AlarmInterruptEnable(host, alarmIndex, enable); } -int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq) +int32_t RtcGetFreq(DevHandle handle, uint32_t *freq) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcGetFreq: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->GetFreq == NULL) { HDF_LOGE("RtcGetFreq: pointer null"); return HDF_ERR_NOT_SUPPORT; @@ -186,60 +154,60 @@ int32_t RtcGetFreq(struct DevHandle *handle, uint32_t *freq) return host->method->GetFreq(host, freq); } -int32_t RtcSetFreq(struct DevHandle *handle, uint32_t freq) +int32_t RtcSetFreq(DevHandle handle, uint32_t freq) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcSetFreq: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->SetFreq == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->SetFreq(host, freq); } -int32_t RtcReset(struct DevHandle *handle) +int32_t RtcReset(DevHandle handle) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcReset: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->Reset == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->Reset(host); } -int32_t RtcReadReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t *value) +int32_t RtcReadReg(DevHandle handle, uint8_t usrDefIndex, uint8_t *value) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcReadReg: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->ReadReg == NULL) { return HDF_ERR_NOT_SUPPORT; } return host->method->ReadReg(host, usrDefIndex, value); } -int32_t RtcWriteReg(struct DevHandle *handle, uint8_t usrDefIndex, uint8_t value) +int32_t RtcWriteReg(DevHandle handle, uint8_t usrDefIndex, uint8_t value) { struct RtcHost *host = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("RtcReadReg: handle is null"); return HDF_ERR_INVALID_OBJECT; } - host = (struct RtcHost *)handle->object; + host = (struct RtcHost *)handle; if (host->method == NULL || host->method->WriteReg == NULL) { return HDF_ERR_NOT_SUPPORT; } diff --git a/support/platform/src/sdio_core.c b/support/platform/src/sdio_core.c old mode 100755 new mode 100644 index 904b4a85..990c460d --- a/support/platform/src/sdio_core.c +++ b/support/platform/src/sdio_core.c @@ -1,38 +1,14 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "device_resource_if.h" -#include "hdf_log.h" #include "osal_mem.h" +#include "plat_log.h" #include "sdio_core.h" #define HDF_LOG_TAG sdio_core @@ -104,7 +80,6 @@ int32_t SdioFillConfigData(struct HdfDeviceObject *device, struct SdioConfigData return ret; } - HDF_LOGD("SdioFillConfigData: Success! funcNum = %d, vendorId = 0x%x, deviceId = 0x%x.", - configData->funcNum, configData->vendorId, configData->deviceId); + PLAT_LOGV("SdioFillConfigData: Success! funcNum = %d", configData->funcNum); return HDF_SUCCESS; } diff --git a/support/platform/src/sdio_if.c b/support/platform/src/sdio_if.c old mode 100755 new mode 100644 index d0af50b7..24059a47 --- a/support/platform/src/sdio_if.c +++ b/support/platform/src/sdio_if.c @@ -1,38 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "devsvc_manager_clnt.h" #include "hdf_base.h" -#include "hdf_log.h" #include "osal_mem.h" +#include "plat_log.h" #include "securec.h" #include "sdio_core.h" @@ -68,9 +45,8 @@ static struct SdioCntlr *SdioGetCntlrByBusNum(int16_t busNum) return cntlr; } -struct DevHandle *SdioOpen(int16_t busNum) +DevHandle SdioOpen(int16_t busNum) { - struct DevHandle *handle = NULL; struct SdioCntlr *cntlr = NULL; int32_t ret; @@ -94,30 +70,21 @@ struct DevHandle *SdioOpen(int16_t busNum) return NULL; } - handle = OsalMemCalloc(sizeof(*handle)); - if (handle == NULL) { - HDF_LOGE("SdioOpen: OsalMemCalloc fail!"); - return NULL; - } - handle->object = cntlr; - HDF_LOGD("SdioOpen: Success!"); - return handle; + PLAT_LOGV("SdioOpen: Success!"); + return (DevHandle)cntlr; } -void SdioClose(struct DevHandle *handle) +void SdioClose(DevHandle handle) { - if (handle != NULL) { - handle->object = NULL; - OsalMemFree(handle); - } + (void)handle; } -int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, +int32_t SdioReadBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioReadBytes: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -126,21 +93,21 @@ int32_t SdioReadBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->incrAddrReadBytes == NULL) { HDF_LOGE("SdioReadBytes: method or incrAddrReadBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioReadBytes: Success!"); + PLAT_LOGV("SdioReadBytes: Success!"); return cntlr->method->incrAddrReadBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, +int32_t SdioWriteBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioWriteBytes: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -149,21 +116,21 @@ int32_t SdioWriteBytes(struct DevHandle *handle, uint8_t *data, uint32_t addr, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->incrAddrWriteBytes == NULL) { HDF_LOGE("SdioWriteBytes: method or incrAddrWriteBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioWriteBytes: Success!"); + PLAT_LOGV("SdioWriteBytes: Success!"); return cntlr->method->incrAddrWriteBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, +int32_t SdioReadBytesFromFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioReadBytesFromFixedAddr: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -172,21 +139,21 @@ int32_t SdioReadBytesFromFixedAddr(struct DevHandle *handle, uint8_t *data, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->fixedAddrReadBytes == NULL) { HDF_LOGE("SdioReadBytesFromFixedAddr: method or incrAddrWriteBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioReadBytesFromFixedAddr: Success!"); + PLAT_LOGV("SdioReadBytesFromFixedAddr: Success!"); return cntlr->method->fixedAddrReadBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, +int32_t SdioWriteBytesToFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioWriteBytesToFixedAddr: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -195,21 +162,21 @@ int32_t SdioWriteBytesToFixedAddr(struct DevHandle *handle, uint8_t *data, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->fixedAddrWriteBytes == NULL) { HDF_LOGE("SdioWriteBytesToFixedAddr: method or fixedAddrWriteBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioWriteBytesToFixedAddr: Success!"); + PLAT_LOGV("SdioWriteBytesToFixedAddr: Success!"); return cntlr->method->fixedAddrWriteBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, +int32_t SdioReadBytesFromFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioReadBytesFromFunc0: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -218,21 +185,21 @@ int32_t SdioReadBytesFromFunc0(struct DevHandle *handle, uint8_t *data, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->func0ReadBytes == NULL) { HDF_LOGE("SdioReadBytesFromFunc0: method or func0ReadBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioReadBytesFromFunc0: Success!"); + PLAT_LOGV("SdioReadBytesFromFunc0: Success!"); return cntlr->method->func0ReadBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, +int32_t SdioWriteBytesToFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t timeOut) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioWriteBytesToFunc0: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -241,38 +208,38 @@ int32_t SdioWriteBytesToFunc0(struct DevHandle *handle, uint8_t *data, return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->func0WriteBytes == NULL) { HDF_LOGE("SdioWriteBytesToFunc0: method or func0WriteBytes is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioWriteBytesToFunc0: Success!"); + PLAT_LOGV("SdioWriteBytesToFunc0: Success!"); return cntlr->method->func0WriteBytes(cntlr, data, addr, size, timeOut); } -int32_t SdioSetBlockSize(struct DevHandle *handle, uint32_t blockSize) +int32_t SdioSetBlockSize(DevHandle handle, uint32_t blockSize) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioSetBlockSize: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->setBlockSize == NULL) { HDF_LOGE("SdioSetBlockSize: method or setBlockSize is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioSetBlockSize: Success!"); + PLAT_LOGV("SdioSetBlockSize: Success!"); return cntlr->method->setBlockSize(cntlr, blockSize); } -int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +int32_t SdioGetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioGetCommonInfo: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -281,20 +248,20 @@ int32_t SdioGetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCo return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->getCommonInfo == NULL) { HDF_LOGE("SdioGetCommonInfo: method or getCommonInfo is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioGetCommonInfo: Success! infoType is %d.", infoType); + PLAT_LOGV("SdioGetCommonInfo: Success! infoType is %d.", infoType); return cntlr->method->getCommonInfo(cntlr, info, infoType); } -int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCommonInfoType infoType) +int32_t SdioSetCommonInfo(DevHandle handle, SdioCommonInfo *info, SdioCommonInfoType infoType) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioSetCommonInfo: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -303,110 +270,110 @@ int32_t SdioSetCommonInfo(struct DevHandle *handle, SdioCommonInfo *info, SdioCo return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->setCommonInfo == NULL) { HDF_LOGE("SdioSetCommonInfo: method or setCommonInfo is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioSetCommonInfo: Success! infoType is %d.", infoType); + PLAT_LOGV("SdioSetCommonInfo: Success! infoType is %d.", infoType); return cntlr->method->setCommonInfo(cntlr, info, infoType); } -int32_t SdioFlushData(struct DevHandle *handle) +int32_t SdioFlushData(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioFlushData: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->flushData == NULL) { HDF_LOGE("SdioFlushData: method or flushData is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioFlushData: Success!"); + PLAT_LOGV("SdioFlushData: Success!"); return cntlr->method->flushData(cntlr); } -void SdioClaimHost(struct DevHandle *handle) +void SdioClaimHost(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioClaimHost: handle or object is null!"); return; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->claimHost == NULL) { HDF_LOGE("SdioClaimHost: method or claimHost is null!"); return; } - HDF_LOGD("SdioClaimHost: Success!"); + PLAT_LOGV("SdioClaimHost: Success!"); cntlr->method->claimHost(cntlr); } -void SdioReleaseHost(struct DevHandle *handle) +void SdioReleaseHost(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioReleaseHost: handle or object is null!"); return; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->releaseHost == NULL) { HDF_LOGE("SdioReleaseHost: method or releaseHost is null!"); return; } - HDF_LOGD("SdioReleaseHost: Success!"); + PLAT_LOGV("SdioReleaseHost: Success!"); cntlr->method->releaseHost(cntlr); } -int32_t SdioEnableFunc(struct DevHandle *handle) +int32_t SdioEnableFunc(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioEnableFunc: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->enableFunc == NULL) { HDF_LOGE("SdioEnableFunc: method or enableFunc is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioEnableFunc: Success!"); + PLAT_LOGV("SdioEnableFunc: Success!"); return cntlr->method->enableFunc(cntlr); } -int32_t SdioDisableFunc(struct DevHandle *handle) +int32_t SdioDisableFunc(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioDisableFunc: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->disableFunc == NULL) { HDF_LOGE("SdioDisableFunc: method or disableFunc is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioDisableFunc: Success!"); + PLAT_LOGV("SdioDisableFunc: Success!"); return cntlr->method->disableFunc(cntlr); } -int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler) +int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler *irqHandler) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioClaimIrq: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } @@ -415,29 +382,29 @@ int32_t SdioClaimIrq(struct DevHandle *handle, SdioIrqHandler *irqHandler) return HDF_ERR_INVALID_PARAM; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->claimIrq == NULL) { HDF_LOGE("SdioClaimIrq: method or claimIrq is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioClaimIrq: Success!"); + PLAT_LOGV("SdioClaimIrq: Success!"); return cntlr->method->claimIrq(cntlr, irqHandler); } -int32_t SdioReleaseIrq(struct DevHandle *handle) +int32_t SdioReleaseIrq(DevHandle handle) { struct SdioCntlr *cntlr = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { HDF_LOGE("SdioReleaseIrq: handle or object is null!"); return HDF_ERR_INVALID_OBJECT; } - cntlr = (struct SdioCntlr *)handle->object; + cntlr = (struct SdioCntlr *)handle; if (cntlr->method == NULL || cntlr->method->releaseIrq == NULL) { HDF_LOGE("SdioReleaseIrq: method or releaseIrq is null!"); return HDF_ERR_NOT_SUPPORT; } - HDF_LOGD("SdioReleaseIrq: Success!"); + PLAT_LOGV("SdioReleaseIrq: Success!"); return cntlr->method->releaseIrq(cntlr); } diff --git a/support/platform/src/spi_core.c b/support/platform/src/spi_core.c old mode 100755 new mode 100644 index 91bd71de..29568ba2 --- a/support/platform/src/spi_core.c +++ b/support/platform/src/spi_core.c @@ -1,42 +1,56 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "spi_core.h" -#include #include "hdf_log.h" #include "osal_mem.h" #include "spi_if.h" #define HDF_LOG_TAG spi_core +int32_t SpiCntlrOpen(struct SpiCntlr *cntlr, uint32_t csNum) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->method == NULL || cntlr->method->Open == NULL) { + HDF_LOGE("%s: Open not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + (void)OsalMutexLock(&(cntlr->lock)); + cntlr->curCs = csNum; + ret = cntlr->method->Open(cntlr); + (void)OsalMutexUnlock(&(cntlr->lock)); + return ret; +} + +int32_t SpiCntlrClose(struct SpiCntlr *cntlr, uint32_t csNum) +{ + int32_t ret; + + if (cntlr == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (cntlr->method == NULL || cntlr->method->Close == NULL) { + HDF_LOGE("%s: Close not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + (void)OsalMutexLock(&(cntlr->lock)); + cntlr->curCs = csNum; + ret = cntlr->method->Close(cntlr); + (void)OsalMutexUnlock(&(cntlr->lock)); + return ret; +} + int32_t SpiCntlrTransfer(struct SpiCntlr *cntlr, uint32_t csNum, struct SpiMsg *msg, uint32_t count) { int32_t ret; @@ -125,6 +139,7 @@ struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device) cntlr->device = device; device->service = &(cntlr->service); (void)OsalMutexInit(&cntlr->lock); + DListHeadInit(&cntlr->list); cntlr->priv = NULL; return cntlr; } diff --git a/support/platform/src/spi_if.c b/support/platform/src/spi_if.c old mode 100755 new mode 100644 index cf54b022..45eb03af --- a/support/platform/src/spi_if.c +++ b/support/platform/src/spi_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "securec.h" @@ -65,18 +42,18 @@ static struct SpiCntlr *SpiGetCntlrByBusNum(uint32_t num) return cntlr; } -int32_t SpiTransfer(struct DevHandle *handle, struct SpiMsg *msgs, uint32_t count) +int32_t SpiTransfer(DevHandle handle, struct SpiMsg *msgs, uint32_t count) { struct SpiObject *obj = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { return HDF_ERR_INVALID_PARAM; } - obj = (struct SpiObject *)handle->object; + obj = (struct SpiObject *)handle; return SpiCntlrTransfer(obj->cntlr, obj->csNum, msgs, count); } -int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len) +int32_t SpiRead(DevHandle handle, uint8_t *buf, uint32_t len) { struct SpiMsg msg = {0}; @@ -86,7 +63,7 @@ int32_t SpiRead(struct DevHandle *handle, uint8_t *buf, uint32_t len) return SpiTransfer(handle, &msg, 1); } -int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len) +int32_t SpiWrite(DevHandle handle, uint8_t *buf, uint32_t len) { struct SpiMsg msg = {0}; @@ -96,44 +73,49 @@ int32_t SpiWrite(struct DevHandle *handle, uint8_t *buf, uint32_t len) return SpiTransfer(handle, &msg, 1); } -int32_t SpiSetCfg(struct DevHandle *handle, struct SpiCfg *cfg) +int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg) { struct SpiObject *obj = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - obj = (struct SpiObject *)handle->object; + obj = (struct SpiObject *)handle; return SpiCntlrSetCfg(obj->cntlr, obj->csNum, cfg); } -int32_t SpiGetCfg(struct DevHandle *handle, struct SpiCfg *cfg) +int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg) { struct SpiObject *obj = NULL; - if (handle == NULL || handle->object == NULL) { + if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - obj = (struct SpiObject *)handle->object; + obj = (struct SpiObject *)handle; return SpiCntlrGetCfg(obj->cntlr, obj->csNum, cfg); } -void SpiClose(struct DevHandle *handle) +void SpiClose(DevHandle handle) { + int32_t ret; + struct SpiObject *obj = NULL; + if (handle == NULL) { HDF_LOGE("%s: handle is NULL", __func__); return; } - if (handle->object != NULL) { - OsalMemFree(handle->object); - handle->object = NULL; + + obj = (struct SpiObject *)handle; + ret = SpiCntlrClose(obj->cntlr, obj->csNum); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret is %d", __func__, ret); } OsalMemFree(handle); } -struct DevHandle *SpiOpen(const struct SpiDevInfo *info) +DevHandle SpiOpen(const struct SpiDevInfo *info) { - struct DevHandle *handle = NULL; + int32_t ret; struct SpiObject *object = NULL; struct SpiCntlr *cntlr = NULL; @@ -145,19 +127,19 @@ struct DevHandle *SpiOpen(const struct SpiDevInfo *info) HDF_LOGE("%s: cntlr is null", __func__); return NULL; } - handle = (struct DevHandle *)OsalMemCalloc(sizeof(*handle)); - if (handle == NULL) { - HDF_LOGE("%s: handle malloc error", __func__); + + 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__); - OsalMemFree(handle); return NULL; } object->cntlr = cntlr; object->csNum = info->csNum; - handle->object = object; - return handle; + return (DevHandle)object; } diff --git a/support/platform/src/uart_core.c b/support/platform/src/uart_core.c old mode 100755 new mode 100644 index 6bea0e0d..524ad61f --- a/support/platform/src/uart_core.c +++ b/support/platform/src/uart_core.c @@ -1,42 +1,211 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "uart_core.h" -#include #include "hdf_log.h" #include "osal_mem.h" #include "uart_if.h" #define HDF_LOG_TAG uart_core +int32_t UartHostInit(struct UartHost *host) +{ + int32_t ret; + + if (host == NULL || host->method == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (OsalAtomicRead(&host->atom) == 1) { + return HDF_ERR_DEVICE_BUSY; + } + OsalAtomicInc(&host->atom); + if (host->method->Init != NULL) { + ret = host->method->Init(host); + if (ret != HDF_SUCCESS) { + OsalAtomicDec(&host->atom); + return ret; + } + } + return HDF_SUCCESS; +} + +int32_t UartHostDeinit(struct UartHost *host) +{ + int32_t ret; + + if (host == NULL || host->method == NULL) { + return HDF_ERR_INVALID_PARAM; + } + if (host->method->Deinit != NULL) { + ret = host->method->Deinit(host); + if (ret != HDF_SUCCESS) { + return ret; + } + } + OsalAtomicDec(&host->atom); + return HDF_SUCCESS; +} + +static int32_t UartUserRead(struct UartHost *host, struct HdfSBuf *reply) +{ + size_t size; + int32_t len; + uint8_t *buf = NULL; + + size = HdfSbufGetCapacity(reply); + if (size == 0) { + HDF_LOGE("%s: the size of Sbuf is 0", __func__); + return HDF_ERR_INVALID_PARAM; + } + buf = (uint8_t *)OsalMemCalloc(sizeof(*buf) * size); + if (buf == NULL) { + HDF_LOGE("%s: OsalMemCalloc error", __func__); + return HDF_ERR_MALLOC_FAIL; + } + len = UartHostRead(host, buf, size); + if (len <= 0) { + HDF_LOGE("%s: UartHostRead error, len is %d", __func__, len); + OsalMemFree(buf); + return len; + } + if (!HdfSbufWriteBuffer(reply, buf, len)) { + HDF_LOGE("%s: sbuf write buffer failed", __func__); + return HDF_ERR_IO; + } + OsalMemFree(buf); + return HDF_SUCCESS; +} + +static int32_t UartUserWrite(struct UartHost *host, struct HdfSBuf *data) +{ + size_t size; + uint8_t *buf = NULL; + + if (!HdfSbufReadBuffer(data, (const void **)&buf, &size)) { + HDF_LOGE("%s: sbuf read buffer failed", __func__); + return HDF_ERR_IO; + } + return UartHostWrite(host, buf, size); +} + +static int32_t UartUserGetBaud(struct UartHost *host, struct HdfSBuf *reply) +{ + int32_t ret; + uint32_t baudRate; + + ret = UartHostGetBaud(host, &baudRate); + if (ret != HDF_SUCCESS) { + return ret; + } + if (!HdfSbufWriteBuffer(reply, &baudRate, sizeof(baudRate))) { + HDF_LOGE("%s: sbuf write buffer failed", __func__); + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t UartUserSetBaud(struct UartHost *host, struct HdfSBuf *data) +{ + size_t size; + uint32_t *baudRate = NULL; + + if (!HdfSbufReadBuffer(data, (const void **)&baudRate, &size)) { + HDF_LOGE("%s: sbuf read buffer failed", __func__); + return HDF_ERR_IO; + } + return UartHostSetBaud(host, *baudRate); +} + +static int32_t UartUserGetAttribute(struct UartHost *host, struct HdfSBuf *reply) +{ + int32_t ret; + struct UartAttribute attribute; + + ret = UartHostGetAttribute(host, &attribute); + if (ret != HDF_SUCCESS) { + return ret; + } + if (!HdfSbufWriteBuffer(reply, &attribute, sizeof(attribute))) { + HDF_LOGE("%s: sbuf write buffer failed", __func__); + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t UartUserSetAttribute(struct UartHost *host, struct HdfSBuf *data) +{ + size_t size; + struct UartAttribute *attribute = NULL; + + if (!HdfSbufReadBuffer(data, (const void **)&attribute, &size)) { + HDF_LOGE("%s: sbuf read buffer failed", __func__); + return HDF_ERR_IO; + } + return UartHostSetAttribute(host, attribute); +} + +static int32_t UartUserSetTransMode(struct UartHost *host, struct HdfSBuf *data) +{ + size_t size; + enum UartTransMode *mode = NULL; + + if (!HdfSbufReadBuffer(data, (const void **)&mode, &size)) { + HDF_LOGE("%s: sbuf read buffer failed", __func__); + return HDF_ERR_IO; + } + return UartHostSetTransMode(host, *mode); +} + +static int32_t UartIoDispatch(struct HdfDeviceIoClient *client, int cmd, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct UartHost *host = NULL; + + if (client == NULL) { + HDF_LOGE("%s: client is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + if (client->device == NULL) { + HDF_LOGE("%s: client->device is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + if (client->device->service == NULL) { + HDF_LOGE("%s: client->device->service is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + host = (struct UartHost *)client->device->service; + switch (cmd) { + case UART_IO_INIT: + return UartHostInit(host); + case UART_IO_DEINIT: + return UartHostDeinit(host); + case UART_IO_READ: + return UartUserRead(host, reply); + case UART_IO_WRITE: + return UartUserWrite(host, data); + case UART_IO_GET_BAUD: + return UartUserGetBaud(host, reply); + case UART_IO_SET_BAUD: + return UartUserSetBaud(host, data); + case UART_IO_GET_ATTRIBUTE: + return UartUserGetAttribute(host, reply); + case UART_IO_SET_ATTRIBUTE: + return UartUserSetAttribute(host, data); + case UART_IO_SET_TRANSMODE: + return UartUserSetTransMode(host, data); + default: + return HDF_ERR_NOT_SUPPORT; + } +} + void UartHostDestroy(struct UartHost *host) { if (host == NULL) { @@ -60,6 +229,8 @@ struct UartHost *UartHostCreate(struct HdfDeviceObject *device) } host->device = device; device->service = &(host->service); + host->device->service->Dispatch = UartIoDispatch; + OsalAtomicSet(&host->atom, 0); host->priv = NULL; host->method = NULL; return host; diff --git a/support/platform/src/uart_if.c b/support/platform/src/uart_if.c old mode 100755 new mode 100644 index e1a8018b..94eae00e --- a/support/platform/src/uart_if.c +++ b/support/platform/src/uart_if.c @@ -1,49 +1,32 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "securec.h" +#ifndef __USER__ #include "devsvc_manager_clnt.h" +#else +#include "hdf_io_service_if.h" +#endif #include "hdf_log.h" #include "osal_mem.h" +#ifndef __USER__ #include "uart_core.h" +#endif #include "uart_if.h" #define HDF_LOG_TAG uart_if_c #define UART_HOST_NAME_LEN 32 -static struct UartHost *UartGetHostByBusNum(uint32_t num) +static void *UartGetObjGetByBusNum(uint32_t num) { int ret; + void *obj = NULL; char *name = NULL; - struct UartHost *host = NULL; name = (char *)OsalMemCalloc(UART_HOST_NAME_LEN + 1); if (name == NULL) { @@ -56,99 +39,218 @@ static struct UartHost *UartGetHostByBusNum(uint32_t num) OsalMemFree(name); return NULL; } - host = (struct UartHost *)DevSvcManagerClntGetService(name); + +#ifdef __USER__ + obj = (void *)HdfIoServiceBind(name); +#else + obj = (void *)DevSvcManagerClntGetService(name); +#endif OsalMemFree(name); - return host; + return obj; } -struct DevHandle *UartOpen(uint32_t port) +static void UartPutObjByPointer(const void *obj) { - struct DevHandle *handle = NULL; - struct UartHost *host = NULL; - - host = UartGetHostByBusNum(port); - if (host == NULL) { - HDF_LOGE("%s: get host error", __func__); - return NULL; + if (obj == NULL) { + return; } - handle = (struct DevHandle *)OsalMemCalloc(sizeof(*handle)); +#ifdef __USER__ + HdfIoServiceRecycle((struct HdfIoService *)obj); +#endif +}; + +DevHandle UartOpen(uint32_t port) +{ + int32_t ret; + void *handle = NULL; + + handle = UartGetObjGetByBusNum(port); if (handle == NULL) { - HDF_LOGE("%s: handle malloc error", __func__); + HDF_LOGE("%s: get handle error", __func__); return NULL; } - if (UartHostInit(host) != HDF_SUCCESS) { - HDF_LOGE("%s: UartHostInit error", __func__); - OsalMemFree(handle); + +#ifdef __USER__ + struct HdfIoService *service = (struct HdfIoService *)handle; + if (service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("%s: service is invalid", __func__); + UartPutObjByPointer(handle); return NULL; } - handle->object = host; - return handle; + ret = service->dispatcher->Dispatch(&service->object, UART_IO_INIT, NULL, NULL); +#else + ret = UartHostInit((struct UartHost *)handle); +#endif + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: UartHostInit error, ret %d", __func__, ret); + UartPutObjByPointer(handle); + return NULL; + } + + return (DevHandle)handle; } -void UartClose(struct DevHandle *handle) +void UartClose(DevHandle handle) { + int32_t ret; if (handle == NULL) { HDF_LOGE("%s: handle is NULL", __func__); return; } - if (UartHostDeinit((struct UartHost *)handle->object) != HDF_SUCCESS) { - HDF_LOGE("%s: UartHostDeinit error", __func__); + +#ifdef __USER__ + struct HdfIoService *service = (struct HdfIoService *)handle; + if (service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("%s: service is invalid", __func__); + UartPutObjByPointer(handle); + return; } - OsalMemFree(handle); + ret = service->dispatcher->Dispatch(&service->object, UART_IO_DEINIT, NULL, NULL); +#else + ret = UartHostDeinit((struct UartHost *)handle); +#endif + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: UartHostDeinit error, ret %d", __func__, ret); + } + UartPutObjByPointer(handle); } -int32_t UartRead(struct DevHandle *handle, uint8_t *data, uint32_t size) +#ifdef __USER__ +static int32_t UartUserReceive(DevHandle handle, void *data, uint32_t size, enum UartIoCmd cmd) { - if (handle == NULL) { + int32_t ret; + uint32_t rLen; + const void *rBuf = NULL; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = (struct HdfIoService *)handle; + + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("%s: service is invalid", __func__); return HDF_ERR_INVALID_PARAM; } - return UartHostRead((struct UartHost *)handle->object, data, size); + /* Four bits are used to store the buffer length, and four bits are used to align the memory. */ + reply = HdfSBufObtain(size + sizeof(uint64_t)); + if (reply == NULL) { + HDF_LOGE("%s: failed to obtain reply", __func__); + return HDF_ERR_MALLOC_FAIL; + } + ret = service->dispatcher->Dispatch(&service->object, cmd, NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed to read, ret %d", __func__, ret); + goto __EXIT; + } + if (!HdfSbufReadBuffer(reply, &rBuf, &rLen)) { + HDF_LOGE("%s: sbuf read buffer failed", __func__); + ret = HDF_ERR_IO; + goto __EXIT; + } + if (size != rLen && cmd != UART_IO_READ) { + HDF_LOGE("%s: read error, size %u, rLen %u", __func__, size, rLen); + ret = HDF_FAILURE; + goto __EXIT; + } + if (memcpy_s(data, size, rBuf, rLen) != EOK) { + HDF_LOGE("%s: memcpy rBuf failed", __func__); + ret = HDF_ERR_IO; + goto __EXIT; + } + if (cmd == UART_IO_READ) { + ret = rLen; + } +__EXIT: + HdfSBufRecycle(reply); + return ret; } -int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size) +static int32_t UartUserSend(DevHandle handle, void *data, uint32_t size, enum UartIoCmd cmd) { - if (handle == NULL) { + int32_t ret; + struct HdfSBuf *buf = NULL; + struct HdfIoService *service = (struct HdfIoService *)handle; + + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("%s: service is invalid", __func__); return HDF_ERR_INVALID_PARAM; } - return UartHostWrite((struct UartHost *)handle->object, data, size); + buf = HdfSBufObtain(size); + if (buf == NULL) { + HDF_LOGE("%s: failed to obtain buf", __func__); + return HDF_ERR_MALLOC_FAIL; + } + if (!HdfSbufWriteBuffer(buf, data, size)) { + HDF_LOGE("%s: sbuf write buffer failed", __func__); + HdfSBufRecycle(buf); + return HDF_ERR_IO; + } + + ret = service->dispatcher->Dispatch(&service->object, cmd, buf, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed to write, ret %d", __func__, ret); + } + HdfSBufRecycle(buf); + return ret; +} +#endif + +int32_t UartRead(DevHandle handle, uint8_t *data, uint32_t size) +{ +#ifdef __USER__ + return UartUserReceive(handle, data, size, UART_IO_READ); +#else + return UartHostRead((struct UartHost *)handle, data, size); +#endif } -int32_t UartGetBaud(struct DevHandle *handle, uint32_t *baudRate) +int32_t UartWrite(DevHandle handle, uint8_t *data, uint32_t size) { - if (handle == NULL) { - return HDF_ERR_INVALID_PARAM; - } - return UartHostGetBaud((struct UartHost *)handle->object, baudRate); +#ifdef __USER__ + return UartUserSend(handle, data, size, UART_IO_WRITE); +#else + return UartHostWrite((struct UartHost *)handle, data, size); +#endif } -int32_t UartSetBaud(struct DevHandle *handle, uint32_t baudRate) +int32_t UartGetBaud(DevHandle handle, uint32_t *baudRate) { - if (handle == NULL) { - return HDF_ERR_INVALID_PARAM; - } - return UartHostSetBaud((struct UartHost *)handle->object, baudRate); +#ifdef __USER__ + return UartUserReceive(handle, baudRate, sizeof(*baudRate), UART_IO_GET_BAUD); +#else + return UartHostGetBaud((struct UartHost *)handle, baudRate); +#endif } -int32_t UartGetAttribute(struct DevHandle *handle, struct UartAttribute *attribute) +int32_t UartSetBaud(DevHandle handle, uint32_t baudRate) { - if (handle == NULL) { - return HDF_ERR_INVALID_PARAM; - } - return UartHostGetAttribute((struct UartHost *)handle->object, attribute); +#ifdef __USER__ + return UartUserSend(handle, &baudRate, sizeof(baudRate), UART_IO_SET_BAUD); +#else + return UartHostSetBaud((struct UartHost *)handle, baudRate); +#endif } -int32_t UartSetAttribute(struct DevHandle *handle, struct UartAttribute *attribute) +int32_t UartGetAttribute(DevHandle handle, struct UartAttribute *attribute) { - if (handle == NULL) { - return HDF_ERR_INVALID_PARAM; - } - return UartHostSetAttribute((struct UartHost *)handle->object, attribute); +#ifdef __USER__ + return UartUserReceive(handle, attribute, sizeof(*attribute), UART_IO_GET_ATTRIBUTE); +#else + return UartHostGetAttribute((struct UartHost *)handle, attribute); +#endif } -int32_t UartSetTransMode(struct DevHandle *handle, enum UartTransMode mode) +int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute) { - if (handle == NULL) { - return HDF_ERR_INVALID_PARAM; - } - return UartHostSetTransMode((struct UartHost *)handle->object, mode); +#ifdef __USER__ + return UartUserSend(handle, attribute, sizeof(*attribute), UART_IO_SET_ATTRIBUTE); +#else + return UartHostSetAttribute((struct UartHost *)handle, attribute); +#endif +} + +int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode) +{ +#ifdef __USER__ + return UartUserSend(handle, &mode, sizeof(mode), UART_IO_SET_TRANSMODE); +#else + return UartHostSetTransMode((struct UartHost *)handle, mode); +#endif } diff --git a/support/platform/src/watchdog_core.c b/support/platform/src/watchdog_core.c old mode 100755 new mode 100644 index 93e873ba..ba522098 --- a/support/platform/src/watchdog_core.c +++ b/support/platform/src/watchdog_core.c @@ -1,36 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "watchdog_core.h" -#include #include "hdf_log.h" #include "osal_mem.h" @@ -79,6 +55,26 @@ void WatchdogCntlrRemove(struct WatchdogCntlr *cntlr) (void)OsalSpinDestroy(&cntlr->lock); } +void WatchdogGetPrivData(struct WatchdogCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL) { + return; + } + if (cntlr->ops->getPriv != NULL) { + cntlr->ops->getPriv(cntlr); + } +} + +void WatchdogReleasePriv(struct WatchdogCntlr *cntlr) +{ + if (cntlr == NULL || cntlr->ops == NULL) { + return; + } + if (cntlr->ops->releasePriv != NULL) { + cntlr->ops->releasePriv(cntlr); + } +} + int32_t WatchdogCntlrGetStatus(struct WatchdogCntlr *cntlr, int32_t *status) { int32_t ret; diff --git a/support/platform/src/watchdog_if.c b/support/platform/src/watchdog_if.c old mode 100755 new mode 100644 index c00431f8..cf317f5f --- a/support/platform/src/watchdog_if.c +++ b/support/platform/src/watchdog_if.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "watchdog_if.h" @@ -70,75 +47,68 @@ static struct Watchdog *WatchdogGetById(int16_t wdtId) } -struct DevHandle *WatchdogOpen(int16_t wdtId) +DevHandle WatchdogOpen(int16_t wdtId) { - struct DevHandle *handle = NULL; struct Watchdog *service = NULL; service = WatchdogGetById(wdtId); if (service == NULL) { return NULL; } - handle = OsalMemCalloc(sizeof(*handle)); - if (handle == NULL) { - return NULL; - } - handle->object = service; - return handle; + WatchdogGetPrivData((struct WatchdogCntlr *)service); + return (DevHandle)service; } -void WatchdogClose(struct DevHandle *handle) +void WatchdogClose(DevHandle handle) { - if (handle != NULL) { - handle->object = NULL; - OsalMemFree(handle); - } + WatchdogReleasePriv((struct WatchdogCntlr *)handle); + (void)handle; } -int32_t WatchdogGetStatus(struct DevHandle *handle, int32_t *status) +int32_t WatchdogGetStatus(DevHandle handle, int32_t *status) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrGetStatus((struct WatchdogCntlr *)handle->object, status); + return WatchdogCntlrGetStatus((struct WatchdogCntlr *)handle, status); } -int32_t WatchdogStart(struct DevHandle *handle) +int32_t WatchdogStart(DevHandle handle) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrStart((struct WatchdogCntlr *)handle->object); + return WatchdogCntlrStart((struct WatchdogCntlr *)handle); } -int32_t WatchdogStop(struct DevHandle *handle) +int32_t WatchdogStop(DevHandle handle) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrStop((struct WatchdogCntlr *)handle->object); + return WatchdogCntlrStop((struct WatchdogCntlr *)handle); } -int32_t WatchdogSetTimeout(struct DevHandle *handle, uint32_t seconds) +int32_t WatchdogSetTimeout(DevHandle handle, uint32_t seconds) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrSetTimeout((struct WatchdogCntlr *)handle->object, seconds); + return WatchdogCntlrSetTimeout((struct WatchdogCntlr *)handle, seconds); } -int32_t WatchdogGetTimeout(struct DevHandle *handle, uint32_t *seconds) +int32_t WatchdogGetTimeout(DevHandle handle, uint32_t *seconds) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrGetTimeout((struct WatchdogCntlr *)handle->object, seconds); + return WatchdogCntlrGetTimeout((struct WatchdogCntlr *)handle, seconds); } -int32_t WatchdogFeed(struct DevHandle *handle) +int32_t WatchdogFeed(DevHandle handle) { if (handle == NULL) { return HDF_ERR_INVALID_OBJECT; } - return WatchdogCntlrFeed((struct WatchdogCntlr *)handle->object); + return WatchdogCntlrFeed((struct WatchdogCntlr *)handle); } diff --git a/support/platform/test/unittest/common/hdf_emmc_test.cpp b/support/platform/test/unittest/common/hdf_emmc_test.cpp new file mode 100644 index 00000000..1d4cf1aa --- /dev/null +++ b/support/platform/test/unittest/common/hdf_emmc_test.cpp @@ -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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "emmc_if.h" +#include "hdf_io_service_if.h" +#include "hdf_uhdf_test.h" + +using namespace testing::ext; + +enum EmmcTestCmd { + EMMC_GET_CID_01 = 0, +}; + +class HdfLiteEmmcTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteEmmcTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteEmmcTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteEmmcTest::SetUp() +{ +} + +void HdfLiteEmmcTest::TearDown() +{ +} + +static void TestUserEmmcGetCid(void) +{ + uint8_t cid[EMMC_CID_LEN] = {0}; + uint32_t i; + + 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]); + } +} + +/** + * @tc.name: EmmcGetCid001 + * @tc.desc: test EmmcGetCid/EmmcGetHuid interface in kernel and user status. + * @tc.type: FUNC + * @tc.require: AR000F5LSD AR000F5LV3 + */ +HWTEST_F(HdfLiteEmmcTest, EmmcGetCid001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_EMMC_TYPE, EMMC_GET_CID_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + TestUserEmmcGetCid(); +} diff --git a/support/platform/test/unittest/common/hdf_gpio_test.cpp b/support/platform/test/unittest/common/hdf_gpio_test.cpp new file mode 100644 index 00000000..7584fc10 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_gpio_test.cpp @@ -0,0 +1,128 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +// pal gpio test case number +enum GpioTestCmd { + GPIO_TEST_SET_GET_DIR = 0, + GPIO_TEST_WRITE_READ = 1, + GPIO_TEST_IRQ_LEVEL = 2, + GPIO_TEST_IRQ_EDGE = 3, + GPIO_TEST_IRQ_THREAD = 4, + GPIO_TEST_RELIABILITY = 5, + GPIO_TEST_MAX = 6, +}; + +class HdfLiteGpioTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteGpioTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteGpioTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteGpioTest::SetUp() +{ +} + +void HdfLiteGpioTest::TearDown() +{ +} + +/** + * @tc.name: GpioTestSetGetDir001 + * @tc.desc: gpio set and get dir test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestSetGetDir001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_SET_GET_DIR, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: GpioTestWriteRead001 + * @tc.desc: gpio write and read test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestWriteRead001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_WRITE_READ, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: GpioTestIrqLevel001 + * @tc.desc: gpio level irq trigger test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestIrqLevel001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_IRQ_LEVEL, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: GpioTestIrqEdge001 + * @tc.desc: gpio edge irq trigger test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestIrqEdge001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_IRQ_EDGE, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: GpioTestIrqThread001 + * @tc.desc: gpio thread irq trigger test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestIrqThread001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_IRQ_THREAD, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: GpioTestReliability001 + * @tc.desc: gpio reliability test + * @tc.type: FUNC + * @tc.require: AR000F868H + */ +HWTEST_F(HdfLiteGpioTest, GpioTestReliability001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_GPIO_TYPE, GPIO_TEST_RELIABILITY, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} diff --git a/support/platform/test/unittest/common/hdf_i2c_test.cpp b/support/platform/test/unittest/common/hdf_i2c_test.cpp new file mode 100644 index 00000000..3bc5b21e --- /dev/null +++ b/support/platform/test/unittest/common/hdf_i2c_test.cpp @@ -0,0 +1,124 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "i2c_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +class HdfLiteI2cTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteI2cTest::SetUpTestCase() +{ + int32_t ret; + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_SETUP_ALL, -1}; + HdfTestOpenService(); + HdfTestSendMsgToService(&msg); + + ret = I2cTestExecute(I2C_TEST_CMD_SETUP_ALL); + if (ret != 0) { + printf("%s: User SetUp FAIL:%d\n\r", __func__, ret); + } + printf("%s: exit!\n", __func__); +} + +void HdfLiteI2cTest::TearDownTestCase() +{ + int32_t ret; + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_TEARDOWN_ALL, -1}; + HdfTestSendMsgToService(&msg); + HdfTestCloseService(); + + ret = I2cTestExecute(I2C_TEST_CMD_TEARDOWN_ALL); + if (ret != 0) { + printf("%s: User TearDown FAIL:%d\n\r", __func__, ret); + } + printf("%s: exit!\n", __func__); +} + +void HdfLiteI2cTest::SetUp() +{ +} + +void HdfLiteI2cTest::TearDown() +{ +} + +/** + * @tc.name: HdfLiteI2cTestTransfer001 + * @tc.desc: i2c transfer test + * @tc.type: FUNC + * @tc.require: AR000F8688 + */ +HWTEST_F(HdfLiteI2cTest, HdfLiteI2cTestTransfer001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_TRANSFER, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + printf("%s: kernel test done, then for user...\n", __func__); + EXPECT_EQ(0, I2cTestExecute(I2C_TEST_CMD_TRANSFER)); + printf("%s: exit!\n", __func__); +} + +/** + * @tc.name: HdfLiteI2cTestWriteRead001 + * @tc.desc: i2c write and read test + * @tc.type: FUNC + * @tc.require: AR000F8688 + */ +HWTEST_F(HdfLiteI2cTest, HdfLiteI2cTestWriteRead001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_WRITE_READ, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + printf("%s: kernel test done, then for user...\n", __func__); + EXPECT_EQ(0, I2cTestExecute(I2C_TEST_CMD_WRITE_READ)); + printf("%s: exit!\n", __func__); +} + +/** + * @tc.name: HdfLiteI2cTestMultiThread001 + * @tc.desc: i2c multithread test + * @tc.type: FUNC + * @tc.require: AR000F8688 + */ +HWTEST_F(HdfLiteI2cTest, HdfLiteI2cTestMultiThread001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_MULTI_THREAD, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + printf("%s: kernel test done, then for user...\n", __func__); + EXPECT_EQ(0, I2cTestExecute(I2C_TEST_CMD_MULTI_THREAD)); + printf("%s: exit!\n", __func__); +} + +/** + * @tc.name: HdfLiteI2cTestReliability001 + * @tc.desc: i2c reliability test + * @tc.type: FUNC + * @tc.require: AR000F8688 + */ +HWTEST_F(HdfLiteI2cTest, HdfLiteI2cTestReliability001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_I2C_TYPE, I2C_TEST_CMD_RELIABILITY, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + printf("%s: kernel test done, then for user...\n", __func__); + EXPECT_EQ(0, I2cTestExecute(I2C_TEST_CMD_RELIABILITY)); + printf("%s: exit!\n", __func__); +} diff --git a/support/platform/test/unittest/common/hdf_mipi_dsi_test.cpp b/support/platform/test/unittest/common/hdf_mipi_dsi_test.cpp new file mode 100644 index 00000000..db7e2bf6 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_mipi_dsi_test.cpp @@ -0,0 +1,107 @@ +/* + * 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_uhdf_test.h" +#include +#include +#include +#include +#include +#include +#include +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +// pal mipi dsi test case number +enum MipiDsiTestCmd { + MIPI_DSI_TEST_SET_CFG = 0, + MIPI_DSI_TEST_GET_CFG = 1, + MIPI_DSI_TEST_TX_RX = 2, + MIPI_DSI_TEST_TO_LP_TO_HS = 3, + MIPI_DSI_TEST_ENTER_ULPS_EXIT_ULPS = 4, + MIPI_DSI_TEST_POWER_CONTROL = 5, + MIPI_DSI_TEST_MAX = 6, +}; + +class HdfLiteMipiDsiTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteMipiDsiTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteMipiDsiTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteMipiDsiTest::SetUp() +{ +} + +void HdfLiteMipiDsiTest::TearDown() +{ +} + +static void MipiDsiTest(enum MipiDsiTestCmd cmd) +{ + struct HdfTestMsg msg = {TEST_PAL_MIPI_DSI_TYPE, (uint8_t)cmd, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: MipiDsiSetCfgTest001 + * @tc.desc: mipi dsi function test + * @tc.type: FUNC + * @tc.require: AR000F868F + */ +HWTEST_F(HdfLiteMipiDsiTest, MipiDsiSetCfgTest001, TestSize.Level0) +{ + MipiDsiTest(MIPI_DSI_TEST_SET_CFG); +} + +/** + * @tc.name: MipiDsiGetCfgTest001 + * @tc.desc: mipi dsi function test + * @tc.type: FUNC + * @tc.require: AR000F868F + */ +HWTEST_F(HdfLiteMipiDsiTest, MipiDsiGetCfgTest001, TestSize.Level0) +{ + MipiDsiTest(MIPI_DSI_TEST_GET_CFG); +} + +/** + * @tc.name: MipiDsiTxRxTest001 + * @tc.desc: mipi dsi function test + * @tc.type: FUNC + * @tc.require: AR000F868F + */ +HWTEST_F(HdfLiteMipiDsiTest, MipiDsiTxRxTest001, TestSize.Level0) +{ + MipiDsiTest(MIPI_DSI_TEST_TX_RX); +} + +/** + * @tc.name: MipiDsiLpHsTest001 + * @tc.desc: mipi dsi function test + * @tc.type: FUNC + * @tc.require: AR000F868F + */ +HWTEST_F(HdfLiteMipiDsiTest, MipiDsiLpHsTest001, TestSize.Level0) +{ + MipiDsiTest(MIPI_DSI_TEST_TO_LP_TO_HS); +} + diff --git a/support/platform/test/unittest/common/hdf_pwm_test.cpp b/support/platform/test/unittest/common/hdf_pwm_test.cpp new file mode 100644 index 00000000..bf8d33b5 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_pwm_test.cpp @@ -0,0 +1,140 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" + +using namespace testing::ext; + +enum PwmTestCmd { + PWM_SET_PERIOD_TEST = 0, + PWM_SET_DUTY_TEST, + PWM_SET_POLARITY_TEST, + PWM_ENABLE_TEST, + PWM_DISABLE_TEST, + PWM_SET_CONFIG_TEST, + PWM_GET_CONFIG_TEST, + PWM_RELIABILITY_TEST, + PWM_TEST_ALL, +}; + +class HdfLitePwmTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLitePwmTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLitePwmTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLitePwmTest::SetUp() +{ +} + +void HdfLitePwmTest::TearDown() +{ +} + +/** + * @tc.name: PwmSetPeriodTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868C + */ +HWTEST_F(HdfLitePwmTest, PwmSetPeriodTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_SET_PERIOD_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmSetDutyTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868C + */ +HWTEST_F(HdfLitePwmTest, PwmSetDutyTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_SET_DUTY_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmSetPolarityTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868C + */ +HWTEST_F(HdfLitePwmTest, PwmSetPolarityTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_PWM_TYPE, PWM_SET_POLARITY_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmSetConfigTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868D + */ +HWTEST_F(HdfLitePwmTest, PwmSetConfigTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_SET_CONFIG_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmGetConfigTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868D + */ +HWTEST_F(HdfLitePwmTest, PwmGetConfigTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_GET_CONFIG_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmEnableTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868D + */ +HWTEST_F(HdfLitePwmTest, PwmEnableTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_ENABLE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PwmDisableTest001 + * @tc.desc: pwm function test + * @tc.type: FUNC + * @tc.require: AR000F868D + */ +HWTEST_F(HdfLitePwmTest, PwmDisableTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_PWM_TYPE, PWM_DISABLE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} diff --git a/support/platform/test/unittest/common/hdf_rtc_test.cpp b/support/platform/test/unittest/common/hdf_rtc_test.cpp new file mode 100644 index 00000000..f55ae565 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_rtc_test.cpp @@ -0,0 +1,281 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +// pal rtc test case number +enum HdfRtcTestCaseCmd { + RTC_INIT, + RTC_UNINIT, + RTC_WR_TIME, + RTC_WR_MAX_TIME, + RTC_WR_MIN_TIME, + RTC_WR_ALARM_TIME, + RTC_WR_ALARM_MAX_TIME, + RTC_WR_ALARM_MIN_TIME, + RTC_ALARM_ENABLE, + RTC_ALARM_IRQ, + RTC_REGISTER_CALLBACK, + RTC_REGISTER_CALLBACK_NULL, + RTC_WR_FREQ, + RTC_WR_MAX_FREQ, + RTC_WR_MIN_FREQ, + RTC_WR_USER_REG, + RTC_WR_USER_REG_MAX_INDEX, + RTC_WR_RELIABILITY, + RTC_FUNCTION_TEST, +}; + +class HdfRtcTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfRtcTest::SetUpTestCase() +{ + HdfTestOpenService(); + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_INIT, -1 }; + HdfTestSendMsgToService(&msg); + +} + +void HdfRtcTest::TearDownTestCase() +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_UNINIT, -1 }; + HdfTestSendMsgToService(&msg); + HdfTestCloseService(); +} + +void HdfRtcTest::SetUp() +{ +} + +void HdfRtcTest::TearDown() +{ +} + +/** + * @tc.name: testRtcReadWriteTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcReadWriteMaxTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteMaxTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_MAX_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcReadWriteMinTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteMinTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_MIN_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcReadWriteAlarmTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteAlarmTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_ALARM_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcReadWriteAlarmMaxTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteAlarmMaxTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_ALARM_MAX_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} +/** + * @tc.name: testRtcReadWriteAlarmMinTime001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcReadWriteAlarmMinTime001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_ALARM_MIN_TIME, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +#ifndef HDF_LITEOS_TEST +/** + * @tc.name: testRtcAlarmEnable001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000F868I + */ +HWTEST_F(HdfRtcTest, testRtcAlarmEnable001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_ALARM_ENABLE, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} +#endif + +#if defined(HDF_LITEOS_TEST) +/** + * @tc.name: testRtcAlarmIqr001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcAlarmIqr001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_ALARM_IRQ, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcRegCallback001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcRegCallback001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_REGISTER_CALLBACK, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcRegCallbackNull001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcRegCallbackNull001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_REGISTER_CALLBACK_NULL, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcFreq001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcFreq001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_FREQ, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcMaxFreq001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcMaxFreq001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_MAX_FREQ, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcMinFreq001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcMinFreq001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_MIN_FREQ, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcUserReg001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcUserReg001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_USER_REG, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: testRtcUserRegMaxIndex001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcUserRegMaxIndex001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_USER_REG_MAX_INDEX, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} +#endif +/** + * @tc.name: testRtcReliability001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcReliability001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_WR_RELIABILITY, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +#if defined(HDF_LITEOS_TEST) +/** + * @tc.name: testRtcModule001 + * @tc.desc: rtc function test + * @tc.type: FUNC + * @tc.require: AR000EKRKU + */ +HWTEST_F(HdfRtcTest, testRtcModule001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_RTC_TYPE, RTC_FUNCTION_TEST, -1 }; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} +#endif diff --git a/support/platform/test/unittest/common/hdf_sdio_test.cpp b/support/platform/test/unittest/common/hdf_sdio_test.cpp new file mode 100644 index 00000000..c2ae82dc --- /dev/null +++ b/support/platform/test/unittest/common/hdf_sdio_test.cpp @@ -0,0 +1,139 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +enum SdioTestCmd { + SDIO_DISABLE_FUNC_01 = 0, + SDIO_ENABLE_FUNC_01, + SDIO_SET_BLOCK_SIZE_01, + SDIO_INCR_ADDR_READ_AND_WRITE_BYTES_01, + SDIO_FIXED_ADDR_READ_AND_WRITE_BYTES_01, + SDIO_FUNC0_READ_AND_WRITE_BYTES_01, + SDIO_SET_AND_GET_COMMON_INFO_01, +}; + +class HdfLiteSdioTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteSdioTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteSdioTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteSdioTest::SetUp() +{ +} + +void HdfLiteSdioTest::TearDown() +{ +} + +/** + * @tc.name: SdioDisableFunc001 + * @tc.desc: SdioDisableFunc Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioDisableFunc001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_DISABLE_FUNC_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioEnableFunc001 + * @tc.desc: SdioEnableFunc Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioEnableFunc001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_ENABLE_FUNC_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioSetBlockSize001 + * @tc.desc: SdioSetBlockSize Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioSetBlockSize001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_SET_BLOCK_SIZE_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioIncrAddrReadAndWriteBytes001 + * @tc.desc: SdioReadBytes and SdioWriteBytes Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioIncrAddrReadAndWriteBytes001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_INCR_ADDR_READ_AND_WRITE_BYTES_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioFixedAddrReadAndWriteBytes001 + * @tc.desc: SdioReadBytesFromFixedAddr and SdioWriteBytesToFixedAddr Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioFixedAddrReadAndWriteBytes001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_FIXED_ADDR_READ_AND_WRITE_BYTES_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioFunc0ReadAndWriteBytes001 + * @tc.desc: SdioReadBytesFromFunc0 and SdioWriteBytesToFunc0 Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioFunc0ReadAndWriteBytes001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_SDIO_TYPE, SDIO_FUNC0_READ_AND_WRITE_BYTES_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SdioSetAndGetCommonInfo001 + * @tc.desc: SdioGetCommonInfo and SdioSetCommonInfo Interface test + * @tc.type: FUNC + * @tc.require: AR000F868B + */ +HWTEST_F(HdfLiteSdioTest, SdioSetAndGetCommonInfo001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SDIO_TYPE, SDIO_SET_AND_GET_COMMON_INFO_01, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} diff --git a/support/platform/test/unittest/common/hdf_spi_test.cpp b/support/platform/test/unittest/common/hdf_spi_test.cpp new file mode 100644 index 00000000..7f4fd3f9 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_spi_test.cpp @@ -0,0 +1,115 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +// pal spi test case number +enum HdfTestCaseCmd { + SPI_SET_CFG_TEST = 0, + SPI_TRANSFER_TEST, + SPI_WRITE_TEST, + SPI_READ_TEST, + SPI_RELIABILITY_TEST, + SPI_PERFORMANCE_TEST, +}; + +class HdfLiteSpiTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteSpiTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteSpiTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteSpiTest::SetUp() +{ +} + +void HdfLiteSpiTest::TearDown() +{ +} + +/** + * @tc.name: SpiSetCfgTest001 + * @tc.desc: spi function test + * @tc.type: FUNC + * @tc.require: SR000DQ0VO + */ +HWTEST_F(HdfLiteSpiTest, SpiSetCfgTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SPI_TYPE, SPI_SET_CFG_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SpiTransferTest001 + * @tc.desc: spi function test + * @tc.type: FUNC + * @tc.require: SR000DQ0VO + */ +HWTEST_F(HdfLiteSpiTest, SpiTransferTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SPI_TYPE, SPI_TRANSFER_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SpiWriteTest001 + * @tc.desc: spi function test + * @tc.type: FUNC + * @tc.require: SR000DQ0VO + */ +HWTEST_F(HdfLiteSpiTest, SpiWriteTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_SPI_TYPE, SPI_WRITE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SpiReadTest001 + * @tc.desc: Spi function test + * @tc.type: FUNC + * @tc.require: SR000DQ0VO + */ +HWTEST_F(HdfLiteSpiTest, SpiReadTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SPI_TYPE, SPI_READ_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: SpiReliabilityTest001 + * @tc.desc: spi function test + * @tc.type: FUNC + * @tc.require: SR000DQ0VO + */ +HWTEST_F(HdfLiteSpiTest, SpiReliabilityTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_SPI_TYPE, SPI_RELIABILITY_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} diff --git a/support/platform/test/unittest/common/hdf_uart_test.cpp b/support/platform/test/unittest/common/hdf_uart_test.cpp new file mode 100644 index 00000000..f12a6b5e --- /dev/null +++ b/support/platform/test/unittest/common/hdf_uart_test.cpp @@ -0,0 +1,158 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +static int g_uartFd; +static const string HDF_TEST_NAME = "/dev/hdf_test"; + +enum HdfLiteUartTestCmd { + UAER_WRITE_TEST = 0, + UART_READ_TEST, + UART_SET_BAUD_TEST, + UART_GET_BAUD_TEST, + UART_SET_ATTRIBUTE_TEST, + UART_GET_ATTRIBUTE_TEST, + UART_SET_TRANSMODE_TEST, + UART_RELIABILITY_TEST, + UART_PERFORMANCE_TEST, +}; + +class HdfLiteUartTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteUartTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteUartTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteUartTest::SetUp() +{ +} + +void HdfLiteUartTest::TearDown() +{ +} + +#ifdef HDF_LITEOS_TEST +/** + * @tc.name: UartSetTransModeTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartSetTransModeTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_SET_TRANSMODE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} +#endif + +/** + * @tc.name: UartWriteTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartWriteTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UAER_WRITE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartReadTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartReadTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = { TEST_PAL_UART_TYPE, UART_READ_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartSetBaudTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartSetBaudTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_SET_BAUD_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartGetBaudTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartGetBaudTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_GET_BAUD_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartSetAttributeTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartSetAttributeTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_SET_ATTRIBUTE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartGetAttributeTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartGetAttributeTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_GET_ATTRIBUTE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: UartReliabilityTest001 + * @tc.desc: uart function test + * @tc.type: FUNC + * @tc.require: AR000F8689 + */ +HWTEST_F(HdfLiteUartTest, UartReliabilityTest001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_UART_TYPE, UART_RELIABILITY_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} diff --git a/support/platform/test/unittest/common/hdf_watchdog_test.cpp b/support/platform/test/unittest/common/hdf_watchdog_test.cpp new file mode 100644 index 00000000..6b6f8061 --- /dev/null +++ b/support/platform/test/unittest/common/hdf_watchdog_test.cpp @@ -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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +// pal watchdog test case number +enum WatchdogTestCmd { + WATCHDOG_TEST_SET_GET_TIMEOUT = 0, + WATCHDOG_TEST_START_STOP = 1, + WATCHDOG_TEST_FEED = 2, + WATCHDOG_TEST_RELIABILITY = 3, + WATCHDOG_TEST_BARK = 4, + WATCHDOG_TEST_MAX = 5, +}; + +class HdfLiteWatchdogTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfLiteWatchdogTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfLiteWatchdogTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfLiteWatchdogTest::SetUp() +{ +} + +void HdfLiteWatchdogTest::TearDown() +{ +} + +/** + * @tc.name: HdfLiteWatchdogTestSetGetTimeout001 + * @tc.desc: watchdog function test + * @tc.type: FUNC + * @tc.require: AR000F868G + */ +HWTEST_F(HdfLiteWatchdogTest, HdfLiteWatchdogTestSetGetTimeout001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_WDT_TYPE, WATCHDOG_TEST_SET_GET_TIMEOUT, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HdfLiteWatchdogTestStartStop001 + * @tc.desc: watchdog function test + * @tc.type: FUNC + * @tc.require: AR000F868G + */ +HWTEST_F(HdfLiteWatchdogTest, HdfLiteWatchdogTestStartStop001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_WDT_TYPE, WATCHDOG_TEST_START_STOP, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HdfLiteWatchdogTestFeed001 + * @tc.desc: watchdog function test + * @tc.type: FUNC + * @tc.require: AR000F868G + */ +HWTEST_F(HdfLiteWatchdogTest, HdfLiteWatchdogTestFeed001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_WDT_TYPE, WATCHDOG_TEST_FEED, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: HdfLiteWatchdogTestReliability001 + * @tc.desc: watchdog function test + * @tc.type: FUNC + * @tc.require: AR000F868G + */ +HWTEST_F(HdfLiteWatchdogTest, HdfLiteWatchdogTestReliability001, TestSize.Level0) +{ + struct HdfTestMsg msg = {TEST_PAL_WDT_TYPE, WATCHDOG_TEST_RELIABILITY, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); +} + diff --git a/support/posix/src/osal_mem.c b/support/posix/src/osal_mem.c new file mode 100644 index 00000000..6bd441c7 --- /dev/null +++ b/support/posix/src/osal_mem.c @@ -0,0 +1,73 @@ +/* + * 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_mem.h" +#include +#include +#include "securec.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG osal_mem + +void *OsalMemAlloc(size_t size) +{ + void *buf = NULL; + + if (size == 0) { + HDF_LOGE("%s invalid param", __func__); + return NULL; + } + + buf = malloc(size); + + return buf; +} + +void *OsalMemCalloc(size_t size) +{ + void *buf = NULL; + + if (size == 0) { + HDF_LOGE("%s invalid param", __func__); + return NULL; + } + + buf = OsalMemAlloc(size); + if (buf != NULL) { + (void)memset_s(buf, size, 0, size); + } + + return buf; +} + +void *OsalMemAllocAlign(size_t alignment, size_t size) +{ + void *buf = NULL; + int ret; + + if (size == 0) { + HDF_LOGE("%s invalid param", __func__); + return NULL; + } + + ret = posix_memalign(&buf, alignment, size); + if (ret != 0) { + HDF_LOGE("%s memory alloc fail %d", __func__, ret); + buf = NULL; + } + + return buf; +} + +void OsalMemFree(void *mem) +{ + if (mem != NULL) { + free(mem); + } +} + diff --git a/support/posix/src/osal_mutex.c b/support/posix/src/osal_mutex.c new file mode 100644 index 00000000..8ca66662 --- /dev/null +++ b/support/posix/src/osal_mutex.c @@ -0,0 +1,135 @@ +/* + * 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_mutex.h" +#include +#include +#include "securec.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define HDF_LOG_TAG osal_mutex +#define HDF_NANO_UNITS 1000000000 + +int32_t OsalMutexInit(struct OsalMutex *mutex) +{ + pthread_mutex_t *mutexTmp = NULL; + int32_t ret; + + if (mutex == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + mutex->realMutex = NULL; + + mutexTmp = (pthread_mutex_t *)OsalMemCalloc(sizeof(pthread_mutex_t)); + if (mutexTmp == NULL) { + HDF_LOGE("%s malloc fail", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + ret = pthread_mutex_init(mutexTmp, NULL); + if (ret != 0) { + HDF_LOGE("%s fail %d %d", __func__, ret, __LINE__); + OsalMemFree(mutexTmp); + return HDF_FAILURE; + } + + mutex->realMutex = (void *)mutexTmp; + + return HDF_SUCCESS; +} + +int32_t OsalMutexDestroy(struct OsalMutex *mutex) +{ + int32_t ret; + + if (mutex == NULL || mutex->realMutex == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = pthread_mutex_destroy((pthread_mutex_t *)mutex->realMutex); + if (ret != 0) { + HDF_LOGE("%s fail %d %d", __func__, ret, __LINE__); + return HDF_FAILURE; + } + + OsalMemFree(mutex->realMutex); + mutex->realMutex = NULL; + + return HDF_SUCCESS; +} + +int32_t OsalMutexLock(struct OsalMutex *mutex) +{ + if (mutex == NULL || mutex->realMutex == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + return OsalMutexTimedLock(mutex, HDF_WAIT_FOREVER); +} + +int32_t OsalMutexTimedLock(struct OsalMutex *mutex, uint32_t ms) +{ + int32_t ret; + + if (mutex == NULL || mutex->realMutex == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (ms == HDF_WAIT_FOREVER) { + ret = pthread_mutex_lock((pthread_mutex_t *)mutex->realMutex); + if (ret != 0) { + HDF_LOGE("pthread_mutex_lock fail %d", ret); + return HDF_FAILURE; + } + } else { + struct timespec time; + (void)memset_s(&time, sizeof(time), 0, sizeof(time)); + clock_gettime(CLOCK_REALTIME, &time); + time.tv_sec += ms / HDF_KILO_UNIT; + time.tv_nsec += (ms % HDF_KILO_UNIT) * HDF_KILO_UNIT * HDF_KILO_UNIT; + if (time.tv_nsec >= HDF_NANO_UNITS) { + time.tv_nsec -= HDF_NANO_UNITS; + time.tv_sec += 1; + } + ret = pthread_mutex_timedlock((pthread_mutex_t *)mutex->realMutex, &time); + if (ret != 0) { + if (ret == ETIMEDOUT) { + return HDF_ERR_TIMEOUT; + } else { + HDF_LOGE("%s time_out time:%d ret:%d", __func__, ms, ret); + return HDF_FAILURE; + } + } + } + + return HDF_SUCCESS; +} + +int32_t OsalMutexUnlock(struct OsalMutex *mutex) +{ + int32_t ret; + + if (mutex == NULL || mutex->realMutex == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = pthread_mutex_unlock((pthread_mutex_t *)mutex->realMutex); + if (ret != 0) { + HDF_LOGE("%s fail %d %d", __func__, ret, __LINE__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + diff --git a/support/posix/src/osal_sem.c b/support/posix/src/osal_sem.c new file mode 100644 index 00000000..f1747818 --- /dev/null +++ b/support/posix/src/osal_sem.c @@ -0,0 +1,116 @@ +/* + * 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_sem.h" +#include +#include +#include +#include "securec.h" +#include "hdf_log.h" +#include "osal_mem.h" + +const int32_t SHARE = 0; +#define HDF_LOG_TAG osal_sem +#define HDF_NANO_UNITS 1000000000 + +int32_t OsalSemInit(struct OsalSem *sem, uint32_t value) +{ + sem_t *semTmp = NULL; + + if (sem == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + sem->realSemaphore = NULL; + + semTmp = (sem_t *)OsalMemCalloc(sizeof(sem_t)); + if (semTmp == NULL) { + HDF_LOGE("malloc fail"); + return HDF_ERR_MALLOC_FAIL; + } + + if (sem_init(semTmp, SHARE, value) != 0) { + HDF_LOGE("sem_init fail errno:%d", errno); + OsalMemFree(semTmp); + return HDF_FAILURE; + } + sem->realSemaphore = (void *)semTmp; + + return HDF_SUCCESS; +} + +int32_t OsalSemWait(struct OsalSem *sem, uint32_t ms) +{ + if (sem == NULL || sem->realSemaphore == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (ms == HDF_WAIT_FOREVER) { + if (sem_wait((sem_t *)sem->realSemaphore) != 0) { + HDF_LOGE("sem_wait fail errno:%d", errno); + return HDF_FAILURE; + } + } else { + struct timespec time; + (void)memset_s(&time, sizeof(time), 0, sizeof(time)); + clock_gettime(CLOCK_REALTIME, &time); + time.tv_sec += ms / HDF_KILO_UNIT; + time.tv_nsec += (ms % HDF_KILO_UNIT) * HDF_KILO_UNIT * HDF_KILO_UNIT; + if (time.tv_nsec >= HDF_NANO_UNITS) { + time.tv_nsec -= HDF_NANO_UNITS; + time.tv_sec += 1; + } + int32_t ret = sem_timedwait((sem_t *)sem->realSemaphore, &time); + if (ret != 0) { + if (errno == ETIMEDOUT) { + return HDF_ERR_TIMEOUT; + } else { + HDF_LOGE("%s time_out time:%d ret:%d,errno:%d", __func__, ms, ret, errno); + return HDF_FAILURE; + } + } + } + + return HDF_SUCCESS; +} + +int32_t OsalSemPost(struct OsalSem *sem) +{ + if (sem == NULL || sem->realSemaphore == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (sem_post((sem_t *)sem->realSemaphore) != 0) { + HDF_LOGE("sem_post fail errno:%d", errno); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +int32_t OsalSemDestroy(struct OsalSem *sem) +{ + if (sem == NULL || sem->realSemaphore == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + int32_t ret = sem_destroy((sem_t *)sem->realSemaphore); + if (ret != 0) { + HDF_LOGE("sem_destroy fail errno:%d", errno); + return HDF_FAILURE; + } + OsalMemFree(sem->realSemaphore); + sem->realSemaphore = NULL; + + return HDF_SUCCESS; +} + diff --git a/support/posix/src/osal_thread.c b/support/posix/src/osal_thread.c new file mode 100644 index 00000000..fc621b42 --- /dev/null +++ b/support/posix/src/osal_thread.c @@ -0,0 +1,171 @@ +/* + * 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_thread.h" +#include +#include "hdf_base.h" +#include "hdf_log.h" +#include "osal_mem.h" + +#define OSAL_PTHREAD_STACK_MIN 4096 + +#define HDF_LOG_TAG osal_thread + +typedef void *(*PosixEntry)(void *data); + +struct ThreadWrapper { + OsalThreadEntry threadEntry; + void *entryPara; + pthread_t id; +}; +#ifdef _LINUX_USER_ +enum { + OSAL_PRIORITY_MIDDLE = 50, + OSAL_PRIORITY_HIGH = 90, + OSAL_PRIORITY_HIGHEST = 99, +}; +#else +enum { + OSAL_PRIORITY_MIDDLE = 30, + OSAL_PRIORITY_HIGH = 15, + OSAL_PRIORITY_HIGHEST = 5, +}; +#endif + +static void OsalThreadRemapSched(int priority, struct sched_param *param, int32_t *policy) +{ + if (priority == OSAL_THREAD_PRI_HIGHEST) { + param->sched_priority = OSAL_PRIORITY_HIGHEST; + } else if (priority == OSAL_THREAD_PRI_HIGH) { + param->sched_priority = OSAL_PRIORITY_HIGH; + } else if (priority == OSAL_THREAD_PRI_DEFAULT) { + param->sched_priority = OSAL_PRIORITY_MIDDLE; + } else { + *policy = SCHED_OTHER; + } +} + +int32_t OsalThreadCreate(struct OsalThread *thread, OsalThreadEntry threadEntry, void *entryPara) +{ + struct ThreadWrapper *para = NULL; + + if (thread == NULL || threadEntry == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + thread->realThread = NULL; + para = (struct ThreadWrapper *)OsalMemCalloc(sizeof(*para)); + if (para == NULL) { + HDF_LOGE("%s malloc fail", __func__); + return HDF_FAILURE; + } + + para->entryPara = entryPara; + para->threadEntry = threadEntry; + thread->realThread = para; + + return HDF_SUCCESS; +} + +int32_t OsalThreadDestroy(struct OsalThread *thread) +{ + if (thread->realThread != NULL) { + OsalMemFree(thread->realThread); + thread->realThread = NULL; + } + return HDF_SUCCESS; +} + +static int OsalCreatePthread(pthread_t *threadId, pthread_attr_t *attribute, struct ThreadWrapper *para) +{ + int resultCode = pthread_create(threadId, attribute, (PosixEntry)para->threadEntry, para->entryPara); + if (resultCode != 0) { + HDF_LOGE("pthread_create errorno: %d", resultCode); + return resultCode; + } + resultCode = pthread_detach(*threadId); + if (resultCode != 0) { + HDF_LOGE("pthread_detach errorno: %d", resultCode); + return resultCode; + } + resultCode = pthread_attr_destroy(attribute); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_destroy errorno: %d", resultCode); + return resultCode; + } + return HDF_SUCCESS; +} + +int32_t OsalThreadStart(struct OsalThread *thread, const struct OsalThreadParam *param) +{ + pthread_attr_t attribute; + struct sched_param priorityHolder; + int32_t policy = SCHED_FIFO; + + if (thread == NULL || thread->realThread == NULL || param == NULL) { + HDF_LOGE("%s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + + struct ThreadWrapper *para = (struct ThreadWrapper *)thread->realThread; + + int resultCode = pthread_attr_init(&attribute); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_init errorno: %d", resultCode); + goto DEAL_FAIL; + } + + resultCode = pthread_attr_setinheritsched(&attribute, PTHREAD_EXPLICIT_SCHED); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_setinheritsched errorno: %d", resultCode); + goto DEAL_FAIL; + } + + size_t stackSize = param->stackSize; + if (stackSize > 0) { + stackSize = (stackSize < OSAL_PTHREAD_STACK_MIN) ? OSAL_PTHREAD_STACK_MIN : stackSize; + resultCode = pthread_attr_setstacksize(&attribute, stackSize); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_setstacksize errorno: %d", resultCode); + goto DEAL_FAIL; + } + } + + resultCode = pthread_attr_getschedparam(&attribute, &priorityHolder); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_getschedparam errorno: %d", resultCode); + goto DEAL_FAIL; + } + + OsalThreadRemapSched(param->priority, &priorityHolder, &policy); + + resultCode = pthread_attr_setschedpolicy(&attribute, policy); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_setschedpolity errorno: %d", resultCode); + goto DEAL_FAIL; + } + + resultCode = pthread_attr_setschedparam(&attribute, &priorityHolder); + if (resultCode != 0) { + HDF_LOGE("pthread_attr_setschedparam errorno: %d", resultCode); + goto DEAL_FAIL; + } + + resultCode = OsalCreatePthread(¶->id, &attribute, thread->realThread); + if (resultCode != 0) { + HDF_LOGE("OsalCreatePthread errorno: %d", resultCode); + goto DEAL_FAIL; + } + return HDF_SUCCESS; + +DEAL_FAIL: + (void)OsalThreadDestroy(thread); + return HDF_FAILURE; +} + diff --git a/support/posix/src/osal_time.c b/support/posix/src/osal_time.c new file mode 100644 index 00000000..ad0429d4 --- /dev/null +++ b/support/posix/src/osal_time.c @@ -0,0 +1,102 @@ +/* + * 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_time.h" +#include +#include +#include +#include +#include "securec.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG osal_time + +int32_t OsalGetTime(OsalTimespec *time) +{ + struct timeval tv; + + if (time == NULL) { + HDF_LOGE("%{public}s invalid para", __func__); + return HDF_ERR_INVALID_PARAM; + } + + (void)memset_s(&tv, sizeof(tv), 0, sizeof(tv)); + if (gettimeofday(&tv, NULL) != 0) { + HDF_LOGE("%{public}s gettimeofday failed", __func__); + return HDF_FAILURE; + } + time->sec = tv.tv_sec; + time->usec = tv.tv_usec; + + return HDF_SUCCESS; +} + +int32_t OsalDiffTime(const OsalTimespec *start, const OsalTimespec *end, OsalTimespec *diff) +{ + uint32_t usec = 0; + uint32_t sec = 0; + if (start == NULL || end == NULL || diff == NULL) { + HDF_LOGE("%{public}s invalid para", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (start->sec > end->sec) { + HDF_LOGE("%{public}s start time later then end time", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (end->usec < start->usec) { + usec = (HDF_KILO_UNIT * HDF_KILO_UNIT); + sec = 1; + } + diff->usec = usec + end->usec - start->usec; + diff->sec = end->sec - start->sec - sec; + + return HDF_SUCCESS; +} + +void OsalSleep(uint32_t sec) +{ + sleep(sec); +} + +void OsalMSleep(uint32_t ms) +{ + int result; + struct timespec ts; + + ts.tv_sec = ms / HDF_KILO_UNIT; + ts.tv_nsec = HDF_KILO_UNIT * HDF_KILO_UNIT * ((long)(ms % HDF_KILO_UNIT)); + result = nanosleep(&ts, &ts); + if (result != 0) { + HDF_LOGE("%{public}s OsalMSleep failed %{public}d", __func__, errno); + } +} + +void OsalUDelay(uint32_t us) +{ + (void)us; +} + +void OsalMDelay(uint32_t ms) +{ + (void)ms; +} + +uint64_t OsalGetSysTimeMs() +{ + struct timeval tv; + + (void)memset_s(&tv, sizeof(tv), 0, sizeof(tv)); + if (gettimeofday(&tv, NULL) != 0) { + HDF_LOGE("%{public}s gettimeofday failed", __func__); + return 0; + } + + return ((uint64_t)tv.tv_sec * HDF_KILO_UNIT + tv.tv_usec / HDF_KILO_UNIT); +} diff --git a/support/posix/test/unittest/common/hdf_osal_test.cpp b/support/posix/test/unittest/common/hdf_osal_test.cpp new file mode 100644 index 00000000..889f3b96 --- /dev/null +++ b/support/posix/test/unittest/common/hdf_osal_test.cpp @@ -0,0 +1,1037 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include "osal_test_case_def.h" +#include "hdf_uhdf_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +static const int OSAL_TEST_TIME = 30; +static const int OSAL_WAIT_END_TIME = 5; +static const char *OSAL_FW_PATH = "/lib/firmware"; +static const int OSAL_FW_PATH_MODE = 0x777; +#define OSAL_TEST_FUNC_DEFINE(subCmd) do { \ + struct HdfTestMsg msg = { TEST_OSAL_ITEM, subCmd, -1 }; \ + printf("OSAL test enter cmd:%d\n\r", subCmd); \ + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); \ +} while (0) + +class OsalTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +static void OsalCreateDir(bool flag) +{ +#if defined(__LITEOS__) + (void)flag; +#else + int ret; + if (flag) { + ret = mkdir(OSAL_FW_PATH, OSAL_FW_PATH_MODE); + } else { + ret = rmdir(OSAL_FW_PATH); + } + printf("%s %d %d", __func__, ret, flag); +#endif +} +void OsalTest::SetUpTestCase() +{ + HdfTestOpenService(); + OsalCreateDir(true); + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_START); + sleep(OSAL_TEST_TIME); + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_END); + sleep(OSAL_WAIT_END_TIME); +} + +void OsalTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void OsalTest::SetUp() +{ +} + +void OsalTest::TearDown() +{ +} + +/** + * @tc.name: OsalGetMutex001 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_CREATE); +} + +/** + * @tc.name: OsalGetMutex002 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_LOCK_TIMEOUT); +} + +/** + * @tc.name: OsalGetMutex003 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_UNLOCK); +} + +/** + * @tc.name: OsalGetMutex004 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_LOCK_FOREVER); +} + +/** + * @tc.name: OsalGetMutex005 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_DESTROY); +} + +/** + * @tc.name: OsalGetMutex006 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_VISIT_DESTROY); +} + +/** + * @tc.name: OsalGetMutex007 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_STRESS_TEST); +} + +/** + * @tc.name: OsalGetMutex008 + * @tc.desc: mutex function test + * @tc.type: FUNC + * @tc.require: AR000F868U + */ +HWTEST_F(OsalTest, OsalGetMutex008, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MUTEX_OTHER); +} + +/** + * @tc.name: OsalGetSpin001 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_CREATE); +} + +/** + * @tc.name: OsalGetSpin002 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_LOCK); +} + +/** + * @tc.name: OsalGetSpin003 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_UNLOCK); +} + +/** + * @tc.name: OsalGetSpin004 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_LOCK_IRQ); +} + +/** + * @tc.name: OsalGetSpin005 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_UNLOCK_IRQ); +} + +/** + * @tc.name: OsalGetSpin006 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_LOCK_IRQ_SAVE); +} + +/** + * @tc.name: OsalGetSpin007 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_UNLOCK_IRQ_RESTORE); +} + +/** + * @tc.name: OsalGetSpin008 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin008, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_DESTROY); +} + +/** + * @tc.name: OsalGetSpin009 + * @tc.desc: Spin function test + * @tc.type: FUNC + * @tc.require: AR000F8690 + */ +HWTEST_F(OsalTest, OsalGetSpin009, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_LOCK_AFTER_DESTROY); +} + +/** + * @tc.name: OsalGetSpin010 + * @tc.desc: LOG function test + * @tc.type: FUNC + * @tc.require: AR000F8695 + */ +HWTEST_F(OsalTest, OsalGetSpin010, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_STRESS_TEST); +} + +/** + * @tc.name: OsalGetSpin011 + * @tc.desc: LOG function test + * @tc.type: FUNC + * @tc.require: AR000F8695 + */ +HWTEST_F(OsalTest, OsalGetSpin011, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SPIN_OTHER); +} + +/** + * @tc.name: OsalGetTime001 + * @tc.desc: time function test + * @tc.type: FUNC + * @tc.require: AR000F8696 + */ +HWTEST_F(OsalTest, OsalGetTime001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIME_SLEEP); +} +/** + * @tc.name: OsalGetTime002 + * @tc.desc: time function test + * @tc.type: FUNC + * @tc.require: AR000F8696 + */ +HWTEST_F(OsalTest, OsalGetTime002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIME_MSLEEP); +} +/** + * @tc.name: OsalGetTime003 + * @tc.desc: time function test + * @tc.type: FUNC + * @tc.require: AR000F8696 + */ +HWTEST_F(OsalTest, OsalGetTime003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIME_USLEEP); +} +/** + * @tc.name: OsalGetTime004 + * @tc.desc: time function test + * @tc.type: FUNC + * @tc.require: AR000F8696 + */ +HWTEST_F(OsalTest, OsalGetTime004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIME_GETTIME); +} +/** + * @tc.name: OsalGetTime005 + * @tc.desc: time function test + * @tc.type: FUNC + * @tc.require: AR000F8696 + */ +HWTEST_F(OsalTest, OsalGetTime005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIME_DIFFTIME); +} + +/** + * @tc.name: OsalGetIrq001 + * @tc.desc: irq function test + * @tc.type: FUNC + * @tc.require: AR000F868Q + */ +HWTEST_F(OsalTest, OsalGetIrq001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_IRQ_UNREG_ABNORMAL); +} +/** + * @tc.name: OsalGetIrq002 + * @tc.desc: irq function test + * @tc.type: FUNC + * @tc.require: AR000F868Q + */ +HWTEST_F(OsalTest, OsalGetIrq002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_IRQ_REG_NORMAL); +} +/** + * @tc.name: OsalGetIrq003 + * @tc.desc: irq function test + * @tc.type: FUNC + * @tc.require: AR000F868Q + */ +HWTEST_F(OsalTest, OsalGetIrq003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_IRQ_UNREG_NORMAL); +} +/** + * @tc.name: OsalGetIrq004 + * @tc.desc: irq function test + * @tc.type: FUNC + * @tc.require: AR000F868Q + */ +HWTEST_F(OsalTest, OsalGetIrq004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_IRQ_REG_NORMAL_STRESS); +} +/** + * @tc.name: OsalGetIrq005 + * @tc.desc: irq function test + * @tc.type: FUNC + * @tc.require: AR000F868Q + */ +HWTEST_F(OsalTest, OsalGetIrq005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_IRQ_UNREG_NORMAL_STRESS); +} + +/** + * @tc.name: OsalGetTimer001 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_CREATE_ONCE); +} +/** + * @tc.name: OsalGetTimer002 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_CREATE_LOOP); +} +/** + * @tc.name: OsalGetTimer003 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_RUN_CHECK); +} +/** + * @tc.name: OsalGetTimer004 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_PARA_CHECK); +} +/** + * @tc.name: OsalGetTimer005 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_PERIOD_CHECK); +} +/** + * @tc.name: OsalGetTimer006 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_MODIFY_CHECK); +} +/** + * @tc.name: OsalGetTimer007 + * @tc.desc: timer function test + * @tc.type: FUNC + * @tc.require: AR000F868T + */ +HWTEST_F(OsalTest, OsalGetTimer007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TIMER_STOP_CHECK); +} + +/** + * @tc.name: OsalGetThread001 + * @tc.desc: thread function test + * @tc.type: FUNC + * @tc.require: AR000F868S + */ +HWTEST_F(OsalTest, OsalGetThread001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_THREAD_CREATE); +} +/** + * @tc.name: OsalGetThread002 + * @tc.desc: thread function test + * @tc.type: FUNC + * @tc.require: AR000F868S + */ +HWTEST_F(OsalTest, OsalGetThread002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_THREAD_PARA_CHECK); +} +/** + * @tc.name: OsalGetThread003 + * @tc.desc: thread function test + * @tc.type: FUNC + * @tc.require: AR000F868S + */ +HWTEST_F(OsalTest, OsalGetThread003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_THREAD_RUN_CHECK); +} + +/** + * @tc.name: OsalGetFW001 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_REQUEST); +} +/** + * @tc.name: OsalGetFW002 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_READ); +} +/** + * @tc.name: OsalGetFW003 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_DATA_CHECK); +} +/** + * @tc.name: OsalGetFW004 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_SEEK); +} +/** + * @tc.name: OsalGetFW005 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_RELEASE); +} +/** + * @tc.name: OsalGetFW006 + * @tc.desc: FW function test + * @tc.type: FUNC + * @tc.require: AR000F8693 + */ +HWTEST_F(OsalTest, OsalGetFW006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FW_READ_AFTER_RELEASE); +} + +/** + * @tc.name: OsalGetMemory001 + * @tc.desc: memory function test + * @tc.type: FUNC + * @tc.require: AR000F868R + */ +HWTEST_F(OsalTest, OsalGetMemory001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MALLOC_BIG); +} +/** + * @tc.name: OsalGetMemory002 + * @tc.desc: memory function test + * @tc.type: FUNC + * @tc.require: AR000F868R + */ +HWTEST_F(OsalTest, OsalGetMemory002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MALLOC_SMALL); +} +/** + * @tc.name: OsalGetMemory003 + * @tc.desc: memory function test + * @tc.type: FUNC + * @tc.require: AR000F868R + */ +HWTEST_F(OsalTest, OsalGetMemory003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MALLOC_BIG_STRESS); +} +/** + * @tc.name: OsalGetMemory004 + * @tc.desc: memory function test + * @tc.type: FUNC + * @tc.require: AR000F868R + */ +HWTEST_F(OsalTest, OsalGetMemory004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_MALLOC_SMALL_STRESS); +} + +/** + * @tc.name: OsalGetList001 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_INIT); +} +/** + * @tc.name: OsalGetList002 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_EMPTY); +} +/** + * @tc.name: OsalGetList003 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_COUNT_CHECK); +} +/** + * @tc.name: OsalGetList004 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_TAIL); +} +/** + * @tc.name: OsalGetList005 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_HEAD); +} +/** + * @tc.name: OsalGetList006 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_REMOVE); +} +/** + * @tc.name: OsalGetList007 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_TRAVERSAL); +} +/** + * @tc.name: OsalGetList008 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList008, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_TRAVERSAL_REMOVE); +} +/** + * @tc.name: OsalGetList009 + * @tc.desc: list function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetList009, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_LIST_STRESS); +} + +/** + * @tc.name: OsalGetSem001 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_CREATE); +} +/** + * @tc.name: OsalGetSem002 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_POST); +} +/** + * @tc.name: OsalGetSem003 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_POST_RESULT); +} +/** + * @tc.name: OsalGetSem004 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_WAIT_TIMEOUT); +} +/** + * @tc.name: OsalGetSem005 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_WAIT_FOREVER); +} +/** + * @tc.name: OsalGetSem006 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_DESTROY); +} +/** + * @tc.name: OsalGetSem007 + * @tc.desc: sem function test + * @tc.type: FUNC + * @tc.require: AR000F868V + */ +HWTEST_F(OsalTest, OsalGetSem007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_SEM_VISIT_AFTER_DESTROY); +} + +/** + * @tc.name: OsalGetWork001 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_WORK_QUEUE_CREATE); +} +/** + * @tc.name: OsalGetWork002 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_WORK_CREATE); +} +/** + * @tc.name: OsalGetWork003 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_DELAY_WORK_CREATE); +} +/** + * @tc.name: OsalGetWork004 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_WORK_ADD); +} +/** + * @tc.name: OsalGetWork005 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_DELAY_WORK_ADD); +} +/** + * @tc.name: OsalGetWork006 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_WORK_RUN_CHECK); +} +/** + * @tc.name: OsalGetWork007 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_DELAY_WORK_RUN_CHECK); +} +/** + * @tc.name: OsalGetWork008 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork008, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_WORK_CANCEL); +} +/** + * @tc.name: OsalGetWork009 + * @tc.desc: work function test + * @tc.type: FUNC + * @tc.require: AR000F8692 + */ +HWTEST_F(OsalTest, OsalGetWork009, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_DELAY_WORK_CANCEL); +} + +/** + * @tc.name: OsalGetAtomic001 + * @tc.desc: atomic function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetAtomic001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_ATOMIC_SET); +} +/** + * @tc.name: OsalGetAtomic002 + * @tc.desc: atomic function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetAtomic002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_ATOMIC_READ); +} +/** + * @tc.name: OsalGetAtomic003 + * @tc.desc: atomic function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetAtomic003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_ATOMIC_INC); +} +/** + * @tc.name: OsalGetAtomic004 + * @tc.desc: atomic function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetAtomic004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_ATOMIC_DEC); +} + +/** + * @tc.name: OsalGetBits001 + * @tc.desc: bits function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetBits001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_BIT); +} +/** + * @tc.name: OsalGetBits002 + * @tc.desc: bits function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetBits002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_SET_BIT); +} +/** + * @tc.name: OsalGetBits003 + * @tc.desc: bits function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetBits003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_CLR_BIT); +} +/** + * @tc.name: OsalGetBits004 + * @tc.desc: bits function test + * @tc.type: FUNC + * @tc.require: AR000F8691 + */ +HWTEST_F(OsalTest, OsalGetBits004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_CLR_BIT); +} + +/** + * @tc.name: OsalGetFile001 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_OPEN_RD); +} +/** + * @tc.name: OsalGetFile002 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile002, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_READ_RD); +} +/** + * @tc.name: OsalGetFile003 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile003, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_WRITE_RD); +} +/** + * @tc.name: OsalGetFile004 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile004, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_SEEK_RD); +} +/** + * @tc.name: OsalGetFile005 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile005, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_CLOSE_RD); +} +/** + * @tc.name: OsalGetFile006 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile006, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_OPEN_RDWR); +} +/** + * @tc.name: OsalGetFile007 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile007, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_READ_RDWR); +} +/** + * @tc.name: OsalGetFile008 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile008, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_WRITE_RDWR); +} +/** + * @tc.name: OsalGetFile009 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile009, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_SEEK_RDWR); +} +/** + * @tc.name: OsalGetFile010 + * @tc.desc: file function test + * @tc.type: FUNC + * @tc.require: AR000F8694 + */ +HWTEST_F(OsalTest, OsalGetFile010, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_FILE_CLOSE_RDWR); +} + +/** + * @tc.name: OsalGetAll001 + * @tc.desc: all function test + * @tc.type: FUNC + * @tc.require: SR000F868P + */ +HWTEST_F(OsalTest, OsalGetAll001, TestSize.Level3) +{ + OSAL_TEST_FUNC_DEFINE(OSAL_TEST_ALL); +} 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 new file mode 100644 index 00000000..654698f2 --- /dev/null +++ b/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.c @@ -0,0 +1,1022 @@ +/* + * 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 "hcs_config_test.h" +#include "device_resource_if.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hcs_config_test + +#define DATA_TYPE_NUM_U32 3 +#define DATA_TYPE_NUM_U64 4 +#define U8_DATA 1 +#define U16_DATA_OFFSET 8 +#define U16_DATA (1 << U16_DATA_OFFSET) +#define U32_DATA_OFFSET 16 +#define U32_DATA (1 << U32_DATA_OFFSET) +#define U64_DATA 0x100000000 +#define DEFAULT_UINT8_MAX 0xFF +#define DEFAULT_UINT16_MAX 0xFFFF +#define DEFAULT_UINT32_MAX 0xFFFFFFFF +#define DEFAULT_UINT64_MAX 0xFFFFFFFFFFFFFFFF +#define BOARDID_LENGTH 2 +#define HW_AUDIO_INFO "hw,hw_audio_info" +#define HW_FINGERPRINT_INFO "hw,hw_fingerprint_info" +#define INVALID_STRING "NULL" +#define READ_U32_INDEX "read_u32_index" +#define DUAL_FINGERPRINT "dual_fingerprint" +#define BOARD_ID "board_id" +#define STRING_LIST_NAMES "string_list_names" +#define AUDIO_INFO "audio_info" +#define FINGERPRINT_INFO "fingerprint_info" +#define INVALID_NODE "fingerprint" +#define FINGER_INFO "finger_info" +#define STRING_ATTR_VALUE "default" +#define READ_FOUR_DATA_TYPE "read_four_data_type" +#define HW_DATA_TYPE_TEST "hw,data_type_test" +#define SMARTPA_NUM "smartpa_num" +#define READ_U64DATA "read_u64data" +#define VOICE_VOL_LEVEL "voice_vol_level" +#define SMARTPA_ADDR "smartpa_addr" +#define DATA_TEST_ARRAY_LENGTH 8 +#define TEST_U8_ELEM_DATA "test_u8_elem_data" +#define TEST_U16_ELEM_DATA "test_u16_elem_data" +static const struct DeviceResourceNode *g_testRoot = NULL; +static const struct DeviceResourceIface *g_devResInstance = NULL; + +static bool TestGetRootNode(void) +{ + g_devResInstance = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (g_devResInstance == NULL) { + HDF_LOGE("%s failed, DeviceResourceGetIfaceInstance is error", __func__); + return false; + } + + g_testRoot = g_devResInstance->GetRootNode(); + if (g_testRoot == NULL) { + HDF_LOGE("%s failed, GetDmRootNode failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + return true; +} + +int HcsTestCreateDMHcsToTree(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static bool TestHcsGetNodeByMatchAttrSuccess(void) +{ + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + if (audioNode == NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + const struct DeviceResourceNode *fingerPrintNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, + HW_FINGERPRINT_INFO); + if (fingerPrintNode == NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + return true; +} + +int HcsTestGetNodeByMatchAttrSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + if (!TestHcsGetNodeByMatchAttrSuccess()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static bool TestHcsGetNodeByMatchAttrFailed(void) +{ + const struct DeviceResourceNode *nullNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, INVALID_STRING); + if (nullNode != NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + nullNode = g_devResInstance->GetNodeByMatchAttr(NULL, INVALID_STRING); + if (nullNode != NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + nullNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, NULL); + if (nullNode != NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + return true; +} + +int HcsTestGetNodeByMatchAttrFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + if (!TestHcsGetNodeByMatchAttrFailed()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static bool TestHcsAttrGetBoolSuccess(void) +{ + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + bool primaryMic = g_devResInstance->GetBool(audioNode, "builtin_primary_mic_exist"); + if (!primaryMic) { + HDF_LOGE("%s failed, HcsGetBool failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + if (fingerNode == NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + bool dualFinger = g_devResInstance->GetBool(fingerNode, DUAL_FINGERPRINT); + if (dualFinger) { + HDF_LOGE("%s failed, HcsGetBool failed, line: %d\n", __FUNCTION__, __LINE__); + return false; + } + return true; +} + +int HcsTestGetBoolAttrValueSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + if (!TestHcsAttrGetBoolSuccess()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static bool TestHcsAttrGetBoolFailed(void) +{ + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + if (audioNode == NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d", __FUNCTION__, __LINE__); + return false; + } + bool testReadBool = g_devResInstance->GetBool(audioNode, INVALID_STRING); + if (testReadBool) { + HDF_LOGE("%s failed, HcsGetBool failed, line: %d", __FUNCTION__, __LINE__); + return false; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + if (fingerNode == NULL) { + HDF_LOGE("%s failed, HcsGetNodeByMatchAttr failed, line: %d", __FUNCTION__, __LINE__); + return false; + } + testReadBool = g_devResInstance->GetBool(fingerNode, INVALID_STRING); + if (testReadBool) { + HDF_LOGE("%s failed, HcsGetBool failed. line: %d", __FUNCTION__, __LINE__); + return false; + } + testReadBool = g_devResInstance->GetBool(NULL, INVALID_STRING); + if (testReadBool) { + HDF_LOGE("%s failed, HcsGetBool failed. line: %d", __FUNCTION__, __LINE__); + return false; + } + testReadBool = g_devResInstance->GetBool(fingerNode, NULL); + if (testReadBool) { + HDF_LOGE("%s failed, HcsGetBool failed. line: %d", __FUNCTION__, __LINE__); + return false; + } + return true; +} + +int HcsTestGetBoolAttrValueFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + if (!TestHcsAttrGetBoolFailed()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint8AttrValueSuccess(void) +{ + uint8_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint8(audioNode, SMARTPA_NUM, &data, DEFAULT_UINT8_MAX); + if ((ret != HDF_SUCCESS) || (data != U8_DATA)) { + HDF_LOGE("%s failed, line: %d, ret = %d, data = %u", __FUNCTION__, __LINE__, ret, data); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint8AttrValueFail(void) +{ + uint8_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint8(audioNode, INVALID_STRING, &data, DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint8(audioNode, READ_U64DATA, NULL, DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint8(audioNode, VOICE_VOL_LEVEL, &data, DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint8(audioNode, SMARTPA_ADDR, &data, DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint8(audioNode, READ_U64DATA, &data, DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +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}; + uint32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t count = g_devResInstance->GetElemNum(dataType, TEST_U8_ELEM_DATA); + if (count != DATA_TEST_ARRAY_LENGTH) { + return HDF_FAILURE; + } + for (i = 0; i < count; i++) { + 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]); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int HcsTestGetUint8ArrayElemFail(void) +{ + uint8_t data; + uint32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + // the number of 8 is invalid value. + int32_t ret = g_devResInstance->GetUint8ArrayElem(dataType, TEST_U8_ELEM_DATA, 8, &data, + DEFAULT_UINT8_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT8_MAX)) { + HDF_LOGE("%s failed, line: %d, ret = %d, data = %x", __FUNCTION__, __LINE__, ret, data); + return HDF_FAILURE; + } + uint8_t data1[DATA_TYPE_NUM_U64] = { 0 }; + dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t count = g_devResInstance->GetElemNum(dataType, READ_FOUR_DATA_TYPE); + if (count != DATA_TYPE_NUM_U64) { + return HDF_FAILURE; + } + 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. + 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); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint8ArraySuccess(void) +{ + uint8_t data[DATA_TEST_ARRAY_LENGTH] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint8ArrayFail(void) +{ + uint8_t data[DATA_TYPE_NUM_U64 + 1] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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 + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint16AttrValueSuccess(void) +{ + uint16_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint16(audioNode, SMARTPA_NUM, &data, DEFAULT_UINT16_MAX); + if ((ret != HDF_SUCCESS) || (data != U8_DATA)) { + HDF_LOGE("%s failed, line: %d, ret = %d, data = %u", __FUNCTION__, __LINE__, ret, data); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint16(audioNode, VOICE_VOL_LEVEL, &data, DEFAULT_UINT16_MAX); + if ((ret != HDF_SUCCESS) || (data != U16_DATA)) { + HDF_LOGE("%s failed, line: %d, ret = %d, data = %u", __FUNCTION__, __LINE__, ret, data); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint16AttrValueFail(void) +{ + uint16_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint16(audioNode, INVALID_STRING, &data, DEFAULT_UINT16_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT16_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint16(audioNode, READ_U64DATA, NULL, DEFAULT_UINT16_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT16_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint16(audioNode, SMARTPA_ADDR, &data, DEFAULT_UINT16_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT16_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint16(audioNode, READ_U64DATA, &data, DEFAULT_UINT16_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT16_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +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}; + uint32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t count = g_devResInstance->GetElemNum(dataType, TEST_U16_ELEM_DATA); + if (count != DATA_TEST_ARRAY_LENGTH) { + return HDF_FAILURE; + } + for (i = 0; i < count; i++) { + int32_t ret = g_devResInstance->GetUint16ArrayElem(dataType, TEST_U16_ELEM_DATA, i, &data[i], + DEFAULT_UINT16_MAX); + if ((ret != HDF_SUCCESS) || (data[i] != testData[i])) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int HcsTestGetUint16ArrayElemFail(void) +{ + uint16_t data; + uint32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t ret = g_devResInstance->GetUint16ArrayElem(dataType, TEST_U16_ELEM_DATA, DATA_TEST_ARRAY_LENGTH, &data, + DEFAULT_UINT16_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT16_MAX)) { + return HDF_FAILURE; + } + uint16_t data1[DATA_TYPE_NUM_U64] = { 0 }; + dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t count = g_devResInstance->GetElemNum(dataType, READ_FOUR_DATA_TYPE); + if (count != DATA_TYPE_NUM_U64) { + return HDF_FAILURE; + } + 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. + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint16ArraySuccess(void) +{ + uint16_t data[DATA_TEST_ARRAY_LENGTH] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint16ArrayFail(void) +{ + uint16_t data[DATA_TYPE_NUM_U64 + 1] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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 + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32AttrValueSuccess(void) +{ + uint32_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint32(audioNode, SMARTPA_NUM, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U8_DATA)) { + HDF_LOGE("%s failed, line: %d, ret = %d, data = %u", __FUNCTION__, __LINE__, ret, data); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint32(audioNode, VOICE_VOL_LEVEL, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U16_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint32(audioNode, SMARTPA_ADDR, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U32_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32AttrValueFail(void) +{ + uint32_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint32(audioNode, INVALID_STRING, &data, DEFAULT_UINT32_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT32_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint32(audioNode, SMARTPA_ADDR, NULL, DEFAULT_UINT32_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT32_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32ArrayElemSuccess(void) +{ + uint32_t data[DATA_TYPE_NUM_U32] = { 0 }; + uint32_t testData[DATA_TYPE_NUM_U32] = {U8_DATA, U16_DATA, U32_DATA}; + int32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + int32_t count = g_devResInstance->GetElemNum(fingerNode, READ_U32_INDEX); + if (count != DATA_TYPE_NUM_U32) { + return HDF_FAILURE; + } + for (i = 0; i < count; i++) { + int32_t ret = g_devResInstance->GetUint32ArrayElem(fingerNode, READ_U32_INDEX, i, &data[i], DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data[i] != testData[i])) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32ArrayElemFail(void) +{ + uint32_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + int32_t ret = g_devResInstance->GetUint32ArrayElem(fingerNode, READ_U32_INDEX, DATA_TYPE_NUM_U32, &data, + DEFAULT_UINT32_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT32_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32ArraySuccess(void) +{ + uint32_t data[BOARDID_LENGTH] = { 0 }; + if (!TestGetRootNode()) { + 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. + if ((ret != HDF_SUCCESS) || (data[0] != U32_DATA) || (data[1] != U16_DATA)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint32ArrayFail(void) +{ + uint32_t data[DATA_TYPE_NUM_U32] = { 0 }; + if (!TestGetRootNode()) { + 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. + 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 + if ((ret == HDF_SUCCESS) || (data[0] != U32_DATA) || (data[1] != U16_DATA) || (data[2] != DEFAULT_UINT32_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint64AttrValueSuccess(void) +{ + uint64_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint64(audioNode, SMARTPA_NUM, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U8_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint64(audioNode, VOICE_VOL_LEVEL, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U16_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint64(audioNode, SMARTPA_ADDR, &data, DEFAULT_UINT32_MAX); + if ((ret != HDF_SUCCESS) || (data != U32_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint64(audioNode, READ_U64DATA, &data, DEFAULT_UINT64_MAX); + if ((ret != HDF_SUCCESS) || (data != U64_DATA)) { + HDF_LOGE("%s failed, line: %d", __FUNCTION__, __LINE__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint64AttrValueFail(void) +{ + uint64_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_AUDIO_INFO); + int32_t ret = g_devResInstance->GetUint64(audioNode, INVALID_STRING, &data, DEFAULT_UINT64_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT64_MAX)) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetUint64(audioNode, READ_U64DATA, NULL, DEFAULT_UINT64_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT64_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +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}; + uint32_t i; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t count = g_devResInstance->GetElemNum(dataType, READ_FOUR_DATA_TYPE); + if (count != DATA_TYPE_NUM_U64) { + return HDF_FAILURE; + } + for (i = 0; i < count; i++) { + int32_t ret = g_devResInstance->GetUint64ArrayElem(dataType, READ_FOUR_DATA_TYPE, i, &data[i], + DEFAULT_UINT64_MAX); + if ((ret != HDF_SUCCESS) || (data[i] != testData[i])) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int HcsTestGetUint64ArrayElemFail(void) +{ + uint64_t data; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *dataType = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_DATA_TYPE_TEST); + int32_t ret = g_devResInstance->GetUint64ArrayElem(dataType, READ_FOUR_DATA_TYPE, DATA_TYPE_NUM_U64, &data, + DEFAULT_UINT64_MAX); + if ((ret == HDF_SUCCESS) || (data != DEFAULT_UINT64_MAX)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint64ArraySuccess(void) +{ + uint64_t data[DATA_TYPE_NUM_U64] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + if ((ret != HDF_SUCCESS) || (data[0] != U8_DATA) || (data[1] != U16_DATA) || (data[2] != U32_DATA) || + (data[3] != U64_DATA)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetUint64ArrayFail(void) +{ + uint64_t data[DATA_TYPE_NUM_U64 + 1] = { 0 }; + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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 + 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; + } + return HDF_SUCCESS; +} + +int HcsTestGetElemNumSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + int32_t count = g_devResInstance->GetElemNum(g_testRoot, BOARD_ID); + if (count != BOARDID_LENGTH) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + count = g_devResInstance->GetElemNum(fingerNode, READ_U32_INDEX); + if (count != DATA_TYPE_NUM_U32) { + return HDF_FAILURE; + } + count = g_devResInstance->GetElemNum(fingerNode, STRING_LIST_NAMES); + if (count != DATA_TYPE_NUM_U32) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetElemNumFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerNode = g_devResInstance->GetNodeByMatchAttr(g_testRoot, HW_FINGERPRINT_INFO); + // the dual_fingerprint attr do not array, so the count is HDF_FAILURE. + int32_t count = g_devResInstance->GetElemNum(fingerNode, DUAL_FINGERPRINT); + if (count != HDF_FAILURE) { + return HDF_FAILURE; + } + // the NULL attr is not exist, so the count is HDF_FAILURE. + count = g_devResInstance->GetElemNum(fingerNode, INVALID_STRING); + if (count != HDF_FAILURE) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetChildNodeSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetChildNode(g_testRoot, AUDIO_INFO); + if (audioNode == NULL) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); + if (fingerprintNode == NULL) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *oneNode = g_devResInstance->GetChildNode(fingerprintNode, "fingerprint_one"); + if (oneNode == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetChildNodeFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *twoNode = g_devResInstance->GetChildNode(g_testRoot, "fingerprint_two"); + if (twoNode != NULL) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *nullNode = g_devResInstance->GetChildNode(g_testRoot, INVALID_NODE); + if (nullNode != NULL) { + return HDF_FAILURE; + } + nullNode = g_devResInstance->GetChildNode(NULL, INVALID_NODE); + if (nullNode != NULL) { + return HDF_FAILURE; + } + nullNode = g_devResInstance->GetChildNode(g_testRoot, NULL); + if (nullNode != NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestTraverseAttrInNodeSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *audioNode = g_devResInstance->GetChildNode(g_testRoot, AUDIO_INFO); + if (audioNode == NULL) { + return HDF_FAILURE; + } + struct DeviceResourceAttr *pp = NULL; + DEV_RES_NODE_FOR_EACH_ATTR(audioNode, pp) { + if ((pp == NULL) || (pp->name == NULL)) { + break; + } + if (strncmp(pp->name, "dual_smartpa_delay", strlen("dual_smartpa_delay")) != 0) { + continue; + } else { + break; + } + } + if (pp == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestTraverseAttrInNodeFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); + if (fingerprintNode == NULL) { + return HDF_FAILURE; + } + struct DeviceResourceAttr *pp = NULL; + DEV_RES_NODE_FOR_EACH_ATTR(fingerprintNode, pp) { + if ((pp == NULL) || (pp->name == NULL)) { + break; + } + if (strncmp(pp->name, "dual-fingerprint", strlen("dual-fingerprint")) != 0) { + continue; + } else { + break; + } + } + if (pp != NULL) { + return HDF_FAILURE; + } + + const struct DeviceResourceNode *childNode = NULL; + DEV_RES_NODE_FOR_EACH_CHILD_NODE(fingerprintNode, childNode) { + if (childNode == NULL) { + break; + } + if ((strcmp(childNode->name, "fingerprint_one") == 0) || (strcmp(childNode->name, "fingerprint_two") == 0)) { + HDF_LOGE("%s: childNode->name is %s", __FUNCTION__, childNode->name); + continue; + } else { + HDF_LOGE("%s: failed, childNode->name is %s", __FUNCTION__, childNode->name); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +int HcsTestGetStringSuccess(void) +{ + if (!TestGetRootNode()) { + 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)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetStringFail(void) +{ + if (!TestGetRootNode()) { + 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)) { + 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)) { + return HDF_FAILURE; + } + testReadString = g_devResInstance->GetString(audioNode, INVALID_STRING, &ptype, NULL); + if (testReadString == HDF_SUCCESS || ptype != NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetStringArrayElemSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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. + 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. + ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 2, &rawDataDts, NULL); + if ((ret != HDF_SUCCESS) || (strcmp(rawDataDts, "third") != HDF_SUCCESS)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetStringArrayElemFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + 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. + 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. + 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; + } + ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 1, NULL, STRING_ATTR_VALUE); + if (ret == HDF_SUCCESS) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetStringArrayElem(fingerprintNode, STRING_LIST_NAMES, 1, &rawDataDts, NULL); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetStringArrayElem(fingerprintNode, READ_U32_INDEX, 1, NULL, STRING_ATTR_VALUE); + if (ret == HDF_SUCCESS) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetStringArrayElem(fingerprintNode, READ_U32_INDEX, 1, &rawDataDts, NULL); + if ((ret == HDF_SUCCESS) || (rawDataDts != NULL)) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetNodeAttrRefSuccess(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); + const struct DeviceResourceNode *ret = g_devResInstance->GetNodeByRefAttr(fingerprintNode, FINGER_INFO); + if (ret == NULL) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetNodeByRefAttr(fingerprintNode, AUDIO_INFO); + if (ret == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int HcsTestGetNodeAttrRefFail(void) +{ + if (!TestGetRootNode()) { + return HDF_FAILURE; + } + const struct DeviceResourceNode *fingerprintNode = g_devResInstance->GetChildNode(g_testRoot, FINGERPRINT_INFO); + const struct DeviceResourceNode *ret = g_devResInstance->GetNodeByRefAttr(fingerprintNode, DUAL_FINGERPRINT); + if (ret != NULL) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetNodeByRefAttr(NULL, DUAL_FINGERPRINT); + if (ret != NULL) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetNodeByRefAttr(fingerprintNode, NULL); + if (ret != NULL) { + return HDF_FAILURE; + } + ret = g_devResInstance->GetNodeByRefAttr(NULL, FINGER_INFO); + if (ret != NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} diff --git a/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.h b/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.h new file mode 100644 index 00000000..7b004ea3 --- /dev/null +++ b/test/unittest/ability/config/hcs_parser/unittest/hcs_config_test.h @@ -0,0 +1,66 @@ +/* + * 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 HCS_CONFIG_TEST_H +#define HCS_CONFIG_TEST_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int HcsTestCreateDMHcsToTree(void); +int HcsTestGetNodeByMatchAttrSuccess(void); +int HcsTestGetNodeByMatchAttrFail(void); +int HcsTestGetBoolAttrValueSuccess(void); +int HcsTestGetBoolAttrValueFail(void); +int HcsTestGetUint8AttrValueSuccess(void); +int HcsTestGetUint8AttrValueFail(void); +int HcsTestGetUint8ArrayElemSuccess(void); +int HcsTestGetUint8ArrayElemFail(void); +int HcsTestGetUint8ArraySuccess(void); +int HcsTestGetUint8ArrayFail(void); +int HcsTestGetUint16AttrValueSuccess(void); +int HcsTestGetUint16AttrValueFail(void); +int HcsTestGetUint16ArrayElemSuccess(void); +int HcsTestGetUint16ArrayElemFail(void); +int HcsTestGetUint16ArraySuccess(void); +int HcsTestGetUint16ArrayFail(void); +int HcsTestGetUint32AttrValueSuccess(void); +int HcsTestGetUint32AttrValueFail(void); +int HcsTestGetUint32ArrayElemSuccess(void); +int HcsTestGetUint32ArrayElemFail(void); +int HcsTestGetUint32ArraySuccess(void); +int HcsTestGetUint32ArrayFail(void); +int HcsTestGetUint64AttrValueSuccess(void); +int HcsTestGetUint64AttrValueFail(void); +int HcsTestGetUint64ArrayElemSuccess(void); +int HcsTestGetUint64ArrayElemFail(void); +int HcsTestGetUint64ArraySuccess(void); +int HcsTestGetUint64ArrayFail(void); +int HcsTestGetElemNumSuccess(void); +int HcsTestGetElemNumFail(void); +int HcsTestGetChildNodeSuccess(void); +int HcsTestGetChildNodeFail(void); +int HcsTestTraverseAttrInNodeSuccess(void); +int HcsTestTraverseAttrInNodeFail(void); +int HcsTestGetStringSuccess(void); +int HcsTestGetStringFail(void); +int HcsTestGetStringArrayElemSuccess(void); +int HcsTestGetStringArrayElemFail(void); +int HcsTestGetNodeAttrRefSuccess(void); +int HcsTestGetNodeAttrRefFail(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* HCS_CONFIG_TEST_H */ diff --git a/test/unittest/common/hdf_common_test.c b/test/unittest/common/hdf_common_test.c new file mode 100644 index 00000000..d3c9cf8b --- /dev/null +++ b/test/unittest/common/hdf_common_test.c @@ -0,0 +1,86 @@ +/* + * 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 +#include +#include +#include "hdf_io_service_if.h" +#include "hdf_uhdf_test.h" + +static struct HdfIoService *g_testService = NULL; +static struct HdfSBuf *g_msg = NULL; +static struct HdfSBuf *g_reply = NULL; + +void HdfTestOpenService(void) +{ + g_testService = HdfIoServiceBind(HDF_TEST_SERVICE_NAME); + g_msg = HdfSBufObtainDefaultSize(); + if (g_msg == NULL) { + printf("fail to obtain sbuf data\n\r"); + return; + } + g_reply = HdfSBufObtainDefaultSize(); + if (g_reply == NULL) { + printf("fail to obtain sbuf reply\n\r"); + HdfSBufRecycle(g_msg); + return; + } +} + +void HdfTestCloseService(void) +{ + if (g_msg != NULL) { + HdfSBufRecycle(g_msg); + g_msg = NULL; + }; + if (g_reply != NULL) { + HdfSBufRecycle(g_reply); + g_reply = NULL; + }; + if (g_testService != NULL) { + HdfIoServiceRecycle(g_testService); + g_testService = NULL; + }; +} + +int HdfTestSendMsgToService(struct HdfTestMsg *msg) +{ + int ret; + struct HdfTestMsg *testReply = NULL; + unsigned int len; + CHECK_TEST_NULL_PTR_RETURN(g_testService); + CHECK_TEST_NULL_PTR_RETURN(g_msg); + CHECK_TEST_NULL_PTR_RETURN(g_reply); + CHECK_TEST_NULL_PTR_RETURN(msg); + + if (!HdfSbufWriteBuffer(g_msg, msg, sizeof(*msg))) { + printf("HdfTestSendMsgToService g_msg write failed\n\r"); + } + + ret = g_testService->dispatcher->Dispatch(&g_testService->object, 0, g_msg, g_reply); + if (ret != HDF_SUCCESS) { + printf("HdfTestSendMsgToService fail to send service call\n\r"); + return ret; + } + + if (!HdfSbufReadBuffer(g_reply, (const void **)&testReply, &len)) { + printf("HdfTestSendMsgToService g_reply read failed\n\r"); + } + + if (testReply == NULL) { + printf("HdfTestSendMsgToService testReply is null\n\r"); + ret = -1; + } else { + ret = testReply->result; + } + HdfSbufFlush(g_msg); + HdfSbufFlush(g_reply); + + return ret; +} + diff --git a/test/unittest/common/hdf_main_test.c b/test/unittest/common/hdf_main_test.c new file mode 100644 index 00000000..039fe902 --- /dev/null +++ b/test/unittest/common/hdf_main_test.c @@ -0,0 +1,195 @@ +/* + * 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 "hdf_base.h" +#include "hdf_config_test.h" +#include "hdf_device_desc.h" +#include "hdf_main_test.h" +#include "osal_test_entry.h" + +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM) || defined(CONFIG_DRIVERS_HDF_PLATFORM) +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_GPIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_GPIO) +#include "hdf_gpio_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_I2C) || defined(CONFIG_DRIVERS_HDF_PLATFORM_I2C) +#include "hdf_i2c_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SPI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SPI) +#include "hdf_spi_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SDIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SDIO) +#include "hdf_sdio_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_UART) || defined(CONFIG_DRIVERS_HDF_PLATFORM_UART) +#include "hdf_uart_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_WATCHDOG) || defined(CONFIG_DRIVERS_HDF_PLATFORM_WATCHDOG) +#include "hdf_watchdog_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_RTC) +#include "hdf_rtc_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MIPI_DSI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MIPI_DSI) +#include "hdf_mipi_dsi_entry_test.h" +#endif +#if (defined(LOSCFG_STORAGE_EMMC) && defined(LOSCFG_DRIVERS_HDF_PLATFORM_EMMC)) || \ + defined(CONFIG_DRIVERS_HDF_PLATFORM_EMMC) +#include "hdf_emmc_entry_test.h" +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PWM) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PWM) +#include "hdf_pwm_entry_test.h" +#endif +#endif +#if defined(LOSCFG_DRIVERS_HDF_WIFI) || defined(CONFIG_DRIVERS_HDF_WIFI) +#include "hdf_wifi_test.h" +#endif + +#define HDF_LOG_TAG hdf_test + +// add submodule entry +HdfTestFuncList g_hdfTestFuncList[] = { +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM) || defined(CONFIG_DRIVERS_HDF_PLATFORM) +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_GPIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_GPIO) + { TEST_PAL_GPIO_TYPE, HdfGpioTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_I2C) || defined(CONFIG_DRIVERS_HDF_PLATFORM_I2C) + { TEST_PAL_I2C_TYPE, HdfI2cTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SPI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SPI) + { TEST_PAL_SPI_TYPE, HdfSpiUnitTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_UART) || defined(CONFIG_DRIVERS_HDF_PLATFORM_UART) + { TEST_PAL_UART_TYPE, HdfUartUnitTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_WATCHDOG) || defined(CONFIG_DRIVERS_HDF_PLATFORM_WATCHDOG) + { TEST_PAL_WDT_TYPE, HdfWatchdogTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_RTC) + { TEST_PAL_RTC_TYPE, HdfRtcEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_MIPI_DSI) || defined(CONFIG_DRIVERS_HDF_PLATFORM_MIPI_DSI) + { TEST_PAL_MIPI_DSI_TYPE, HdfMipiDsiEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_SDIO) || defined(CONFIG_DRIVERS_HDF_PLATFORM_SDIO) + { TEST_PAL_SDIO_TYPE, HdfSdioUnitTestEntry }, +#endif +#if (defined(LOSCFG_STORAGE_EMMC) && defined(LOSCFG_DRIVERS_HDF_PLATFORM_EMMC)) || \ + defined(CONFIG_DRIVERS_HDF_PLATFORM_EMMC) + { TEST_PAL_EMMC_TYPE, HdfEmmcUnitTestEntry }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_PWM) || defined(CONFIG_DRIVERS_HDF_PLATFORM_PWM) + { TEST_PAL_PWM_TYPE, HdfPwmUnitTestEntry }, +#endif +#endif + { TEST_CONFIG_TYPE, HdfConfigEntry }, + { TEST_OSAL_ITEM, HdfOsalEntry }, +#if defined(LOSCFG_DRIVERS_HDF_WIFI) || defined(CONFIG_DRIVERS_HDF_WIFI) + {TEST_WIFI_TYPE, HdfWifiEntry} +#endif +}; + +static int32_t HdfTestCaseProcess(struct HdfDeviceIoClient *client, + int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + HdfTestMsg *msg = NULL; + HdfTestMsg replyMsg; + uint32_t len; + int i; + struct TestService *testService = NULL; + + if (client == NULL || client->device == NULL) { + HDF_LOGE("%s:: client or client->device is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + if (data == NULL || reply == NULL) { + HDF_LOGE("%s:: data or reply is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + + testService = (struct TestService *)client->device->service; + if (testService == NULL) { + HDF_LOGE("%s:: service is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + if (!HdfSbufReadBuffer(data, (const void **)&msg, &len)) { + HDF_LOGE("%s:: msg sbuf read fail", __func__); + return HDF_ERR_INVALID_PARAM; + } + + replyMsg.cmd = msg->cmd; + replyMsg.subCmd = msg->subCmd; + + HDF_LOGE("%s::Hdf test receive cmd: command[%d], subCommand[%d]", __func__, msg->cmd, msg->subCmd); + + replyMsg.result = HDF_FAILURE; + for (i = 0; i < sizeof(g_hdfTestFuncList) / sizeof(g_hdfTestFuncList[0]); ++i) { + if ((msg->cmd == g_hdfTestFuncList[i].cmd) && (g_hdfTestFuncList[i].testFunc != NULL)) { + g_hdfTestFuncList[i].testFunc(&replyMsg); + break; + } + } + + if (!HdfSbufWriteBuffer(reply, &replyMsg, sizeof(replyMsg))) { + HDF_LOGE("%s:: hdf test sbuf write fail", __func__); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +void HdfTestDriverRelease(struct HdfDeviceObject *device) +{ + return; +} + +void HdfTestDriverDispatch(struct HdfDeviceObject *device) +{ + return; +} + +int HdfTestDriverBind(struct HdfDeviceObject *device) +{ + if (device == NULL) { + return -1; + } + + static struct TestService testService = { + .testRemoteService.Dispatch = HdfTestCaseProcess, + }; + device->service = &testService.testRemoteService; + return 0; +} + +static struct HdfDeviceObject *g_devObject; +struct HdfDeviceObject *GetDeviceObject(void) +{ + return g_devObject; +} + +int HdfTestDriverInit(struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%s::ptr is null!\n", __func__); + return -1; + } + g_devObject = device; + return 0; +} + +struct HdfDriverEntry g_hdfTestDevice = { + .moduleVersion = 1, + .moduleName = "HDF_TEST", + .Bind = HdfTestDriverBind, + .Init = HdfTestDriverInit, + .Release = HdfTestDriverRelease, +}; + +HDF_INIT(g_hdfTestDevice); diff --git a/test/unittest/common/hdf_main_test.h b/test/unittest/common/hdf_main_test.h new file mode 100644 index 00000000..be051bd9 --- /dev/null +++ b/test/unittest/common/hdf_main_test.h @@ -0,0 +1,75 @@ +/* + * 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_MAIN_TEST_H +#define HDF_MAIN_TEST_H + +#include "hdf_object.h" +#include "hdf_device_desc.h" + +typedef struct { + uint16_t cmd; // submodule command + uint8_t subCmd; // test case command + int8_t result; +} HdfTestMsg; + +typedef int32_t (*TestFunc)(HdfTestMsg*); +typedef int32_t (*TestCaseFunc)(void); +typedef struct { + uint16_t cmd; // submodule command + TestFunc testFunc; // function +} HdfTestFuncList; +typedef struct { + uint8_t subCmd; // test case command + TestCaseFunc testFunc; // test case function +} HdfTestCaseList; + +struct TestService { + struct IDeviceIoService testRemoteService; +}; + +// two hundred values allocated per submodule +typedef enum { + TEST_PAL_I2C_TYPE = 0, + TEST_PAL_SPI_TYPE = 1, + TEST_PAL_GPIO_TYPE = 2, + TEST_PAL_PINCTRL_TYPE = 3, + TEST_PAL_CLOCK_TYPE = 4, + TEST_PAL_REGULATOR_TYPE = 5, + TEST_PAL_MIPI_DSI_TYPE = 6, + TEST_PAL_UART_TYPE = 7, + TEST_PAL_SDIO_TYPE = 8, + TEST_PAL_MDIO_TYPE = 9, + TEST_PAL_APB_TYPE = 10, + TEST_PAL_PCIE_TYPE = 11, + TEST_PAL_PCM_TYPE = 12, + TEST_PAL_I2S_TYPE = 13, + TEST_PAL_PWM_TYPE = 14, + TEST_PAL_DMA_TYPE = 15, + TEST_PAL_EFUSE_TYPE = 16, + TEST_PAL_FLASH_TYPE = 17, + TEST_PAL_EMMC_TYPE = 18, + TEST_PAL_RTC_TYPE = 19, + TEST_PAL_ADC_TYPE = 20, + TEST_PAL_WDT_TYPE = 21, + TEST_PAL_I3C_TYPE = 22, + TEST_PAL_END = 200, + TEST_OSAL_BEGIN = TEST_PAL_END, +#define HDF_OSAL_TEST_ITEM(v) (TEST_OSAL_BEGIN + (v)) + TEST_OSAL_ITEM = HDF_OSAL_TEST_ITEM(1), + TEST_OSAL_END = 400, + TEST_WIFI_BEGIN = TEST_OSAL_END, + TEST_WIFI_TYPE = TEST_WIFI_BEGIN + 1, + TEST_WIFI_END = 600, + TEST_CONFIG_TYPE = 601, + TEST_HDF_FRAME_END = 800, +} HdfTestSubModuleCmd; + +struct HdfDeviceObject *GetDeviceObject(void); + +#endif // HDF_MAIN_TEST_H diff --git a/test/unittest/config/hdf_config_test.c b/test/unittest/config/hdf_config_test.c new file mode 100644 index 00000000..7cf001db --- /dev/null +++ b/test/unittest/config/hdf_config_test.c @@ -0,0 +1,82 @@ +/* + * 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_config_test.h" +#include "device_resource_if.h" +#include "hcs_config_test.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "osal_mem.h" + +// add test case entry +HdfTestCaseList g_hdfConfigTestCaseList[] = { + { HDF_CREATE_DM_HCS_TO_TREE_001, HcsTestCreateDMHcsToTree }, + { HDF_GET_NODE_BY_ATTR_VALUE_001, HcsTestGetNodeByMatchAttrSuccess }, + { HDF_GET_NODE_BY_ATTR_VALUE_002, HcsTestGetNodeByMatchAttrFail }, + { HDF_GET_BOOL_ATTR_VALUE_001, HcsTestGetBoolAttrValueSuccess }, + { HDF_GET_BOOL_ATTR_VALUE_002, HcsTestGetBoolAttrValueFail }, + { HDF_GET_UINT8_ATTR_VALUE_001, HcsTestGetUint8AttrValueSuccess }, + { HDF_GET_UINT8_ATTR_VALUE_002, HcsTestGetUint8AttrValueFail }, + { HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, HcsTestGetUint8ArrayElemSuccess }, + { HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, HcsTestGetUint8ArrayElemFail }, + { HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, HcsTestGetUint8ArraySuccess }, + { HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, HcsTestGetUint8ArrayFail }, + { HDF_GET_UINT16_ATTR_VALUE_001, HcsTestGetUint16AttrValueSuccess }, + { HDF_GET_UINT16_ATTR_VALUE_002, HcsTestGetUint16AttrValueFail }, + { HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, HcsTestGetUint16ArrayElemSuccess }, + { HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, HcsTestGetUint16ArrayElemFail }, + { HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, HcsTestGetUint16ArraySuccess }, + { HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, HcsTestGetUint16ArrayFail }, + { HDF_GET_UINT32_ATTR_VALUE_001, HcsTestGetUint32AttrValueSuccess }, + { HDF_GET_UINT32_ATTR_VALUE_002, HcsTestGetUint32AttrValueFail }, + { HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, HcsTestGetUint32ArrayElemSuccess }, + { HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, HcsTestGetUint32ArrayElemFail }, + { HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, HcsTestGetUint32ArraySuccess }, + { HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, HcsTestGetUint32ArrayFail }, + { HDF_GET_UINT64_ATTR_VALUE_001, HcsTestGetUint64AttrValueSuccess }, + { HDF_GET_UINT64_ATTR_VALUE_002, HcsTestGetUint64AttrValueFail }, + { HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, HcsTestGetUint64ArrayElemSuccess }, + { HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, HcsTestGetUint64ArrayElemFail }, + { HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, HcsTestGetUint64ArraySuccess }, + { HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, HcsTestGetUint64ArrayFail }, + { HDF_GET_ELEM_NUM_VALUE_001, HcsTestGetElemNumSuccess }, + { HDF_GET_ELEM_NUM_VALUE_002, HcsTestGetElemNumFail }, + { HDF_GET_CHILD_NODE_001, HcsTestGetChildNodeSuccess }, + { HDF_GET_CHILD_NODE_002, HcsTestGetChildNodeFail }, + { HDF_TRAVERSE_ATTR_IN_NODE_001, HcsTestTraverseAttrInNodeSuccess }, + { HDF_TRAVERSE_ATTR_IN_NODE_002, HcsTestTraverseAttrInNodeFail }, + { HDF_GET_STRING_ATTR_VALUE_001, HcsTestGetStringSuccess }, + { HDF_GET_STRING_ATTR_VALUE_002, HcsTestGetStringFail }, + { HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, HcsTestGetStringArrayElemSuccess }, + { HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, HcsTestGetStringArrayElemFail }, + { HDF_GET_NODE_BY_ATTR_REF_001, HcsTestGetNodeAttrRefSuccess }, + { HDF_GET_NODE_BY_ATTR_REF_002, HcsTestGetNodeAttrRefFail }, +}; + +int32_t HdfConfigEntry(HdfTestMsg *msg) +{ + int i; + if (msg == NULL) { + return HDF_FAILURE; + } + + for (i = 0; i < sizeof(g_hdfConfigTestCaseList) / sizeof(g_hdfConfigTestCaseList[0]); ++i) { + if (msg->subCmd != g_hdfConfigTestCaseList[i].subCmd) { + continue; + } + if (g_hdfConfigTestCaseList[i].testFunc == NULL) { + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = g_hdfConfigTestCaseList[i].testFunc(); + if (msg->result != HDF_SUCCESS) { + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} diff --git a/test/unittest/config/hdf_config_test.h b/test/unittest/config/hdf_config_test.h new file mode 100644 index 00000000..8c719300 --- /dev/null +++ b/test/unittest/config/hdf_config_test.h @@ -0,0 +1,60 @@ +/* + * 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_CONFIG_TEST_H +#define HDF_CONFIG_TEST_H + +#include "hdf_main_test.h" + +enum HdfConfigTestCaseCmd { + HDF_CREATE_DM_HCS_TO_TREE_001, + HDF_GET_NODE_BY_ATTR_VALUE_001, + HDF_GET_NODE_BY_ATTR_VALUE_002, + HDF_GET_BOOL_ATTR_VALUE_001, + HDF_GET_BOOL_ATTR_VALUE_002, + HDF_GET_UINT8_ATTR_VALUE_001, + HDF_GET_UINT8_ATTR_VALUE_002, + HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT8_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT8_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT8_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT16_ATTR_VALUE_001, + HDF_GET_UINT16_ATTR_VALUE_002, + HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT16_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT16_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT16_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT32_ATTR_VALUE_001, + HDF_GET_UINT32_ATTR_VALUE_002, + HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT32_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT32_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT32_ARRAY_ATTR_VALUE_002, + HDF_GET_UINT64_ATTR_VALUE_001, + HDF_GET_UINT64_ATTR_VALUE_002, + HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_UINT64_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_UINT64_ARRAY_ATTR_VALUE_001, + HDF_GET_UINT64_ARRAY_ATTR_VALUE_002, + HDF_GET_ELEM_NUM_VALUE_001, + HDF_GET_ELEM_NUM_VALUE_002, + HDF_GET_CHILD_NODE_001, + HDF_GET_CHILD_NODE_002, + HDF_TRAVERSE_ATTR_IN_NODE_001, + HDF_TRAVERSE_ATTR_IN_NODE_002, + HDF_GET_STRING_ATTR_VALUE_001, + HDF_GET_STRING_ATTR_VALUE_002, + HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_001, + HDF_GET_STRING_ARRAY_ELEM_ATTR_VALUE_002, + HDF_GET_NODE_BY_ATTR_REF_001, + HDF_GET_NODE_BY_ATTR_REF_002, +}; + +int32_t HdfConfigEntry(HdfTestMsg *msg); + +#endif // HDF_CONFIG_TEST_H diff --git a/test/unittest/include/hdf_uhdf_test.h b/test/unittest/include/hdf_uhdf_test.h new file mode 100644 index 00000000..dcd4f486 --- /dev/null +++ b/test/unittest/include/hdf_uhdf_test.h @@ -0,0 +1,77 @@ +/* + * 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_UHDF_TEST_H +#define HDF_UHDF_TEST_H + +#include "hdf_base.h" + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +#define HDF_TEST_SERVICE_NAME "HDF_TEST" +#define CHECK_TEST_NULL_PTR_RETURN(ptr) do { \ + if ((ptr) == NULL) { \ + printf("pointer is null and return\n\r"); \ + return HDF_FAILURE; \ + } \ +} while (0) + +struct HdfTestMsg { + uint16_t cmd; // submodule command + uint8_t subCmd; // test case command + int8_t result; +}; + +// two hundred values allocated per submodule +enum HdfTestSubModuleCmd { + TEST_PAL_I2C_TYPE = 0, + TEST_PAL_SPI_TYPE = 1, + TEST_PAL_GPIO_TYPE = 2, + TEST_PAL_PINCTRL_TYPE = 3, + TEST_PAL_CLOCK_TYPE = 4, + TEST_PAL_REGULATOR_TYPE = 5, + TEST_PAL_MIPI_DSI_TYPE = 6, + TEST_PAL_UART_TYPE = 7, + TEST_PAL_SDIO_TYPE = 8, + TEST_PAL_MDIO_TYPE = 9, + TEST_PAL_APB_TYPE = 10, + TEST_PAL_PCIE_TYPE = 11, + TEST_PAL_PCM_TYPE = 12, + TEST_PAL_I2S_TYPE = 13, + TEST_PAL_PWM_TYPE = 14, + TEST_PAL_DMA_TYPE = 15, + TEST_PAL_EFUSE_TYPE = 16, + TEST_PAL_FLASH_TYPE = 17, + TEST_PAL_EMMC_TYPE = 18, + TEST_PAL_RTC_TYPE = 19, + TEST_PAL_ADC_TYPE = 20, + TEST_PAL_WDT_TYPE = 21, + TEST_PAL_I3C_TYPE = 22, + TEST_PAL_END = 200, + TEST_OSAL_BEGIN = TEST_PAL_END, +#define HDF_OSAL_TEST_ITEM(v) (TEST_OSAL_BEGIN + (v)) + TEST_OSAL_ITEM = HDF_OSAL_TEST_ITEM(1), + TEST_OSAL_END = 400, + TEST_WIFI_BEGIN = TEST_OSAL_END, + TEST_WIFI_TYPE = TEST_WIFI_BEGIN + 1, + TEST_WIFI_END = 600, + TEST_CONFIG_TYPE = 601, + TEST_HDF_FRAME_END = 800, +}; + +void HdfTestOpenService(void); +void HdfTestCloseService(void); +int HdfTestSendMsgToService(struct HdfTestMsg *msg); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif // HDF_UHDF_TEST_H \ No newline at end of file diff --git a/test/unittest/manager/sample_driver_test.c b/test/unittest/manager/sample_driver_test.c new file mode 100644 index 00000000..eac190dc --- /dev/null +++ b/test/unittest/manager/sample_driver_test.c @@ -0,0 +1,139 @@ +/* + * 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 "sample_driver_test.h" +#include "devsvc_manager_clnt.h" +#include "hdf_log.h" +#include "hdf_device_desc.h" + +#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; + return; +} + +int32_t SampleDriverRegisterDevice(struct HdfSBuf *data) +{ + if (data == NULL) { + return HDF_FAILURE; + } + + const char *moduleName = HdfSbufReadString(data); + if (moduleName == NULL) { + return HDF_FAILURE; + } + const char *serviceName = HdfSbufReadString(data); + if (serviceName == NULL) { + return HDF_FAILURE; + } + + struct HdfDeviceObject *devObj = HdfRegisterDevice(moduleName, serviceName); + if (devObj == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t SampleDriverUnregisterDevice(struct HdfSBuf *data) +{ + if (data == NULL) { + return HDF_FAILURE; + } + + const char *moduleName = HdfSbufReadString(data); + if (moduleName == NULL) { + return HDF_FAILURE; + } + const char *serviceName = HdfSbufReadString(data); + if (serviceName == NULL) { + return HDF_FAILURE; + } + HdfUnregisterDevice(moduleName, serviceName); + return HDF_SUCCESS; +} + +int32_t SampleDriverSendEvent(struct HdfDeviceIoClient *client, int id, struct HdfSBuf *data, bool broadcast) +{ + return broadcast ? HdfDeviceSendEvent(client->device, id, data) : HdfDeviceSendEventToClient(client, id, data); +} + +int32_t SampleDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_SUCCESS; + if (reply == NULL || client == NULL) { + return HDF_FAILURE; + } + switch (cmdId) { + case SAMPLE_DRIVER_REGISTER_DEVICE: { + ret = SampleDriverRegisterDevice(data); + HdfSbufWriteInt32(reply, ret); + break; + } + case SAMPLE_DRIVER_UNREGISTER_DEVICE: + ret = SampleDriverUnregisterDevice(data); + HdfSbufWriteInt32(reply, ret); + break; + case SAMPLE_DRIVER_SENDEVENT_SINGLE_DEVICE: + ret = SampleDriverSendEvent(client, cmdId, data, false); + HdfSbufWriteInt32(reply, INT32_MAX); + break; + case SAMPLE_DRIVER_SENDEVENT_BROADCAST_DEVICE: + ret = SampleDriverSendEvent(client, cmdId, data, true); + HdfSbufWriteInt32(reply, INT32_MAX); + break; + default: + break; + } + + return ret; +} + +int HdfSampleDriverBind(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGD("%s::enter!, deviceObject=%p", __func__, deviceObject); + if (deviceObject == NULL) { + return HDF_FAILURE; + } + static struct IDeviceIoService testService = { + .Dispatch = SampleDriverDispatch, + .Open = NULL, + .Release = NULL, + }; + deviceObject->service = &testService; + return HDF_SUCCESS; +} + +int HdfSampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGD("%s::enter!, deviceObject=%p", __func__, deviceObject); + if (deviceObject == NULL) { + HDF_LOGE("%s::ptr is null!", __func__); + return HDF_FAILURE; + } + HDF_LOGD("%s:Init success", __func__); + return HDF_SUCCESS; +} + + +struct HdfDriverEntry g_sampleDriverEntry = { + .moduleVersion = 1, + .moduleName = "sample_driver", + .Bind = HdfSampleDriverBind, + .Init = HdfSampleDriverInit, + .Release = HdfSampleDriverRelease, +}; + +HDF_INIT(g_sampleDriverEntry); + diff --git a/test/unittest/manager/sample_driver_test.h b/test/unittest/manager/sample_driver_test.h new file mode 100644 index 00000000..3241601b --- /dev/null +++ b/test/unittest/manager/sample_driver_test.h @@ -0,0 +1,26 @@ +/* + * 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_SAMPLE_DRIVER_H +#define HDF_SAMPLE_DRIVER_H + +#include "hdf_object.h" + +#define SAMPLE_SERVICE "sample_service" + +typedef enum { + SAMPLE_DRIVER_REGISTER_DEVICE = 0, + SAMPLE_DRIVER_UNREGISTER_DEVICE, + SAMPLE_DRIVER_SENDEVENT_SINGLE_DEVICE, + SAMPLE_DRIVER_SENDEVENT_BROADCAST_DEVICE, +} SAMPLE_DRIVER_CMDID; + +struct HdfDeviceObject *GetDeviceObject(void); + +#endif // HDF_MAIN_TEST_H + diff --git a/test/unittest/model/network/wifi/unittest/message/hdf_message_test.h b/test/unittest/model/network/wifi/unittest/message/hdf_message_test.h new file mode 100644 index 00000000..b15c7df4 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/message/hdf_message_test.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 WIFI_MESSAGE_TEST_H +#define WIFI_MESSAGE_TEST_H +#include "hdf_base.h" + +#define MSG_BREAK_IF(ERRCODE_VAR, CONDITION) \ + if (CONDITION) { \ + HDF_LOGE("%s:Line=%d:Check " #CONDITION, __func__, __LINE__); \ + ERRCODE_VAR = HDF_FAILURE; \ + break; \ + } + +#define MSG_RETURN_IF(CONDITION) \ + do { \ + if (CONDITION) { \ + HDF_LOGE("%s:Line=%d:Check " #CONDITION, __func__, __LINE__); \ + return HDF_FAILURE; \ + } \ + } while (false) + +#define MSG_BREAK_IF_NOT_SUCCESS(ERROR_CODE) \ + if ((ERROR_CODE) != HDF_SUCCESS) { \ + HDF_LOGE("%s:Line=%d,errCode=%d", __func__, __LINE__, (ERROR_CODE)); \ + errCode = HDF_FAILURE; \ + break; \ + } + +#define MSG_RETURN_IF_FUNCTION_FAILED(ERRCODE_VAR, FUNCTION_CALL) \ + do { \ + ERRCODE_VAR = FUNCTION_CALL; \ + if ((ERRCODE_VAR) != 0) { \ + HDF_LOGE("%s:Line=%d:Ret=%d,Call " #FUNCTION_CALL, __func__, __LINE__, ERRCODE_VAR); \ + return ERRCODE_VAR; \ + } \ + } while (false) + +#define MSG_BREAK_IF_FUNCTION_FAILED(ERRCODE_VAR, FUNCTION_CALL) \ + ERRCODE_VAR = FUNCTION_CALL; \ + if ((ERRCODE_VAR) != 0) { \ + HDF_LOGE("%s:Line=%d:Ret=%d,Call " #FUNCTION_CALL, __func__, __LINE__, ERRCODE_VAR); \ + break; \ + } + + +int32_t MessageQueueTest001(void); +int32_t MessageQueueTest002(void); +int32_t MessageQueueTest003(void); +int32_t MessageSingleNodeTest001(void); +int32_t MessageSingleNodeTest002(void); +int32_t MessageSingleNodeTest003(void); +int32_t MessageSingleNodeTest004(void); +int32_t MessageSingleNodeTest005(void); + +#endif \ No newline at end of file diff --git a/test/unittest/model/network/wifi/unittest/message/hdf_queue_test.c b/test/unittest/model/network/wifi/unittest/message/hdf_queue_test.c new file mode 100644 index 00000000..04b2f5cc --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/message/hdf_queue_test.c @@ -0,0 +1,168 @@ +/* + * 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_log.h" +#include "hdf_message_test.h" +#include "hdf_wlan_priority_queue.h" +#include "osal_thread.h" +#include "osal_time.h" + + +#define TEST_QUEUE_SIZE 30 + +#define NO_PRIORITY 1 +#define MUTI_PRIORITY 2 + +#define POP_TIMEOUT 3000 +int32_t MessageQueueTest001(void) +{ + int a = 1; + int b = 2; + int c = 3; + int d = 4; + int32_t errCode; + PriorityQueue *queue = CreatePriorityQueue(TEST_QUEUE_SIZE, NO_PRIORITY); + if (queue == NULL) { + HDF_LOGE("%s:Create queue failed!", __func__); + return -1; + } + do { + errCode = PushPriorityQueue(queue, 0, &a); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 0, &b); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 0, &c); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 0, &d); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + void *p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &a); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &b); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &c); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &d); + } while (0); + + DestroyPriorityQueue(queue); + + return errCode; +} + +// Proprity test +int32_t MessageQueueTest002(void) +{ + int a = 1; + int b = 2; + int c = 3; + int d = 4; + int32_t errCode; + PriorityQueue *queue = CreatePriorityQueue(TEST_QUEUE_SIZE, MUTI_PRIORITY); + if (queue == NULL) { + HDF_LOGE("%s:Create queue failed!", __func__); + return -1; + } + do { + errCode = PushPriorityQueue(queue, 0, &a); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 1, &b); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 1, &c); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + errCode = PushPriorityQueue(queue, 0, &d); + MSG_BREAK_IF_NOT_SUCCESS(errCode); + + void *p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &a); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &d); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &b); + + p = PopPriorityQueue(queue, 0); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &c); + } while (0); + + DestroyPriorityQueue(queue); + return errCode; +} + +int g_testValue = 0; +#define PUSH_DELAY 2000 +static int RunPushQueue(void *para) +{ + if (para == NULL) { + return -1; + } + OsalMSleep(PUSH_DELAY); + PushPriorityQueue((PriorityQueue *)para, 0, &g_testValue); + return 0; +} + +// wait and awake test +int32_t MessageQueueTest003(void) +{ + int32_t errCode = HDF_SUCCESS; + PriorityQueue *queue = CreatePriorityQueue(TEST_QUEUE_SIZE, NO_PRIORITY); + if (queue == NULL) { + HDF_LOGE("%s:Create queue failed!", __func__); + return -1; + } + OSAL_DECLARE_THREAD(pushThread); + do { + struct OsalThreadParam config = { + .name = "PushQueueWithDelay", + .priority = OSAL_THREAD_PRI_DEFAULT, + .stackSize = 0x1000, + }; + + int32_t status = OsalThreadCreate(&pushThread, RunPushQueue, queue); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadCreate failed!status=%d", __func__, status); + errCode = HDF_FAILURE; + break; + } + status = OsalThreadStart(&pushThread, &config); + if (status != HDF_SUCCESS) { + HDF_LOGE("%s:OsalThreadStart failed!status=%d", __func__, status); + OsalThreadDestroy(&pushThread); + errCode = HDF_FAILURE; + break; + } + + void *p = PopPriorityQueue(queue, POP_TIMEOUT); + MSG_BREAK_IF(errCode, p == NULL); + MSG_BREAK_IF(errCode, p != &g_testValue); + } while (false); + + OsalThreadDestroy(&pushThread); + DestroyPriorityQueue(queue); + return errCode; +} diff --git a/test/unittest/model/network/wifi/unittest/message/hdf_single_node_message_test.c b/test/unittest/model/network/wifi/unittest/message/hdf_single_node_message_test.c new file mode 100644 index 00000000..e1105160 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/message/hdf_single_node_message_test.c @@ -0,0 +1,320 @@ +/* + * 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_test.h" +#include "message/message_types.h" +#include "message/message_router.h" +#include "message/sidecar.h" +#include "hdf_log.h" +#include "hdf_sbuf.h" +#include "osal_time.h" + +const uint32_t SEND_MESSAGE_COUNT = 40000; +const uint32_t SYNC_MESSAGE_TIMEOUT = 2; +const uint32_t ASYNC_MESSAGE_TIMEOUT = 2; +#define COMMON_SEM_TIMEOUT 300 + +enum ServiceList { + SERVICE_ID_A = 10, + SERVICE_ID_B +}; + +const uint8_t CUSTOM_DISPATCHER_ID = 1; +const uint8_t SINGLE_NODE_TEST_CUSTOM_DISPATCHER_PRIORITYLEVEL = 4; +const uint32_t SINGLE_NODE_TEST_CUSTOM_DISPATCHER_QUEUESIZE = 10000; + +const uint16_t SMALL_LOAD_WAIT_TIME = 500; + + +#define CMD_LIST_MAX_SIZE 32 +uint8_t g_cmdList[CMD_LIST_MAX_SIZE]; +uint8_t g_cmdListCount = 0; + +void ClearRecvQueue(void) +{ + g_cmdListCount = 0; +} + +uint8_t GetCMDByIndex(uint8_t index) +{ + return g_cmdList[index]; +} + +size_t GetRecvQueueSize(void) +{ + return g_cmdListCount; +} + +static ErrorCode FuncNoLoad(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)reqData; + (void)rspData; + (void)context; + return ME_SUCCESS; +} + +static ErrorCode FuncSmallLoad(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + (void)reqData; + (void)rspData; + HDF_LOGI("Handle message %d\n", context->commandId); + + OsalMSleep(SMALL_LOAD_WAIT_TIME); + if (g_cmdListCount >= CMD_LIST_MAX_SIZE) { + HDF_LOGE("%s:Too much cmd!", __func__); + return HDF_FAILURE; + } + g_cmdList[g_cmdListCount++] = context->commandId; + HDF_LOGI("Finish handle message %d\n", context->commandId); + return ME_SUCCESS; +} + +static struct MessageDef g_testServiceACmds[] = { + DUEMessage(0, FuncNoLoad, 1) +}; + +ServiceDefine(TestServiceA, SERVICE_ID_A, g_testServiceACmds); + +static struct MessageDef g_testServiceBCmds[] = { + DUEMessage(0, FuncNoLoad, 2), // commandId = 0 + DUEMessage(1, FuncSmallLoad, 0), + DUEMessage(2, FuncSmallLoad, 1), + DUEMessage(3, FuncSmallLoad, 2), + DUEMessage(4, FuncSmallLoad, 3), +}; + +ServiceDefine(TestServiceB, SERVICE_ID_B, g_testServiceBCmds); + +Service *g_serviceA = NULL; +Service *g_serviceB = NULL; +bool g_dispatcherInited = false; + +int32_t StartEnv(void) +{ + int32_t errCode; + if (!g_dispatcherInited) { + DispatcherConfig config = { + .dispatcherId = CUSTOM_DISPATCHER_ID, + .priorityLevelCount = SINGLE_NODE_TEST_CUSTOM_DISPATCHER_PRIORITYLEVEL, + .queueSize = SINGLE_NODE_TEST_CUSTOM_DISPATCHER_QUEUESIZE + }; + MSG_RETURN_IF_FUNCTION_FAILED(errCode, AddDispatcher(&config)); + g_dispatcherInited = true; + } + if (g_serviceA == NULL) { + ServiceCfg cfgA = { + .dispatcherId = DEFAULT_DISPATCHER_ID + }; + g_serviceA = CreateService(TestServiceA, &cfgA); + MSG_RETURN_IF(g_serviceA == NULL); + } + + if (g_serviceB == NULL) { + ServiceCfg cfgB = { + .dispatcherId = CUSTOM_DISPATCHER_ID + }; + g_serviceB = CreateService(TestServiceB, &cfgB); + MSG_RETURN_IF(g_serviceB == NULL); + } + return HDF_SUCCESS; +} + +int32_t StopEnv(void) +{ + if (g_serviceA != NULL) { + if (g_serviceA->Destroy != NULL) { + g_serviceA->Destroy(g_serviceA); + } + g_serviceA = NULL; + } + + if (g_serviceB != NULL) { + if (g_serviceB->Destroy != NULL) { + g_serviceB->Destroy(g_serviceB); + } + g_serviceB = NULL; + } + return HDF_SUCCESS; +} + +// Repeated register +int32_t MessageSingleNodeTest001(void) +{ + ErrorCode errCode; + ErrorCode errShutdown; + + do { + ServiceCfg cfgB = { + .dispatcherId = CUSTOM_DISPATCHER_ID + }; + + MSG_RETURN_IF_FUNCTION_FAILED(errCode, StartEnv()); + + Service *service = CreateService(TestServiceB, &cfgB); + MSG_BREAK_IF(errCode, service != NULL); + } while (false); + + MSG_RETURN_IF_FUNCTION_FAILED(errShutdown, StopEnv()); + + return errCode; +} + +// Sync message test +int32_t MessageSingleNodeTest002(void) +{ + ErrorCode errCode; + ErrorCode errShutdown; + struct HdfSBuf *rspData = NULL; + + do { + MSG_BREAK_IF_FUNCTION_FAILED(errCode, StartEnv()); + + MSG_BREAK_IF(errCode, g_serviceA == NULL); + + rspData = HdfSBufObtainDefaultSize(); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, g_serviceA->SendSyncMessage(g_serviceA, SERVICE_ID_B, 0, NULL, rspData)); + } while (false); + + if (rspData != NULL) { + HdfSBufRecycle(rspData); + rspData = NULL; + } + + MSG_RETURN_IF_FUNCTION_FAILED(errShutdown, StopEnv()); + + return errCode; +} + + +// Sync Perf test +int32_t MessageSingleNodeTest003(void) +{ + ErrorCode errCode; + ErrorCode errShutdown; + uint32_t i; + struct HdfSBuf *rspData = NULL; + struct HdfSBuf *sendData = NULL; + do { + OsalTimespec startTime; + OsalTimespec endTime; + OsalTimespec diffTime; + MSG_BREAK_IF_FUNCTION_FAILED(errCode, StartEnv()); + MSG_BREAK_IF(errCode, g_serviceA == NULL); + rspData = HdfSBufObtainDefaultSize(); + sendData = HdfSBufObtainDefaultSize(); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalGetTime(&startTime)); + for (i = 0; i < SEND_MESSAGE_COUNT; i++) { + MSG_BREAK_IF_FUNCTION_FAILED(errCode, + g_serviceA->SendSyncMessage(g_serviceA, SERVICE_ID_B, 0, sendData, rspData)); + } + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalGetTime(&endTime)); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalDiffTime(&startTime, &endTime, &diffTime)); + + HDF_LOGI("Process time %ld \n", diffTime.sec); + MSG_BREAK_IF(errCode, diffTime.sec > SYNC_MESSAGE_TIMEOUT); + } while (false); + + if (rspData != NULL) { + HdfSBufRecycle(rspData); + rspData = NULL; + } + + if (sendData != NULL) { + HdfSBufRecycle(sendData); + sendData = NULL; + } + + MSG_RETURN_IF_FUNCTION_FAILED(errShutdown, StopEnv()); + + return errCode; +} + +OSAL_DECLARE_SEMAPHORE(g_callBackSem); + +void SendMessageTestCallBack(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData, + ErrorCode rspCode) +{ + OsalSemPost(&g_callBackSem); + HDF_LOGI("Receive response for CMD %d.\n", context->commandId); +} + +int32_t MessageSingleNodeTest004(void) +{ + ErrorCode errCode; + ErrorCode errShutdown = 0; + + do { + MSG_BREAK_IF_FUNCTION_FAILED(errCode, StartEnv()); + MSG_BREAK_IF(errCode, g_serviceA == NULL); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalSemInit(&g_callBackSem, 0)); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, + g_serviceA->SendAsyncMessage(g_serviceA, SERVICE_ID_B, 0, NULL, SendMessageTestCallBack)); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalSemWait(&g_callBackSem, COMMON_SEM_TIMEOUT)); + } while (false); + errShutdown = errShutdown | OsalSemDestroy(&g_callBackSem); + errShutdown = errShutdown | StopEnv(); + + return errCode; +} + +void SendMessagePerfTestCallBack(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData, + ErrorCode rspCode) +{ + ErrorCode errCode = OsalSemPost(&g_callBackSem); + (void)context; + if (HDF_SUCCESS != errCode) { + HDF_LOGE("%s:Post sem failed!ret=%d", __func__, errCode); + } +} + +const uint32_t PERF_TEST_COUNT = 10000; + +int32_t MessageSingleNodeTest005(void) +{ + ErrorCode errCode; + ErrorCode errShutdown = 0; + uint32_t i; + + do { + OsalTimespec startTime; + OsalTimespec endTime; + OsalTimespec diffTime; + MSG_BREAK_IF_FUNCTION_FAILED(errCode, StartEnv()); + MSG_BREAK_IF(errCode, g_serviceA == NULL); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalSemInit(&g_callBackSem, 0)); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalGetTime(&startTime)); + + for (i = 0; i < PERF_TEST_COUNT; i++) { + MSG_BREAK_IF_FUNCTION_FAILED(errCode, + g_serviceA->SendAsyncMessage(g_serviceA, SERVICE_ID_B, 0, NULL, SendMessagePerfTestCallBack)); + } + + for (i = 0; i < PERF_TEST_COUNT; i++) { + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalSemWait(&g_callBackSem, COMMON_SEM_TIMEOUT)); + } + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalGetTime(&endTime)); + + MSG_BREAK_IF_FUNCTION_FAILED(errCode, OsalDiffTime(&startTime, &endTime, &diffTime)); + + HDF_LOGW("Process time %ld \n", diffTime.sec); + MSG_BREAK_IF(errCode, diffTime.sec > ASYNC_MESSAGE_TIMEOUT); + } while (false); + errShutdown = errShutdown | OsalSemDestroy(&g_callBackSem); + errShutdown = errShutdown | StopEnv(); + + return errCode; +} diff --git a/test/unittest/model/network/wifi/unittest/module/hdf_module_test.c b/test/unittest/model/network/wifi/unittest/module/hdf_module_test.c new file mode 100644 index 00000000..858bff8f --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/module/hdf_module_test.c @@ -0,0 +1,140 @@ +/* + * 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_module_test.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_wifi_product.h" +#include "ap.h" + +struct HdfConfigWlanModuleConfig *g_hdfWlanModuleCfg = NULL; +struct WifiModule *g_hdfWifiModule = NULL; + +struct HdfConfigWlanRoot g_moduleData1 = { + .wlanConfig.moduleConfig = { + .featureMap = 0xffff, + .station = { + .name = "sta", + .mode = 0x1, + }, + .hostAp = { + .name = "ap", + .mode = 0x0, + .vapResNum = 0x1, + .userResNum = 0x8, + }, + .p2p = { + .name = "p2p", + .mode = 0x0, + }, + } +}; + +static int32_t P2pInit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} + +static int32_t P2pDeinit(struct WifiFeature *feature) +{ + (void)feature; + return HDF_SUCCESS; +} +struct WifiFeature g_p2pFeature = { + .name = "p2p", + .init = P2pInit, + .deInit = P2pDeinit, +}; + +static int32_t WiFiModuleTestSetEnv(void) +{ + g_hdfWlanModuleCfg = &g_moduleData1.wlanConfig.moduleConfig; + if (g_hdfWifiModule == NULL) { + int ret; + g_hdfWifiModule = OsalMemCalloc(sizeof(struct WifiModule)); + if (g_hdfWifiModule == NULL) { + HDF_LOGE("%s:oom", __func__); + return HDF_FAILURE; + } + ret = InitWifiModule(g_hdfWifiModule, g_hdfWlanModuleCfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Init WifiModule failed!ret=%d", __func__, ret); + OsalMemFree(g_hdfWifiModule); + g_hdfWifiModule = NULL; + return ret; + } + } + return HDF_SUCCESS; +} + +int32_t WiFiModuleTestCreateModule(void) +{ + int32_t ret; + ret = WiFiModuleTestSetEnv(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:WiFiModuleTestSetEnv failed.ret=%d", __func__, ret); + return ret; + } + struct WifiModule *module = OsalMemCalloc(sizeof(struct WifiModule)); + if (module == NULL) { + HDF_LOGE("%s fail WifiModuleCreate FAIL ", __func__); + return HDF_FAILURE; + } + + ret = InitWifiModule(module, g_hdfWlanModuleCfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Init WifiModule failed!ret=%d", __func__, ret); + OsalMemFree(module); + return ret; + } + OsalMemFree(module); + module = NULL; + + return HDF_SUCCESS; +} + +int32_t WiFiModuleTestAddFeature(void) +{ + struct WifiModule *module = HdfWlanGetModule(); + if (module == NULL) { + HDF_LOGE("%s:Cannot get module!", __func__); + return HDF_FAILURE; + } + if (module->iface.addFeature == NULL) { + HDF_LOGE("%s:bad module found!", __func__); + return HDF_FAILURE; + } + return module->iface.addFeature(module, HDF_WIFI_FEATURE_P2P, &g_p2pFeature); +} + +int32_t WiFiModuleTestDelFeature(void) +{ + struct WifiModule *module = HdfWlanGetModule(); + if (module == NULL) { + HDF_LOGE("%s:Cannot get module!", __func__); + return HDF_FAILURE; + } + if (module->iface.delFeature == NULL) { + HDF_LOGE("%s:bad module found!", __func__); + return HDF_FAILURE; + } + return module->iface.delFeature(module, HDF_WIFI_FEATURE_P2P); +} + +int32_t WiFiModuleTestDeleteModule(void) +{ + int ret = WiFiModuleTestSetEnv(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Set env failed!", __func__); + return ret; + } + OsalMemFree(g_hdfWifiModule); + g_hdfWifiModule = NULL; + return HDF_SUCCESS; +} \ No newline at end of file diff --git a/test/unittest/model/network/wifi/unittest/module/hdf_module_test.h b/test/unittest/model/network/wifi/unittest/module/hdf_module_test.h new file mode 100644 index 00000000..5b1deec1 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/module/hdf_module_test.h @@ -0,0 +1,22 @@ +/* + * 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_LITE_WIFI_MODULE_TEST_H +#define HDF_LITE_WIFI_MODULE_TEST_H + +#include "hdf_base.h" + +int32_t WiFiModuleTestCreateModule(void); +int32_t WiFiModuleTestDeleteModule(void); +int32_t WiFiModuleTestUpdateModule(void); + +int32_t WiFiModuleTestAddFeature(void); +int32_t WiFiModuleTestDelFeature(void); +int32_t WiFiModuleTestGetFeature(void); + +#endif // HDF_LITE_WIFI_MODULE_TEST_H 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 new file mode 100644 index 00000000..76c57ff6 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.c @@ -0,0 +1,899 @@ +/* + * 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_netbuf.h" +#include "hdf_log.h" +#include "hdf_wifi_test.h" + +#define DEFAULT_NETBUF_SIZE 100 +#define DEFAULT_OP_SIZE 10 +#define DEFAULT_HEAD_SIZE 10 +#define DEFAULT_TAIL_SIZE 20 +#define DEFAULT_MAPPING_QUEUE 10 +#define DEFAULT_TRIM_SIZE 3 +#define DEFAULT_SECTION_SIZE 3 + +#define MAX_MEM_ALLOC_SIZE 0x7fffffff + +typedef int32_t (*pTestCaseFunc)(void); + +/* +* @tc.name: HdfNetBufTest001 +* @tc.desc: Alloc net buffer +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest001(void) +{ + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest002 +* @tc.desc: Alloc net buffer for invalid size +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest002(void) +{ + NetBuf *nb = NetBufAlloc(MAX_MEM_ALLOC_SIZE); + if (nb == NULL) { + return HDF_SUCCESS; + } + NetBufFree(nb); + return HDF_FAILURE; +} + +/* +* @tc.name: HdfNetBufTest003 +* @tc.desc: NetBufPush test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest003(void) +{ + void *tmp = NULL; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + tmp = NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + if (tmp == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf Push fail"); + return HDF_FAILURE; + } + + if (NetBufGetRoom(nb, E_DATA_BUF) != DEFAULT_OP_SIZE) { + NetBufFree(nb); + HDF_LOGE("NetBuf datasize error."); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest004 +* @tc.desc: NetBufPush test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest004(void) +{ + void *tmp = NULL; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + tmp = NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + if (tmp == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf push data fail"); + return HDF_FAILURE; + } + + tmp = NetBufPush(nb, E_HEAD_BUF, DEFAULT_OP_SIZE); + if (tmp == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf push head fail"); + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_HEAD_BUF) != DEFAULT_OP_SIZE || NetBufGetRoom(nb, E_DATA_BUF) != 0) { +#else + if (NetBufGetRoom(nb, E_HEAD_BUF) < DEFAULT_OP_SIZE) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBuf datasize error."); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest005 +* @tc.desc: NetBufPop test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest005(void) +{ + void *tmp = NULL; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb, E_HEAD_BUF, DEFAULT_OP_SIZE); + tmp = NetBufPop(nb, E_HEAD_BUF, DEFAULT_OP_SIZE); + if (tmp == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf Pull fail"); + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_DATA_BUF) != DEFAULT_OP_SIZE || NetBufGetRoom(nb, E_HEAD_BUF) != 0) { +#else + if (NetBufGetRoom(nb, E_DATA_BUF) < DEFAULT_OP_SIZE) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBuf datasize error."); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest006 +* @tc.desc: NetBufPop test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest006(void) +{ + void *tmp = NULL; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + tmp = NetBufPop(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + if (tmp == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf Pull fail"); + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_HEAD_BUF) != DEFAULT_OP_SIZE || NetBufGetRoom(nb, E_DATA_BUF) != 0) { +#else + if (NetBufGetRoom(nb, E_HEAD_BUF) < DEFAULT_OP_SIZE) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBuf datasize error."); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest007 +* @tc.desc: NetBufGetRoom test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest007(void) +{ + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_HEAD_BUF) != 0) { + NetBufFree(nb); + HDF_LOGE("NetBufGetRoom head fail"); + return HDF_FAILURE; + } +#endif + + if (NetBufGetRoom(nb, E_DATA_BUF) != 0) { + NetBufFree(nb); + HDF_LOGE("NetBufGetRoom data fail"); + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_TAIL_BUF) != DEFAULT_NETBUF_SIZE) { +#else + if (NetBufGetRoom(nb, E_TAIL_BUF) < DEFAULT_NETBUF_SIZE) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBufGetRoom tail fail"); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest008 +* @tc.desc: NetBufGetRoom test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest008(void) +{ + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_TAIL_BUF) != (DEFAULT_NETBUF_SIZE - DEFAULT_OP_SIZE)) { +#else + if (NetBufGetRoom(nb, E_TAIL_BUF) < (DEFAULT_NETBUF_SIZE - DEFAULT_OP_SIZE)) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBufTailRoom fail"); + return HDF_FAILURE; + } + + NetBufFree(nb); + + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest009 +* @tc.desc: NetBufExpandRoom test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest009(void) +{ + int32_t ret; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + return HDF_FAILURE; + } + + ret = NetBufResizeRoom(nb, DEFAULT_HEAD_SIZE, DEFAULT_TAIL_SIZE); + if (ret != 0) { + NetBufFree(nb); + HDF_LOGE("NetBufExpandRoom fail"); + return HDF_FAILURE; + } + +#ifdef __LITEOS__ + if (NetBufGetRoom(nb, E_HEAD_BUF) != DEFAULT_HEAD_SIZE) { +#else + if (NetBufGetRoom(nb, E_HEAD_BUF) < DEFAULT_HEAD_SIZE) { +#endif + NetBufFree(nb); + HDF_LOGE("NetBufHeadRoom fail"); + return HDF_FAILURE; + } + + if (NetBufGetRoom(nb, E_TAIL_BUF) < (DEFAULT_NETBUF_SIZE + DEFAULT_TAIL_SIZE)) { + NetBufFree(nb); + HDF_LOGE("NetBufTailRoom fail, tailroom:%d", NetBufGetRoom(nb, E_TAIL_BUF)); + return HDF_FAILURE; + } + + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest010 +* @tc.desc: NetBufConcat test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest010(void) +{ + uint32_t ret; + NetBuf *dst = NetBufAlloc(DEFAULT_NETBUF_SIZE); + NetBuf *src = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (dst == NULL || src == NULL) { + NetBufFree(src); + NetBufFree(dst); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(dst, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(src, E_DATA_BUF, DEFAULT_OP_SIZE); + + ret = NetBufConcat(dst, src); + if (ret != HDF_SUCCESS) { + NetBufFree(src); + NetBufFree(dst); + HDF_LOGE("NetBufConcat fail"); + return HDF_FAILURE; + } + + if (NetBufGetDataLen(dst) != (DEFAULT_OP_SIZE + DEFAULT_OP_SIZE)) { + NetBufFree(dst); + HDF_LOGE("NetBufGetLen fail"); + return HDF_FAILURE; + } + + NetBufFree(dst); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest011 +* @tc.desc: NetBufConcat test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest011(void) +{ + uint32_t ret, dstDataLen; + NetBuf *dst = NetBufAlloc(DEFAULT_NETBUF_SIZE); + NetBuf *src = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (dst == NULL || src == NULL) { + NetBufFree(src); + NetBufFree(dst); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + /* push large enough because there is maybe padding bytes exists */ + dstDataLen = DEFAULT_OP_SIZE * DEFAULT_SECTION_SIZE; + NetBufPush(dst, E_DATA_BUF, dstDataLen); + NetBufPush(src, E_DATA_BUF, DEFAULT_NETBUF_SIZE - 1); + + ret = NetBufConcat(dst, src); + if (ret == HDF_SUCCESS) { + NetBufFree(dst); + HDF_LOGE("NetBufConcat success"); + return HDF_FAILURE; + } + + if (NetBufGetDataLen(dst) != dstDataLen) { + NetBufFree(src); + NetBufFree(dst); + HDF_LOGE("NetBufGetLen fail"); + return HDF_FAILURE; + } + + NetBufFree(src); + NetBufFree(dst); + return HDF_SUCCESS; +} + +#ifdef __LITEOS__ +/* +* @tc.name: HdfNetBufTest012 +* @tc.desc: NetBuf2Pbuf test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest012(void) +{ + struct pbuf *lwipBuf = NULL; + NetBuf *nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb == NULL) { + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + + lwipBuf = NetBuf2Pbuf(nb); + if (lwipBuf == NULL) { + NetBufFree(nb); + HDF_LOGE("NetBuf2Pbuf fail"); + return HDF_FAILURE; + } + + pbuf_free(lwipBuf); + NetBufFree(nb); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufTest013 +* @tc.desc: Pbuf2NetBuf test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufTest013(void) +{ + struct pbuf *lwipBuf = NULL; + NetBuf *nb = NULL; + + lwipBuf = pbuf_alloc(PBUF_RAW, DEFAULT_NETBUF_SIZE, PBUF_RAM); + if (lwipBuf == NULL) { + HDF_LOGE("pbuf_alloc fail"); + return HDF_FAILURE; + } + + nb = Pbuf2NetBuf(NULL, lwipBuf); + if (nb == NULL) { + pbuf_free(lwipBuf); + NetBufFree(nb); + HDF_LOGE("Pbuf2NetBuf fail"); + return HDF_FAILURE; + } + + pbuf_free(lwipBuf); + NetBufFree(nb); + return HDF_SUCCESS; +} +#endif + +/* +* @tc.name: HdfNetBufQueueTest001 +* @tc.desc: NetBufQueueInit test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest001(void) +{ + NetBufQueue q; + + NetBufQueueInit(&q); + + if (!NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueIsEmpty fail"); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest002 +* @tc.desc: NetBufQueueSize test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest002(void) +{ + NetBufQueue q; + + NetBufQueueInit(&q); + + if (NetBufQueueSize(&q) != 0) { + HDF_LOGE("NetBufQueueIsEmpty fail"); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest003 +* @tc.desc: NetBufQueueEnqueue test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest003(void) +{ + NetBufQueue q; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + uint32_t size = 0; + + NetBufQueueInit(&q); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + size++; + NetBufQueueEnqueue(&q, nb2); + size++; + if (NetBufQueueSize(&q) != size || NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueIsEmpty fail"); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + NetBufQueueClear(&q); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest004 +* @tc.desc: NetBufQueueAtHead test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest004(void) +{ + NetBufQueue q; + NetBuf *nb = NULL; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + + NetBufQueueInit(&q); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + HDF_LOGE("NetBufAlloc fail"); + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE + DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + NetBufQueueEnqueue(&q, nb2); + + nb = NetBufQueueAtHead(&q); + if (NetBufGetDataLen(nb) != DEFAULT_OP_SIZE) { + HDF_LOGE("NetBufGetLen fail, len:%d", NetBufGetDataLen(nb)); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + NetBufQueueClear(&q); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest005 +* @tc.desc: NetBufQueueAtTail test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest005(void) +{ + NetBufQueue q; + NetBuf *nb = NULL; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + + NetBufQueueInit(&q); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE + DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + NetBufQueueEnqueue(&q, nb2); + + nb = NetBufQueueAtTail(&q); + if (NetBufGetDataLen(nb) != (DEFAULT_OP_SIZE + DEFAULT_OP_SIZE)) { + HDF_LOGE("NetBufGetLen fail, len:%d", NetBufGetDataLen(nb)); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + NetBufQueueClear(&q); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest006 +* @tc.desc: NetBufQueueDequeue test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest006(void) +{ + NetBufQueue q; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + + NetBufQueueInit(&q); + if (NetBufQueueIsEmpty(&q) != 1) { + HDF_LOGE("NetBufQueueIsEmpty fail"); + return HDF_FAILURE; + } + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE + DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + NetBufQueueEnqueue(&q, nb2); + + nb1 = NetBufQueueDequeue(&q); + nb2 = NetBufQueueDequeue(&q); + if (nb1 == NULL || nb2 == NULL) { + HDF_LOGE("NetBufQueueDequeue fail"); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + if (NetBufQueueSize(&q) != 0 || !NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueSize fail, queue size:%d", NetBufQueueSize(&q)); + NetBufFree(nb1); + NetBufFree(nb2); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + if (NetBufGetDataLen(nb1) != DEFAULT_OP_SIZE || + NetBufGetDataLen(nb2) != (DEFAULT_OP_SIZE + DEFAULT_OP_SIZE)) { + HDF_LOGE("NetBufGetLen fail, len:%d", NetBufGetDataLen(nb1)); + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_FAILURE; + } + + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest007 +* @tc.desc: NetBufQueueEnqueueHead test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest007(void) +{ + NetBufQueue q; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + uint32_t size = 0; + + NetBufQueueInit(&q); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE + DEFAULT_OP_SIZE); + NetBufQueueEnqueueHead(&q, nb1); + size++; + NetBufQueueEnqueueHead(&q, nb2); + size++; + if (NetBufQueueSize(&q) != size || NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueSize fail, queue size:%d", NetBufQueueSize(&q)); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + nb1 = NetBufQueueDequeueTail(&q); + nb2 = NetBufQueueDequeueTail(&q); + + if (NetBufQueueSize(&q) != 0 || !NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueSize fail, queue size:%d", NetBufQueueSize(&q)); + NetBufQueueClear(&q); + return HDF_FAILURE; + } + + if (NetBufGetDataLen(nb1) != DEFAULT_OP_SIZE) { + HDF_LOGE("NetBufGetLen fail, len:%d", NetBufGetDataLen(nb1)); + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_FAILURE; + } + + if (NetBufGetDataLen(nb2) != (DEFAULT_OP_SIZE + DEFAULT_OP_SIZE)) { + HDF_LOGE("NetBufGetLen fail, len:%d", NetBufGetDataLen(nb2)); + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_FAILURE; + } + + NetBufFree(nb1); + NetBufFree(nb2); + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest008 +* @tc.desc: NetBufQueuePurge test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest008(void) +{ + NetBufQueue q; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + + NetBufQueueInit(&q); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + NetBufQueueEnqueue(&q, nb2); + + NetBufQueueClear(&q); + + if (NetBufQueueSize(&q) != 0 || !NetBufQueueIsEmpty(&q)) { + HDF_LOGE("NetBufQueueSize fail, queue size:%d", NetBufQueueSize(&q)); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +/* +* @tc.name: HdfNetBufQueueTest009 +* @tc.desc: NetBufQueueSpliceInit test +* @tc.type: FUNC +* @tc.require: AR000DT1UD +*/ +int32_t HdfNetBufQueueTest009(void) +{ + NetBufQueue q; + NetBufQueue add; + NetBuf *nb1 = NULL; + NetBuf *nb2 = NULL; + NetBuf *nb = NULL; + uint32_t size = 0; + + NetBufQueueInit(&q); + NetBufQueueInit(&add); + + nb1 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb2 = NetBufAlloc(DEFAULT_NETBUF_SIZE); + nb = NetBufAlloc(DEFAULT_NETBUF_SIZE); + if (nb1 == NULL || nb2 == NULL || nb == NULL) { + NetBufFree(nb1); + NetBufFree(nb2); + NetBufFree(nb); + HDF_LOGE("NetBufAlloc fail"); + return HDF_FAILURE; + } + + NetBufPush(nb1, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb2, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufPush(nb, E_DATA_BUF, DEFAULT_OP_SIZE); + NetBufQueueEnqueue(&q, nb1); + size++; + NetBufQueueEnqueue(&q, nb2); + size++; + NetBufQueueEnqueue(&add, nb); + + NetBufQueueConcat(&q, &add); + size++; + if (NetBufQueueSize(&q) != size) { + NetBufQueueClear(&q); + HDF_LOGE("NetBufQueueSize fail, queue size:%d", NetBufQueueSize(&q)); + return HDF_FAILURE; + } + + NetBufQueueClear(&q); + return HDF_SUCCESS; +} + +// add test case +pTestCaseFunc g_hdfNetBufTestCaseLists[] = { + HdfNetBufTest001, + HdfNetBufTest002, + HdfNetBufTest003, + HdfNetBufTest004, + HdfNetBufTest005, + HdfNetBufTest006, + HdfNetBufTest007, + HdfNetBufTest008, + HdfNetBufTest009, + HdfNetBufTest010, + HdfNetBufTest011, +#ifdef __LITEOS__ + HdfNetBufTest012, + HdfNetBufTest013, +#endif +}; + +// add test case +pTestCaseFunc g_hdfNetBufQueueTestCaseLists[] = { + HdfNetBufQueueTest001, + HdfNetBufQueueTest002, + HdfNetBufQueueTest003, + HdfNetBufQueueTest004, + HdfNetBufQueueTest005, + HdfNetBufQueueTest006, + HdfNetBufQueueTest007, + HdfNetBufQueueTest008, + HdfNetBufQueueTest009, +}; + +// HDFNetBuf test canse Entry +int32_t HdfNetBufTest(void) +{ + int32_t ret, i; + + for (i = 0; i < sizeof(g_hdfNetBufTestCaseLists) / sizeof(g_hdfNetBufTestCaseLists[0]); ++i) { + if (g_hdfNetBufTestCaseLists[i] != NULL) { + ret = g_hdfNetBufTestCaseLists[i](); + HDF_LOGI("HdfTest:HdfNetBuf test_case[%d] result[%s-%d]", + i + 1, (ret != HDF_SUCCESS) ? "failed" : "pass", ret); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + } + } + + return HDF_SUCCESS; +} + +// HdfNetBufQueue test canse Entry +int32_t HdfNetBufQueueTest(void) +{ + int32_t ret, i; + + for (i = 0; i < sizeof(g_hdfNetBufQueueTestCaseLists) / sizeof(g_hdfNetBufQueueTestCaseLists[0]); ++i) { + if (g_hdfNetBufQueueTestCaseLists[i] != NULL) { + ret = g_hdfNetBufQueueTestCaseLists[i](); + HDF_LOGI("HdfTest:HdfNetBufQueue test_case[%d] result[%s-%d]", + i + 1, (ret != HDF_SUCCESS) ? "failed" : "pass", ret); + if (ret != HDF_SUCCESS) { + return HDF_FAILURE; + } + } + } + + return HDF_SUCCESS; +} diff --git a/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.h b/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.h new file mode 100644 index 00000000..8e1a57c8 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/net/hdf_netbuf_test.h @@ -0,0 +1,16 @@ +/* + * 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_NETBUF_TEST_H +#define HDF_NETBUF_TEST_H + +int32_t HdfNetBufTest(void); +int32_t HdfNetBufQueueTest(void); + +#endif // HDF_NETBUF_TEST_H + 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 new file mode 100644 index 00000000..d44f0036 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.c @@ -0,0 +1,186 @@ +/* + * 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 "net_device_test.h" +#include "hdf_log.h" +#include "net_device.h" +#include + +static struct NetDevice *g_netDevice = NULL; + +static uint8_t g_filterData[] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x88, 0x11, 0x31, 0xc6, 0xda, 0xdc, 0xff, 0xff +}; + +static bool WiFiNetDeviceTestEnv(void) +{ + if (g_netDevice == NULL) { + char devName[IFNAMSIZ] = {0}; + strncpy_s(devName, IFNAMSIZ, "wlan_test_0", strlen("wlan_test_0") + 1); + g_netDevice = NetDeviceInit(devName, strlen(devName), LITE_OS); + if (g_netDevice == NULL) { + HDF_LOGE("%s fail ", __func__); + return false; + } + HDF_LOGE("%s success ", __func__); + return true; + } + return true; +} + +int32_t WiFiNetDviceTestInit(void) +{ + if (g_netDevice != NULL) { + return HDF_SUCCESS; + } + if (!WiFiNetDeviceTestEnv()) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestDeInit(void) +{ + NetDeviceDeInit(g_netDevice); + g_netDevice = NULL; + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestAdd(void) +{ + if (g_netDevice == NULL) { + if (!WiFiNetDeviceTestEnv()) { + HDF_LOGE("%s WiFiNetDeviceTestEnv fail!", __func__); + return HDF_FAILURE; + } + } + if (NetDeviceAdd(g_netDevice, PROTOCOL_80211_IFTYPE_STATION) != HDF_SUCCESS) { + HDF_LOGE("%s add fail!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestDelete(void) +{ + if (NetDeviceDelete(g_netDevice) != HDF_SUCCESS) { + HDF_LOGE("%s NetDeviceDelete fail!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestGetDevice(void) +{ + struct NetDevice *temp = NetDeviceGetInstByName(g_netDevice->name); + if (temp == NULL) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestGetCount(void) +{ + uint32_t count = NetDevGetRegisterCount(); + if (count == 0) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WiFiNetDviceTestGetCap(void) +{ + uint32_t count = NetDeviceGetCap(); + if (count > 0) { + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +int32_t WiFiNetDviceTestSetAddr(void) +{ +#ifdef __LITEOS__ + IpV4Addr ip = { 0x010ca8c0UL }; // 192, 168, 12, 1 + IpV4Addr netmask = { 0x00ffffffUL }; // 255, 255, 255, 0 + IpV4Addr gw = { 0x010ca8c0UL }; // 192, 168, 12, 1 + return NetIfSetAddr(g_netDevice, &ip, &netmask, &gw); +#else + return HDF_SUCCESS; +#endif +} + +int32_t WiFiNetDviceTestRx(void) +{ + NetBuf *buff = NULL; + int count = sizeof(g_filterData); + buff = NetBufAlloc(count); + if (buff == NULL) { + HDF_LOGE("%s fail : NetBufAlloc = null!", __func__); + return HDF_FAILURE; + } + NetBufPush(buff, E_DATA_BUF, count); + if (memcpy_s(NetBufGetAddress(buff, E_DATA_BUF), count, g_filterData, count) != EOK) { + NetBufFree(buff); + buff = NULL; + HDF_LOGE("%s fail : memcpy_s fail", __func__); + return HDF_FAILURE; + } + return NetIfRx(g_netDevice, buff); +} + +int32_t WiFiNetDviceTestSetStatus(void) +{ + return NetIfSetStatus(g_netDevice, NETIF_DOWN); +} + +int32_t WiFiNetDviceTestSetLinkStatus(void) +{ +#ifdef __LITEOS__ + return NetIfSetLinkStatus(g_netDevice, NETIF_LINK_DOWN); +#else + return HDF_SUCCESS; +#endif +} + +int32_t WifiNetDeviceDhcpClient(void) +{ +#ifdef __LITEOS__ + int32_t expectedRet = HDF_SUCCESS; +#else + int32_t expectedRet = HDF_ERR_INVALID_PARAM; +#endif + + NetIfSetStatus(g_netDevice, NETIF_UP); + NetIfDhcpStop(g_netDevice); + if (NetIfDhcpStart(g_netDevice) != expectedRet) { + return HDF_FAILURE; + } + if (NetIfDhcpStop(g_netDevice) != expectedRet) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t WifiNetDeviceDhcpServer(void) +{ +#ifdef __LITEOS__ + int32_t expectedRet = HDF_SUCCESS; +#else + int32_t expectedRet = HDF_ERR_INVALID_PARAM; +#endif + + NetIfSetStatus(g_netDevice, NETIF_UP); + NetIfDhcpsStop(g_netDevice); + if (NetIfDhcpsStart(g_netDevice, NULL, 0) != expectedRet) { + return HDF_FAILURE; + } + if (NetIfDhcpsStop(g_netDevice) != expectedRet) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} \ No newline at end of file diff --git a/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.h b/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.h new file mode 100644 index 00000000..1213d25d --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/netdevice/net_device_test.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 WIFI_NET_DEVICE_TEST_H +#define WIFI_NET_DEVICE_TEST_H + +#include "hdf_base.h" + +int32_t WiFiNetDviceTestInit(void); +int32_t WiFiNetDviceTestDeInit(void); +int32_t WiFiNetDviceTestAdd(void); +int32_t WiFiNetDviceTestDelete(void); +int32_t WiFiNetDviceTestGetDevice(void); +int32_t WiFiNetDviceTestGetCount(void); +int32_t WiFiNetDviceTestGetCap(void); +int32_t WiFiNetDviceTestSetAddr(void); +int32_t WiFiNetDviceTestRx(void); +int32_t WiFiNetDviceTestSetStatus(void); +int32_t WiFiNetDviceTestSetLinkStatus(void); +int32_t WifiNetDeviceDhcpClient(void); +int32_t WifiNetDeviceDhcpServer(void); + +#endif \ No newline at end of file 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 new file mode 100644 index 00000000..1a4a0ba2 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/qos/flow_control_test.c @@ -0,0 +1,176 @@ +/* + * 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 "flow_control_test.h" +#include "flow_control.h" +#include "hdf_log.h" +#include "securec.h" +#include "osal_time.h" + +#define WATITE_RESULT_TIME 1000 // 1000ms +static struct FlowControlModule *g_flowControlInstance = NULL; +static bool g_result = false; + +static uint8_t g_dhcpData[] = { + 0x42, 0x2b, 0x13, 0x41, 0xc9, 0xd7, 0x38, 0x81, 0x13, 0x1c, 0x6d, 0xad, 0x08, 0x00, 0x45, 0x00, 0x01, 0x50, 0x00, + 0x01, 0x00, 0x00, 0xff, 0x11, 0xba, 0x9c, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x44, 0x00, 0x43, + 0x01, 0x3c, 0xd4, 0xa8 +}; + +static bool IsDeviceStaOrP2PClient(void) +{ + return true; +} + +static int32_t SendDataPacket(NetBufQueue *q, void *fcmPrivate, int32_t fwPriorityId) +{ + NetBuf *buff = NULL; + uint32_t count = NetBufQueueSize(q); + if (count != 1) { + HDF_LOGE("%s count error", __func__); + return HDF_FAILURE; + } + buff = NetBufQueueDequeue(q); + g_result = false; + HDF_LOGE("%s enter", __func__); + if (memcmp(NetBufGetAddress(buff, E_DATA_BUF), g_dhcpData, sizeof(g_dhcpData) / sizeof(g_dhcpData[0])) != 0) { + HDF_LOGE("%s fail : memcmp != size", __func__); + return HDF_FAILURE; + } + g_result = true; + (void)fcmPrivate; + (void)fwPriorityId; + return HDF_SUCCESS; +} + +static struct FlowControlOp g_flowControlOp = { + .isDeviceStaOrP2PClient = IsDeviceStaOrP2PClient, + .txDataPacket = SendDataPacket, + .rxDataPacket = NULL, + .getTxQueueId = NULL, + .getRxQueueId = NULL, + .getTxPriorityId = NULL, + .getRxPriorityId = NULL, +}; + +static bool WiFiFlowControlTestEnv(void) +{ + if (g_flowControlInstance == NULL) { + g_flowControlInstance = InitFlowControl(NULL); + if (g_flowControlInstance == NULL) { + HDF_LOGE("%s fail : InitFlowControl = null!", __func__); + return false; + } + } + g_flowControlInstance->interface->registerFlowControlOp(g_flowControlInstance, &g_flowControlOp); + return true; +} + +static bool WiFiFlowControlTestOut(void) +{ + if (g_flowControlInstance != NULL) { + DeInitFlowControl(g_flowControlInstance); + g_flowControlInstance = NULL; + } + return true; +} + +static NetBuf *ConstructEapolNetBuf(void) +{ + NetBuf *buff = NULL; + int count = sizeof(g_dhcpData) / sizeof(g_dhcpData[0]); + buff = NetBufAlloc(count); + if (buff == NULL) { + HDF_LOGE("%s fail : NetBufAlloc = null!", __func__); + return buff; + } + NetBufPush(buff, E_DATA_BUF, count); + if (memcpy_s(NetBufGetAddress(buff, E_DATA_BUF), count, g_dhcpData, count) != EOK) { + NetBufFree(buff); + buff = NULL; + HDF_LOGE("%s fail : memcpy_s fail", __func__); + return buff; + } + return buff; +} + +int32_t WiFiFlowControlTestInit(void) +{ + if (WiFiFlowControlTestEnv()) { + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +int32_t WiFiFlowControlTestDeinit(void) +{ + if (WiFiFlowControlTestOut()) { + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +int32_t WiFiFlowControlTestGetEapolQueueId(void) +{ + NetBuf *buff = NULL; + FlowControlQueueID id; + if (!WiFiFlowControlTestEnv()) { + return HDF_FAILURE; + } + buff = ConstructEapolNetBuf(); + if (buff == NULL) { + return HDF_FAILURE; + } + if (g_flowControlInstance->interface == NULL) { + HDF_LOGE("%s interface =null!", __func__); + return HDF_FAILURE; + } + id = g_flowControlInstance->interface->getQueueIdByEtherBuff(buff); + HDF_LOGE("%s get id =%d!", __func__, id); + + NetBufFree(buff); + DeInitFlowControl(g_flowControlInstance); + g_flowControlInstance = NULL; + if (id == VIP_QUEUE_ID) { + return HDF_SUCCESS; + } + return HDF_FAILURE; +} + +int32_t WiFiFlowControlTestSendData(void) +{ + NetBuf *buff = NULL; + FlowControlQueueID id; + if (!WiFiFlowControlTestEnv()) { + return false; + } + buff = ConstructEapolNetBuf(); + if (buff == NULL) { + return HDF_FAILURE; + } + if (g_flowControlInstance->interface == NULL) { + HDF_LOGE("%s interface =null!", __func__); + return HDF_FAILURE; + } + id = g_flowControlInstance->interface->getQueueIdByEtherBuff(buff); + g_result = false; + if (g_flowControlInstance->interface->sendBuffToFCM(g_flowControlInstance, buff, id, FLOW_TX) != HDF_SUCCESS) { + HDF_LOGE("%s sendBuffToFCM fail!", __func__); + return HDF_FAILURE; + } + if (g_flowControlInstance->interface->schedFCM(g_flowControlInstance, FLOW_TX) != HDF_SUCCESS) { + HDF_LOGE("%s sendBuffToFCM fail!", __func__); + return HDF_FAILURE; + } + OsalMSleep(WATITE_RESULT_TIME); + NetBufFree(buff); + DeInitFlowControl(g_flowControlInstance); + g_flowControlInstance = NULL; + HDF_LOGE("%s g_result = %d!", __func__, g_result); + return g_result ? HDF_SUCCESS : HDF_FAILURE; +} \ No newline at end of file diff --git a/test/unittest/model/network/wifi/unittest/qos/flow_control_test.h b/test/unittest/model/network/wifi/unittest/qos/flow_control_test.h new file mode 100644 index 00000000..4b103098 --- /dev/null +++ b/test/unittest/model/network/wifi/unittest/qos/flow_control_test.h @@ -0,0 +1,16 @@ +/* + * 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 WIFI_FLOW_CONTROL_TEST_H +#define WIFI_FLOW_CONTROL_TEST_H +#include "hdf_base.h" +int32_t WiFiFlowControlTestInit(void); +int32_t WiFiFlowControlTestDeinit(void); +int32_t WiFiFlowControlTestSendData(void); +int32_t WiFiFlowControlTestGetEapolQueueId(void); +#endif \ No newline at end of file diff --git a/test/unittest/osal/osal_all_test.c b/test/unittest/osal/osal_all_test.c new file mode 100644 index 00000000..1efe4a73 --- /dev/null +++ b/test/unittest/osal/osal_all_test.c @@ -0,0 +1,835 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "osal_firmware.h" +#include "osal_irq.h" +#include "osal_list_test.h" +#include "osal_file_test.h" +#include "osal_case_cmd_test.h" +#include "osal_get_case_test.h" +#include "osal_test_case_def.h" +#include "osal_mem.h" +#include "osal_mutex.h" +#include "osal_spinlock.h" +#include "osal_test_type.h" +#include "osal_thread.h" +#include "osal_time.h" +#include "osal_timer.h" +#include "securec.h" + +#define IRQ_NUM_TEST 33 +#define HDF_LOG_TAG osal_test + +#define OSAL_TEST_TIME_DEFAULT 100 + +uint32_t g_osalTestCases[OSAL_TEST_CASE_CNT]; + +OsalTimespec g_hdfTestBegin; +OsalTimespec g_hdfTestEnd; +static int32_t g_waitMutexTime = 3100; +static int32_t g_threadTest1Flag = true; +OSAL_DECLARE_THREAD(thread1); +OSAL_DECLARE_THREAD(thread2); +OSAL_DECLARE_THREAD(thread); +struct OsalMutex g_mutexTest; +OSAL_DECLARE_SPINLOCK(g_spinTest); + +#define HDF_THREAD_TEST_SLEEP_S 1 +#define HDF_THREAD_TEST_SLEEP_US 600 +#define HDF_THREAD_TEST_SLEEP_MS 300 +#define HDF_THREAD_TEST_MUX_CNT 20 +static int g_thread1RunFlag; +static int g_threadMuxLockFlag; +static int32_t g_test1Para = 120; +static int32_t g_test2Para = 123; +#define TIME_RANGE 200000 +static bool OsalCheckTime(OsalTimespec *time, uint32_t ms) +{ + uint64_t t1 = time->sec * HDF_KILO_UNIT * HDF_KILO_UNIT + time->usec; + uint64_t t2 = ms * HDF_KILO_UNIT; + uint64_t diff = (t1 < t2) ? (t2 - t1) : (t1 - t2); + + return diff < TIME_RANGE; +} + +static int ThreadTest1(void *arg) +{ + static int cnt = 0; + int ret; + + HDF_LOGI("[OSAL_UT_TEST]%s test thread para end", __func__); + (void)arg; + + g_thread1RunFlag = true; + + while (g_threadTest1Flag) { + OsalSleep(HDF_THREAD_TEST_SLEEP_S); + HDF_LOGE("%s %d", __func__, cnt); + cnt++; + if (cnt > HDF_THREAD_TEST_MUX_CNT) { + g_waitMutexTime = HDF_WAIT_FOREVER; + } + ret = OsalMutexTimedLock(&g_mutexTest, g_waitMutexTime); + if (g_threadMuxLockFlag == true) { + UT_TEST_CHECK_RET(ret == HDF_FAILURE, OSAL_MUTEX_LOCK_TIMEOUT); + } else { + UT_TEST_CHECK_RET(ret == HDF_FAILURE, OSAL_MUTEX_LOCK_TIMEOUT); + } + + OsalMSleep(HDF_THREAD_TEST_SLEEP_MS); + if (ret == HDF_SUCCESS) { + ret = OsalMutexUnlock(&g_mutexTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_UNLOCK); + } + OsalMSleep(HDF_THREAD_TEST_SLEEP_US); + + ret = OsalSpinLock(&g_spinTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_LOCK); + ret = OsalSpinUnlock(&g_spinTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_UNLOCK); + + OsalMSleep(HDF_THREAD_TEST_SLEEP_MS); + if (cnt % HDF_THREAD_TEST_MUX_CNT == 0) { + HDF_LOGE("%s ", __func__); + } + if (g_testEndFlag) { + break; + } + } + HDF_LOGE("%s thread return\n", __func__); + return 0; +} + +static int g_thread2RunFlag; +static int32_t g_threadTest2Flag = true; +int ThreadTest2(void *arg) +{ + static int cnt = 0; + OsalTimespec hdfTs1 = { 0, 0 }; + OsalTimespec hdfTs2 = { 0, 0 }; + OsalTimespec hdfTsDiff = { 0, 0 }; + int ret; + int32_t para; + + HDF_LOGI("[OSAL_UT_TEST]%s test thread para end", __func__); + if (arg != NULL) { + para = *(int32_t *)arg; + UT_TEST_CHECK_RET(para != g_test2Para, OSAL_THREAD_PARA_CHECK); + } else { + UT_TEST_CHECK_RET(true, OSAL_THREAD_PARA_CHECK); + } + + g_thread2RunFlag = true; + + while (g_threadTest2Flag) { + OsalSleep(HDF_THREAD_TEST_SLEEP_S); + OsalGetTime(&hdfTs1); + HDF_LOGE("%s %d", __func__, cnt); + + cnt++; + ret = OsalMutexTimedLock(&g_mutexTest, g_waitMutexTime); + if (g_threadMuxLockFlag == true) { + UT_TEST_CHECK_RET(ret == HDF_FAILURE, OSAL_MUTEX_LOCK_TIMEOUT); + } else { + UT_TEST_CHECK_RET(ret == HDF_FAILURE, OSAL_MUTEX_LOCK_TIMEOUT); + } + + OsalMSleep(HDF_THREAD_TEST_SLEEP_MS); + if (ret == HDF_SUCCESS) { + ret = OsalMutexUnlock(&g_mutexTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_UNLOCK); + } + + OsalMSleep(HDF_THREAD_TEST_SLEEP_US); + + ret = OsalSpinLock(&g_spinTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_LOCK); + ret = OsalSpinUnlock(&g_spinTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_UNLOCK); + + OsalMSleep(HDF_THREAD_TEST_SLEEP_MS); + OsalGetTime(&hdfTs2); + OsalDiffTime(&hdfTs1, &hdfTs2, &hdfTsDiff); + if (cnt % HDF_THREAD_TEST_MUX_CNT == 0) { + HDF_LOGE("%s %ds %dus", __func__, + (uint32_t)hdfTsDiff.sec, (uint32_t)hdfTsDiff.usec); + } + if (g_testEndFlag) { + break; + } + } + HDF_LOGE("%s thread return\n", __func__); + return 0; +} + +OSAL_DECLARE_TIMER(g_testTimerLoop1); +OSAL_DECLARE_TIMER(g_testTimerLoop2); +OSAL_DECLARE_TIMER(g_testTimerOnce); +#define HDF_TIMER1_PERIOD 630 +#define HDF_TIMER2_PERIOD 1350 +static int32_t g_timerPeriod1 = HDF_TIMER1_PERIOD; +static int32_t g_timerPeriod2 = HDF_TIMER2_PERIOD; +static int32_t g_timerPeriod3 = 10300; +static int32_t g_timerPeriod1Modify = 1250; +static int32_t g_timerPeriod2Modify = 750; +#define HDF_TIMER_TEST_MODIFY 8 +#define HDF_TEST_TIMER_PARA 1 +#define HDF_TEST_TIMER_MODIFY 2 +#define HDF_TEST_TIMER_END 3 +#define HDF_DBG_CNT_CTRL 10 + +static int g_timerLoop1RunFlag; +static int g_timer1Cnt = 0; +static void TimerLoopTest1(uintptr_t arg) +{ + int32_t para; + OsalTimespec hdfTs1 = { 0, 0 }; + static OsalTimespec hdfTs2 = { 0, 0 }; + OsalTimespec hdfTsDiff = { 0, 0 }; + static int index = HDF_TEST_TIMER_PARA; + int32_t ret; + + if (g_timer1Cnt == 0) { + OsalGetTime(&hdfTs2); + } + + para = *(int32_t *)arg; + if ((g_timer1Cnt >= 1) && (g_timer1Cnt != HDF_TIMER_TEST_MODIFY + 1)) { + OsalGetTime(&hdfTs1); + OsalDiffTime(&hdfTs2, &hdfTs1, &hdfTsDiff); + HDF_LOGE("%s %d %d %d %d %d", __func__, g_timer1Cnt, para, (int32_t)hdfTsDiff.sec, + (int32_t)hdfTsDiff.usec, g_timerPeriod1); + UT_TEST_CHECK_RET(!OsalCheckTime(&hdfTsDiff, g_timerPeriod1), OSAL_TIMER_PERIOD_CHECK); + UT_TEST_CHECK_RET(g_timerPeriod1 != para, OSAL_TIMER_PARA_CHECK); + if (index == HDF_TEST_TIMER_PARA) { + HDF_LOGE("[OSAL_UT_TEST]%s test timer para end", __func__); + index = HDF_TEST_TIMER_END; + } + if (index == HDF_TEST_TIMER_MODIFY) { + HDF_LOGE("[OSAL_UT_TEST]%s test timer modify function end", __func__); + index = HDF_TEST_TIMER_END; + } + } + + if (g_timer1Cnt == HDF_TIMER_TEST_MODIFY) { + g_timerPeriod1 = g_timerPeriod1Modify; + ret = OsalTimerSetTimeout(&g_testTimerLoop1, g_timerPeriod1); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_MODIFY_CHECK); + index = HDF_TEST_TIMER_MODIFY; + } + + OsalGetTime(&hdfTs2); + + g_timer1Cnt++; + g_timerLoop1RunFlag = true; +} + +static int g_timerLoop2RunFlag; +static int g_timer2Cnt = 0; +static void TimerLoopTest2(uintptr_t arg) +{ + int32_t para; + OsalTimespec hdfTs1 = { 0, 0 }; + static OsalTimespec hdfTs2 = { 0, 0 }; + OsalTimespec hdfTsDiff = { 0, 0 }; + static int index = HDF_TEST_TIMER_PARA; + int32_t ret; + + if (g_timer2Cnt == 0) { + OsalGetTime(&hdfTs2); + } + + para = *(int32_t *)arg; + if ((g_timer2Cnt >= 1) && (g_timer2Cnt != HDF_TIMER_TEST_MODIFY + 1)) { + OsalGetTime(&hdfTs1); + OsalDiffTime(&hdfTs2, &hdfTs1, &hdfTsDiff); + HDF_LOGE("%s %d %d %d %d %d", __func__, g_timer2Cnt, para, (int32_t)hdfTsDiff.sec, + (int32_t)hdfTsDiff.usec, g_timerPeriod2); + + UT_TEST_CHECK_RET(!OsalCheckTime(&hdfTsDiff, g_timerPeriod2), OSAL_TIMER_PERIOD_CHECK); + UT_TEST_CHECK_RET(g_timerPeriod2 != para, OSAL_TIMER_PARA_CHECK); + if (index == HDF_TEST_TIMER_PARA) { + HDF_LOGE("[OSAL_UT_TEST]%s test timer para end", __func__); + index = HDF_TEST_TIMER_END; + } + if (index == HDF_TEST_TIMER_MODIFY) { + HDF_LOGE("[OSAL_UT_TEST]%s test timer modify function end", __func__); + index = HDF_TEST_TIMER_END; + } + } + + if (g_timer2Cnt == HDF_TIMER_TEST_MODIFY) { + g_timerPeriod2 = g_timerPeriod2Modify; + HDF_LOGE("[OSAL_UT_TEST]%s modify timer", __func__); + ret = OsalTimerSetTimeout(&g_testTimerLoop2, g_timerPeriod2); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_MODIFY_CHECK); + index = HDF_TEST_TIMER_MODIFY; + } + OsalGetTime(&hdfTs2); + g_timer2Cnt++; + g_timerLoop2RunFlag = true; +} + +static int g_timerOnceRunFlag; +static void TimerOnceTest(uintptr_t arg) +{ + int32_t para; + para = *(int32_t *)arg; + + HDF_LOGE("%s %d", __func__, para); + UT_TEST_CHECK_RET(para != g_timerPeriod3, OSAL_TIMER_PARA_CHECK); + g_timerOnceRunFlag++; +} + +static void OsaTimerTest(void) +{ + int32_t ret; + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + g_timerPeriod1 = HDF_TIMER1_PERIOD; + g_timerPeriod2 = HDF_TIMER2_PERIOD; + + ret = OsalTimerCreate(&g_testTimerLoop1, g_timerPeriod1, TimerLoopTest1, (uintptr_t)&g_timerPeriod1); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_CREATE_LOOP); + OsalTimerStartLoop(&g_testTimerLoop1); + + ret = OsalTimerCreate(&g_testTimerLoop2, g_timerPeriod2, TimerLoopTest2, (uintptr_t)&g_timerPeriod2); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_CREATE_LOOP); + OsalTimerStartLoop(&g_testTimerLoop2); + + ret = OsalTimerCreate(&g_testTimerOnce, g_timerPeriod3, TimerOnceTest, (uintptr_t)&g_timerPeriod3); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_CREATE_ONCE); + OsalTimerStartOnce(&g_testTimerOnce); + + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +static void OsaTimerTestStop(void) +{ + int32_t ret; + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + ret = OsalTimerDelete(&g_testTimerLoop2); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIMER_STOP_CHECK); + g_timerLoop2RunFlag = false; + + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +#define HDF_FILE_SEEK_TEST 8 +static void OsaFWTest(int flag) +{ + struct OsalFirmware fw; + struct OsalFwBlock block; + int32_t ret; + char *name = NULL; + char *fwBuf = OsalFWTestBuff(); + + HDF_LOGE("[OSAL_UT_TEST]%s start", __func__); + if (flag != 0) { + HDF_LOGE("%s file do not exist %d", __func__, flag); + return; + } +#if defined(__LITEOS__) + name = TEST_FW_PATH_NAME; +#else + name = TEST_FW_NAME; +#endif + (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); + + (void)memset_s(&block, sizeof(block), 0, sizeof(block)); + ret = OsalReadFirmware(&fw, &block); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_READ); + HDF_LOGE("%s %d %d", name, block.dataSize, block.curOffset); + UT_TEST_CHECK_RET(memcmp(block.data, fwBuf, block.dataSize) != 0, OSAL_FW_DATA_CHECK); +#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); + ret = OsalReadFirmware(&fw, &block); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_READ); + HDF_LOGE("%s %d %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 + ret = OsalReleaseFirmware(&fw); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_FW_RELEASE); + 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 +#define THREAD_TEST_TIMER_STOP 25 + +static void OsaCheckRun(int cnt) +{ + OsalTimespec diffTime = { 0, 0 }; + + if (cnt == THREAD_TEST_TIMER_RUN) { + UT_TEST_CHECK_RET(g_timerOnceRunFlag == 0, OSAL_TIMER_RUN_CHECK); + UT_TEST_CHECK_RET(g_timerLoop2RunFlag == false, OSAL_TIMER_RUN_CHECK); + UT_TEST_CHECK_RET(g_timerLoop1RunFlag == false, OSAL_TIMER_RUN_CHECK); + HDF_LOGI("[OSAL_UT_TEST]%s timer run end", __func__); + } + + if (cnt == THREAD_TEST_TIMER_STOP) { + UT_TEST_CHECK_RET(g_timerOnceRunFlag != 1, OSAL_TIMER_STOP_CHECK); + UT_TEST_CHECK_RET(g_timerLoop2RunFlag != false, OSAL_TIMER_STOP_CHECK); + HDF_LOGI("[OSAL_UT_TEST]%s timer stop end", __func__); + } + if (cnt == THREAD_TEST_TIMER_STOP) { + OsalGetTime(&g_hdfTestEnd); + OsalDiffTime(&g_hdfTestBegin, &g_hdfTestEnd, &diffTime); + HDF_LOGI("[OSAL_UT_TEST]%s **** All case test end, use %ds****", __func__, (uint32_t)diffTime.sec); + HDF_LOGI("[OSAL_UT_TEST]%s ***************************", __func__); + } +} +static uint8_t g_irqData = 100; +uint32_t IRQHandle(uint32_t irqId, void *data) +{ + uint8_t *p = data; + static OsalTimespec hdfTs = { 0, 0 }; + OsalTimespec hdfTs2 = { 0, 0 }; + OsalTimespec hdfTsDiff = { 0, 0 }; + if (p == NULL) { + HDF_LOGE("%s nul ptr", __func__); + return 1; + } + + OsalGetTime(&hdfTs2); + OsalDiffTime(&hdfTs, &hdfTs2, &hdfTsDiff); + + HDF_LOGE("%s IRQ handle, irqId:%u, data:%u, %ds %dus", __func__, irqId, *p, + (int32_t)(hdfTsDiff.sec), (int32_t)(hdfTsDiff.usec)); + OsalGetTime(&hdfTs); + + return 0; +} + +#define IRQ_TEST_CNT 10 +void OsaIrqTest(void) +{ + int i = 0; + int32_t ret; + int32_t retFlag = HDF_FAILURE; +#if defined(__LITEOS__) + retFlag = HDF_SUCCESS; +#endif + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); +#if defined(__LITEOS__) + ret = OsalUnregisterIrq(IRQ_NUM_TEST, &g_irqData); + UT_TEST_CHECK_RET(ret == retFlag, OSAL_IRQ_UNREG_ABNORMAL); +#endif + ret = OsalRegisterIrq(IRQ_NUM_TEST, 0, IRQHandle, "test", &g_irqData); + UT_TEST_CHECK_RET(ret != retFlag, OSAL_IRQ_REG_NORMAL); + ret = OsalDisableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); + ret = OsalEnableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); +#if defined(__LITEOS__) + ret = OsalUnregisterIrq(IRQ_NUM_TEST, &g_irqData); + UT_TEST_CHECK_RET(ret != retFlag, OSAL_IRQ_UNREG_NORMAL); +#endif + + ret = OsalDisableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); + + ret = OsalEnableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); + +#if defined(__LITEOS__) + ret = OsalUnregisterIrq(IRQ_NUM_TEST, &g_irqData); + UT_TEST_CHECK_RET(ret == retFlag, OSAL_IRQ_UNREG_ABNORMAL); +#endif + + for (; i < IRQ_TEST_CNT; i++) { + ret = OsalRegisterIrq(IRQ_NUM_TEST, 0, IRQHandle, "test", &g_irqData); + UT_TEST_CHECK_RET(ret != retFlag, OSAL_IRQ_REG_NORMAL_STRESS); + ret = OsalDisableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); + ret = OsalEnableIrq(IRQ_NUM_TEST); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TEST_OTHER); +#if defined(__LITEOS__) + ret = OsalUnregisterIrq(IRQ_NUM_TEST, &g_irqData); + UT_TEST_CHECK_RET(ret != retFlag, OSAL_IRQ_UNREG_NORMAL_STRESS); +#endif + } + + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +#define IRQ_TEST_REG 1 +#define IRQ_TEST_ENABLE 10 +#define IRQ_TEST_DISABLE 20 +#define IRQ_TEST_UNREG 30 +#define THREAD_TEST_STOP_TIMER 25 +#define THREAD_TEST_STOP_TIMER_CHECK 45 + +#define THREAD_TEST_DBG_CTRL 200 +#define THREAD_TEST_MUX_BEGIN 3 +#define THREAD_TEST_MUX_END 5 +#define THREAD_TEST_SLEEP_MS 1 +static int g_thread3RunFlag; +static int32_t g_threadTestFlag = true; +static int ThreadTest(void *arg) +{ + static int cnt = 0; + HDF_STATUS ret; + HDF_LOGI("in threadTest %s %d", __func__, __LINE__); + + g_thread3RunFlag = true; + (void)arg; + + while (g_threadTestFlag) { + OsalSleep(THREAD_TEST_SLEEP_MS); + + if (cnt < THREAD_TEST_DBG_CTRL && cnt % HDF_DBG_CNT_CTRL == 0) { + HDF_LOGI("in threadTest %d", cnt); + } + cnt++; + + if (cnt == THREAD_TEST_MUX_BEGIN) { + HDF_LOGE("%s mutex Lock", __func__); + g_threadMuxLockFlag = true; + ret = OsalMutexTimedLock(&g_mutexTest, g_waitMutexTime); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_STRESS_TEST); + } + if (cnt == THREAD_TEST_MUX_END) { + ret = OsalMutexUnlock(&g_mutexTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_STRESS_TEST); + HDF_LOGE("%s mutex unLock", __func__); + g_threadMuxLockFlag = false; + } + + if (cnt == THREAD_TEST_STOP_TIMER) { + OsaTimerTestStop(); + } + OsaCheckRun(cnt); + if (g_testEndFlag) { + break; + } + } + HDF_LOGE("%s thread return\n", __func__); + return 0; +} + +#define HDF_TEST_STACK_SIZE 10000 +void OsaThreadTest1(void) +{ + struct OsalThreadParam threadCfg; + static int para = 120; + int32_t ret; + + (void)memset_s(&threadCfg, sizeof(threadCfg), 0, sizeof(threadCfg)); + threadCfg.name = "hdf_test"; + threadCfg.priority = OSAL_THREAD_PRI_HIGH; + threadCfg.stackSize = HDF_TEST_STACK_SIZE; + ret = OsalThreadCreate(&thread, (OsalThreadEntry)ThreadTest, (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) +{ + struct OsalThreadParam threadCfg; + int ret; + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + ret = OsalMutexInit(&g_mutexTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_CREATE); + ret = OsalSpinInit(&g_spinTest); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_CREATE); + + (void)memset_s(&threadCfg, sizeof(threadCfg), 0, sizeof(threadCfg)); + threadCfg.name = "hdf_test"; + threadCfg.priority = OSAL_THREAD_PRI_HIGH; + threadCfg.stackSize = HDF_TEST_STACK_SIZE; + ret = OsalThreadCreate(&thread1, (OsalThreadEntry)ThreadTest1, (void *)&g_test1Para); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + ret = OsalThreadStart(&thread1, &threadCfg); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + + OsalMSleep(HDF_THREAD_TEST_SLEEP_S); + + (void)memset_s(&threadCfg, sizeof(threadCfg), 0, sizeof(threadCfg)); + threadCfg.name = "hdf_test"; + threadCfg.priority = OSAL_THREAD_PRI_DEFAULT; + threadCfg.stackSize = HDF_TEST_STACK_SIZE; + ret = OsalThreadCreate(&thread2, (OsalThreadEntry)ThreadTest2, (void *)&g_test2Para); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + ret = OsalThreadStart(&thread2, &threadCfg); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + + OsaThreadTest1(); + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +#define TIME_TEST_SLEEP_S 2 +#define TIME_TEST_SLEEP_MS 200 +#define TIME_TEST_SLEEP_US 200 +#define TIME_TEST_MS_RANGE_H 210 +#define TIME_TEST_MS_RANGE_L 190 +#define TIME_TEST_US_RANGE_H 1000 +#define TIME_TEST_US_RANGE_L 200 +static void OsaTimeTest(void) +{ + int32_t ret; + OsalTimespec hdfTs = { 0, 0 }; + OsalTimespec hdfTs2 = { 0, 0 }; + OsalTimespec hdfTsDiff = { 0, 0 }; + HDF_LOGE("%s ms:%llu", __func__, OsalGetSysTimeMs()); + + OsalGetTime(&hdfTs); + OsalSleep(TIME_TEST_SLEEP_S); + 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); + 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); + + 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); + + 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); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_TIME_DIFFTIME); + UT_TEST_CHECK_RET(!OsalCheckTime(&hdfTsDiff, TIME_TEST_SLEEP_MS), OSAL_TIME_DIFFTIME); +} +enum { + MEM_ALIGN_TEST_0 = 1, + MEM_ALIGN_TEST_1 = 2, + MEM_ALIGN_TEST_2 = 3, + MEM_ALIGN_TEST_3 = 4, + MEM_ALIGN_TEST_4 = 7, + MEM_ALIGN_TEST_5 = 8, + MEM_ALIGN_TEST_6 = 16, +}; +#define MALLOC_TEST_CASE1_SIZE 0x4000 +#define MALLOC_TEST_CASE2_SIZE 0x1FF +#define MALLOC_TEST_CNT 1000 +static void OsaMemoryTest(void) +{ + void *buf = NULL; + int i = 0; + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + buf = OsalMemCalloc(MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + + buf = OsalMemCalloc(MALLOC_TEST_CASE2_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_SMALL); + OsalMemFree(buf); + + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_0, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf != NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_1, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf != NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_2, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf != NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_3, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_4, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf != NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_5, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + buf = OsalMemAllocAlign(MEM_ALIGN_TEST_6, MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_BIG); + OsalMemFree(buf); + + for (; i < MALLOC_TEST_CNT; i++) { + buf = OsalMemCalloc(MALLOC_TEST_CASE1_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_BIG_STRESS); + OsalMemFree(buf); + + buf = OsalMemCalloc(MALLOC_TEST_CASE2_SIZE); + UT_TEST_CHECK_RET(buf == NULL, OSAL_MALLOC_SMALL_STRESS); + OsalMemFree(buf); + } + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +static void OsaLogTest(void) +{ + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + HDF_LOGE("%s", __func__); + HDF_LOGW("%s", __func__); + HDF_LOGI("%s", __func__); + HDF_LOGD("%s", __func__); + HDF_LOGV("%s", __func__); + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +static void OsaMutexTest(void) +{ + HDF_STATUS ret; + struct OsalMutex mutex; + + HDF_LOGE("[OSAL_UT_TEST]%s start", __func__); + + (void)memset_s(&mutex, sizeof(mutex), 0, sizeof(mutex)); + ret = OsalMutexInit(&mutex); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_CREATE); + ret = OsalMutexTimedLock(&mutex, OSAL_TEST_TIME_DEFAULT); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_LOCK_TIMEOUT); + ret = OsalMutexUnlock(&mutex); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_UNLOCK); + ret = OsalMutexLock(&mutex); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_LOCK_FOREVER); + ret = OsalMutexUnlock(&mutex); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_UNLOCK); + ret = OsalMutexDestroy(&mutex); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_MUTEX_DESTROY); + + HDF_LOGE("[OSAL_UT_TEST]%s test no init", __func__); + ret = OsalMutexTimedLock(&mutex, HDF_WAIT_FOREVER); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_MUTEX_VISIT_DESTROY); + ret = OsalMutexUnlock(&mutex); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_MUTEX_VISIT_DESTROY); + ret = OsalMutexDestroy(&mutex); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_MUTEX_VISIT_DESTROY); + + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +static void OsaSpinTest(void) +{ + int32_t ret; + uint32_t flag = 0; + OSAL_DECLARE_SPINLOCK(spin); + + HDF_LOGE("[OSAL_UT_TEST]%s start", __func__); + (void)memset_s(&spin, sizeof(spin), 0, sizeof(spin)); + ret = OsalSpinInit(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_CREATE); + + ret = OsalSpinLock(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_LOCK); + ret = OsalSpinUnlock(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_UNLOCK); + + ret = OsalSpinLockIrq(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_LOCK_IRQ); + ret = OsalSpinUnlockIrq(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_UNLOCK_IRQ); + + ret = OsalSpinLockIrqSave(&spin, &flag); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_LOCK_IRQ_SAVE); + ret = OsalSpinUnlockIrqRestore(&spin, &flag); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_UNLOCK_IRQ_RESTORE); + + ret = OsalSpinDestroy(&spin); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SPIN_DESTROY); + + HDF_LOGE("[OSAL_UT_TEST]%s test no init", __func__); + ret = OsalSpinLock(&spin); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SPIN_LOCK_AFTER_DESTROY); + ret = OsalSpinUnlock(&spin); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SPIN_LOCK_AFTER_DESTROY); + ret = OsalSpinDestroy(&spin); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SPIN_LOCK_AFTER_DESTROY); + + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +static void OsaCheckThreadRun(void) +{ + UT_TEST_CHECK_RET(g_thread1RunFlag == 0, OSAL_THREAD_RUN_CHECK); + UT_TEST_CHECK_RET(g_thread1RunFlag == 0, OSAL_THREAD_RUN_CHECK); + UT_TEST_CHECK_RET(g_thread1RunFlag == 0, OSAL_THREAD_RUN_CHECK); + HDF_LOGI("[OSAL_UT_TEST]%s end", __func__); +} + +#define HDF_MAIN_SLEEP_S 20 +int OsaTestBegin(void) +{ + int ret; + (void)memset_s(g_osalTestCases, sizeof(g_osalTestCases), 0, sizeof(g_osalTestCases)); + g_testEndFlag = false; + g_timer1Cnt = 0; + g_timer2Cnt = 0; + OsalGetTime(&g_hdfTestBegin); + OsaLogTest(); + ret = OsalTestFileInit(); + OsalTestOther(ret); + OsaTimeTest(); + OsaMutexTest(); + OsaSpinTest(); + OsaIrqTest(); + OsaTimerTest(); + OsaThreadTest(); + OsaMemoryTest(); + HDF_LOGD("%s ", __func__); + OsaFWTest(ret); + OsalTestFileDeInit(); + + OsalSleep(HDF_MAIN_SLEEP_S); + HDF_LOGI("%s", __func__); + OsaCheckThreadRun(); + + return 0; +} + +int OsaTestEnd(void) +{ + OsalTimerDelete(&g_testTimerLoop1); + OsalTimerDelete(&g_testTimerLoop2); + OsalTimerDelete(&g_testTimerLoop1); + OsalStopThread(); + g_testEndFlag = true; + OsalThreadDestroy(&thread1); + OsalThreadDestroy(&thread); + OsalThreadDestroy(&thread2); + HDF_LOGE("%s", __func__); + + return 0; +} + +int OsaTestALLResult(void) +{ + int index; + for (index = 0; index < OSAL_TEST_CASE_CNT; index++) { + if (g_osalTestCases[index] != 0) { + HDF_LOGE("%s %d %d", __func__, g_osalTestCases[index], index); + return 1; + } + } + return 0; +} + diff --git a/test/unittest/osal/osal_case_cmd_test.h b/test/unittest/osal/osal_case_cmd_test.h new file mode 100644 index 00000000..4147f6b0 --- /dev/null +++ b/test/unittest/osal/osal_case_cmd_test.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 OSAL_TEST_CASE_CMD_H +#define OSAL_TEST_CASE_CMD_H + +#include "hdf_base.h" +#include "osal_test_case_def.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define BITS_PER_INT 32 + +#define OSAL_TEST_CASE_CNT (OSAL_TEST_MAX / BITS_PER_INT + 1) + +extern uint32_t g_osalTestCases[OSAL_TEST_CASE_CNT]; +extern bool g_testEndFlag; + +#define OSAL_TEST_CASE_SET(cmd) (g_osalTestCases[(cmd) / BITS_PER_INT] |= (1 << ((cmd) % BITS_PER_INT))) +#define OSAL_TEST_CASE_CHECK(cmd) (g_osalTestCases[(cmd) / BITS_PER_INT] & (1 << ((cmd) % BITS_PER_INT))) + +#define UT_TEST_CHECK_RET(val, cmd) do { \ + if ((val) && (g_testEndFlag == false)) { \ + HDF_LOGE("[OSAL_UT_TEST] %s %d %d OSA_UT_TEST_FAIL ", __func__, __LINE__, cmd); \ + OSAL_TEST_CASE_SET((cmd)); \ + } \ +} while (0) + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_TEST_CASE_CMD_H */ diff --git a/test/unittest/osal/osal_file_test.c b/test/unittest/osal/osal_file_test.c new file mode 100644 index 00000000..c52254b0 --- /dev/null +++ b/test/unittest/osal/osal_file_test.c @@ -0,0 +1,102 @@ +/* + * 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_file.h" +#include "osal_test_case_def.h" +#include "osal_test_type.h" +#include "securec.h" + +#define HDF_LOG_TAG osal_test + +#define UT_TEST_CHECK_RET(val) do { \ + if (val) { \ + HDF_LOGE("[OSAL_UT_TEST] %s %d OSA_UT_TEST_FAIL ", __func__, __LINE__); \ + } \ +} while (0) + +#define HDF_BUFF_LEN 30 +#define HDF_PATH_LEN 50 +#define HDF_FILE_MODE 0777 + +char *OsalFWTestBuff(void) +{ + static char *fwBuf = "123456789123456789123456789123456789123456789123456789123456789123456789"; + return fwBuf; +} +#if defined(__KERNEL__) +static void OsalPutWriteAccess(OsalFile *file) +{ + HDF_LOGE("%s %d %d", __func__, deny_write_access((struct file *)file->realFile), __LINE__); + HDF_LOGE("%s %d %d", __func__, atomic_read(&file_inode((struct file *)file->realFile)->i_writecount), __LINE__); + put_write_access(file_inode((struct file *)file->realFile)); + HDF_LOGE("%s %d %d", __func__, atomic_read(&file_inode((struct file *)file->realFile)->i_writecount), __LINE__); + HDF_LOGE("%s %d %d", __func__, deny_write_access((struct file *)file->realFile), __LINE__); +} +#endif + +int OsalTestFileInit(void) +{ + char *buf = OsalFWTestBuff(); +#if defined(__KERNEL__) + OsalFile file; +#endif + int32_t ret = -1; + +#if defined(__KERNEL__) + ret = OsalFileOpen(&file, TEST_FILE_PATH_NAME, O_CREAT | OSAL_O_RDWR, OSAL_S_IWRITE); +#else + ret = open(TEST_FILE_PATH_NAME, O_CREAT | O_RDWR, HDF_FILE_MODE); +#endif + if (ret < 0) { + HDF_LOGE("%s %d err:%d %s", __func__, __LINE__, ret, TEST_FILE_PATH_NAME); + return ret; + } + +#if defined(__KERNEL__) + UT_TEST_CHECK_RET(OsalFileWrite(&file, buf, strlen(buf)) == -1); +#else + UT_TEST_CHECK_RET(write(ret, buf, strlen(buf)) == -1); +#endif +#if defined(__KERNEL__) + OsalFileClose(&file); +#else + close(ret); +#endif + +#if defined(__KERNEL__) + ret = OsalFileOpen(&file, TEST_FW_PATH_NAME, O_CREAT | OSAL_O_RDWR, OSAL_S_IWRITE); +#else + ret = open(TEST_FW_PATH_NAME, O_CREAT | O_RDWR, HDF_FILE_MODE); +#endif + if (ret < 0) { + HDF_LOGE("%s %d err:%d %s", __func__, __LINE__, ret, TEST_FILE_PATH_NAME); + return ret; + } +#if defined(__KERNEL__) + UT_TEST_CHECK_RET(OsalFileWrite(&file, buf, strlen(buf)) == -1); +#else + UT_TEST_CHECK_RET(write(ret, buf, strlen(buf)) == -1); +#endif +#if defined(__KERNEL__) + OsalPutWriteAccess(&file); +#endif + +#if defined(__KERNEL__) + OsalFileClose(&file); +#else + close(ret); +#endif + return 0; +} + +void OsalTestFileDeInit(void) +{ + HDF_LOGE("%s end", __func__); +} + diff --git a/test/unittest/osal/osal_file_test.h b/test/unittest/osal/osal_file_test.h new file mode 100644 index 00000000..adf79ba2 --- /dev/null +++ b/test/unittest/osal/osal_file_test.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 OSAL_FILE_TEST_H +#define OSAL_FILE_TEST_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +char* OsalFWTestBuff(void); +int OsalTestFileInit(void); +void OsalTestFileDeInit(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* OSAL_FILE_TEST_H */ diff --git a/test/unittest/osal/osal_get_case_test.c b/test/unittest/osal/osal_get_case_test.c new file mode 100644 index 00000000..4a2db735 --- /dev/null +++ b/test/unittest/osal/osal_get_case_test.c @@ -0,0 +1,17 @@ +/* + * 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_case_cmd_test.h" + +int OsalGetTestResult(uint32_t cmd) +{ + HDF_LOGD("[OSAL_UT_TEST]%s %d start", __func__, cmd); + return OSAL_TEST_CASE_CHECK(cmd); +} + diff --git a/test/unittest/osal/osal_get_case_test.h b/test/unittest/osal/osal_get_case_test.h new file mode 100644 index 00000000..e4bbd64d --- /dev/null +++ b/test/unittest/osal/osal_get_case_test.h @@ -0,0 +1,25 @@ +/* + * 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_GET_CASE_H +#define OSAL_GET_CASE_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int OsaTestBegin(void); +int OsaTestEnd(void); +int OsaTestALLResult(void); +int OsalGetTestResult(uint32_t cmd); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_GET_CASE_H */ diff --git a/test/unittest/osal/osal_list_test.c b/test/unittest/osal/osal_list_test.c new file mode 100644 index 00000000..d6ff57f9 --- /dev/null +++ b/test/unittest/osal/osal_list_test.c @@ -0,0 +1,374 @@ +/* + * 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 "securec.h" +#include "hdf_dlist.h" +#include "hdf_log.h" +#include "osal_case_cmd_test.h" +#include "osal_work_test.h" +#include "osal_sem.h" +#include "osal_thread.h" +#include "osal_time.h" + +#define LIST_LEN_TAIL 10 +#define LIST_LEN_HEAD 10 + +#define HDF_LOG_TAG osal_test + +#define HDF_THREAD_TEST_SLEEP_MS 200 +#define HDF_TEST_STACK_SIZE 10000 + +typedef void(*EventHandle)(int para); + +typedef struct { + EventHandle handle; + struct DListHead list; +} OsalTestEventHandle; +bool g_testEndFlag = false; +static OsalTestEventHandle g_handleMng; +static OsalTestEventHandle g_handleArr[LIST_LEN_TAIL + LIST_LEN_HEAD]; + +static struct OsalSem g_hdfSem; +static struct OsalThread g_threadPostSem; +static struct OsalThread g_threadWaitSem; +static bool g_threadTestFlag = true; +static int32_t g_threadPara = 120; +static bool g_hdfListStatus = true; +static bool g_hdfSemStatus = true; + +#define MSG_SEND_PERIOD 5 +#define MSG_TEST_ITME_PERIOD 10 + +#define MSG_NOSEND_CNT 1 +#define MSG_NOSEND_CHECK_CNT 2 +#define MSG_EVENT_AGAIN 3 + +static int g_listCnt = 0; +static int g_listLen = LIST_LEN_TAIL + LIST_LEN_HEAD; +static void OsalEventHandlerTail(int para) +{ + static int cnt = 0; + + cnt += para; + if ((g_listLen != 0) && (cnt % g_listLen) == 0) { + HDF_LOGE("in %s msg:%d", __func__, cnt); + } + g_hdfListStatus = false; + g_listCnt++; +} + +static void OsalEventHandlerHead(int para) +{ + static int cnt = 0; + + cnt += para; + if ((g_listLen != 0) && (cnt % g_listLen) == 0) { + HDF_LOGE("in %s msg:%d", __func__, cnt); + } + g_hdfListStatus = false; + g_listCnt++; +} + +static void OsalTestList(const struct DListHead *head) +{ + OsalTestEventHandle *pos = NULL; + g_listCnt = 0; + DLIST_FOR_EACH_ENTRY(pos, head, OsalTestEventHandle, list) { + if (pos->handle != NULL) { + pos->handle(1); + } else { + HDF_LOGE("%s no handle\n", __func__); + UT_TEST_CHECK_RET(true, OSAL_LIST_TRAVERSAL); + } + } +} + +static void TestListAddTail(void) +{ + int i = 0; + for (; i < LIST_LEN_TAIL; i++) { + g_handleArr[i].handle = OsalEventHandlerTail; + DListHeadInit(&g_handleArr[i].list); + DListInsertTail(&g_handleArr[i].list, &g_handleMng.list); + } +} + +static void TestListMerge(void) +{ + OsalTestEventHandle list1[LIST_LEN_TAIL]; + OsalTestEventHandle list2[LIST_LEN_TAIL]; + OsalTestEventHandle mng1; + OsalTestEventHandle mng2; + int i = 0; + + HDF_LOGE("[OSAL_UT_TEST]%s start", __func__); + + DListHeadInit(&mng1.list); + mng1.handle = NULL; + for (; i < LIST_LEN_TAIL; i++) { + list1[i].handle = OsalEventHandlerTail; + DListHeadInit(&list1[i].list); + DListInsertTail(&list1[i].list, &mng1.list); + } + OsalTestList(&mng1.list); + UT_TEST_CHECK_RET(g_listCnt != LIST_LEN_TAIL, OSAL_LIST_TAIL); + + DListHeadInit(&mng2.list); + mng2.handle = NULL; + for (i = 0; i < LIST_LEN_TAIL; i++) { + list2[i].handle = OsalEventHandlerTail; + DListHeadInit(&list2[i].list); + DListInsertTail(&list2[i].list, &mng2.list); + } + OsalTestList(&mng2.list); + UT_TEST_CHECK_RET(g_listCnt != LIST_LEN_TAIL, OSAL_LIST_TAIL); + + DListMerge(&mng1.list, &mng2.list); + OsalTestList(&mng2.list); + UT_TEST_CHECK_RET(g_listCnt != g_listLen, OSAL_LIST_TAIL); + + OsalTestList(&mng1.list); + UT_TEST_CHECK_RET(g_listCnt != 0, OSAL_LIST_TAIL); + HDF_LOGE("[OSAL_UT_TEST]%s end", __func__); +} + +static void TestListAddHead(void) +{ + int i = 0; + for (; i < LIST_LEN_HEAD; i++) { + g_handleArr[LIST_LEN_TAIL + i].handle = OsalEventHandlerHead; + DListHeadInit(&g_handleArr[LIST_LEN_TAIL + i].list); + DListInsertHead(&g_handleArr[LIST_LEN_TAIL + i].list, &g_handleMng.list); + } +} + +static void TestListRemoveInlist(void) +{ + OsalTestEventHandle *pos = NULL; + OsalTestEventHandle *q = NULL; + + g_listCnt = 0; + DLIST_FOR_EACH_ENTRY_SAFE(pos, q, &g_handleMng.list, OsalTestEventHandle, list) { + if (&(pos->list) == &g_handleArr[0].list) { + DListRemove(&(pos->list)); + g_listLen--; + HDF_LOGE("%s find\n", __func__); + continue; + } + if (pos->handle != NULL) { + pos->handle(1); + } else { + HDF_LOGE("%s no handle\n", __func__); + UT_TEST_CHECK_RET(true, OSAL_LIST_TRAVERSAL); + } + } +} + +static void OsalTestListInit(void) +{ + int i = 0; + HDF_LOGE("[OSAL_UT_TEST]%s start", __func__); + + g_handleMng.handle = NULL; + DListHeadInit(&g_handleMng.list); + UT_TEST_CHECK_RET(DListIsEmpty(&g_handleMng.list) != true, OSAL_LIST_INIT); + OsalTestList(&g_handleMng.list); + UT_TEST_CHECK_RET(g_listCnt != 0, OSAL_LIST_COUNT_CHECK); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + + TestListAddTail(); + UT_TEST_CHECK_RET(DListIsEmpty(&g_handleMng.list) == true, OSAL_LIST_TAIL); + TestListAddHead(); + + OsalTestList(&g_handleMng.list); + UT_TEST_CHECK_RET(g_listCnt != g_listLen, OSAL_LIST_HEAD); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + + for (; i < g_listLen; i++) { + DListRemove(&g_handleArr[i].list); + } + UT_TEST_CHECK_RET(DListIsEmpty(&g_handleMng.list) != true, OSAL_LIST_REMOVE); + + OsalTestList(&g_handleMng.list); + UT_TEST_CHECK_RET(g_listCnt != 0, OSAL_LIST_TRAVERSAL); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + + TestListAddHead(); + TestListAddTail(); + + OsalTestList(&g_handleMng.list); + UT_TEST_CHECK_RET(g_listCnt != g_listLen, OSAL_LIST_TRAVERSAL); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + + TestListRemoveInlist(); + UT_TEST_CHECK_RET(g_listCnt != g_listLen, OSAL_LIST_TRAVERSAL_REMOVE); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + + DListInsertTail(&g_handleArr[0].list, &g_handleMng.list); + g_listLen++; + + UT_TEST_CHECK_RET(DListIsEmpty(&g_handleMng.list) == true, OSAL_LIST_EMPTY); + + TestListMerge(); +} + +static void OsalTestSemList(void) +{ + OsalTestEventHandle *pos = NULL; + OsalTestEventHandle *q = NULL; + + DLIST_FOR_EACH_ENTRY_SAFE(pos, q, &g_handleMng.list, OsalTestEventHandle, list) { + if (pos->handle != NULL) { + pos->handle(1); + } else { + HDF_LOGE("%s no handle\n", __func__); + UT_TEST_CHECK_RET(true, OSAL_LIST_TRAVERSAL); + } + } +} + +static bool g_noSemFlag = false; +static int ThreadTestPostSem(void *arg) +{ + static int cnt = 0; + static int index = 0; + HDF_STATUS ret; + + HDF_LOGI("[OSAL_UT_TEST]%s entry", __func__); + (void)arg; + + while (g_threadTestFlag) { + OsalMSleep(HDF_THREAD_TEST_SLEEP_MS); + if (cnt % MSG_SEND_PERIOD == 0) { + g_hdfSemStatus = true; + g_hdfListStatus = true; + index = 0; + g_listCnt = 0; + if (g_testEndFlag) { + g_noSemFlag = true; + break; + } + ret = OsalSemPost(&g_hdfSem); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SEM_POST); + } + if (index == MSG_NOSEND_CNT) { + UT_TEST_CHECK_RET(g_hdfSemStatus == true, OSAL_SEM_POST_RESULT); + UT_TEST_CHECK_RET(g_hdfListStatus == true, OSAL_LIST_STRESS); + UT_TEST_CHECK_RET(g_listCnt != g_listLen, OSAL_LIST_COUNT_CHECK); + HDF_LOGE("g_listCnt %d %d", g_listCnt, g_listLen); + g_hdfSemStatus = true; + g_hdfListStatus = true; + } + + if (index == MSG_NOSEND_CHECK_CNT) { + UT_TEST_CHECK_RET(g_hdfSemStatus == false, OSAL_SEM_POST_RESULT); + UT_TEST_CHECK_RET(g_hdfListStatus == false, OSAL_LIST_STRESS); + } + + TestAddRoute(cnt); + cnt++; + index++; + } + HDF_LOGE("%s exit", __func__); + return 0; +} + +static int ThreadTestWaitSem(void *arg) +{ + HDF_STATUS ret; + + HDF_LOGI("[OSAL_UT_TEST]%s entry", __func__); + (void)arg; + + while (g_threadTestFlag) { + ret = OsalSemWait(&g_hdfSem, HDF_WAIT_FOREVER); + if (ret == HDF_SUCCESS) { + OsalTestSemList(); + g_hdfSemStatus = false; + } else { + HDF_LOGE("[OSAL_UT_TEST]%s OsalSemWait fail", __func__); + UT_TEST_CHECK_RET(true, OSAL_SEM_WAIT_FOREVER); + } + if (g_testEndFlag && g_noSemFlag) { + break; + } + } + HDF_LOGE("%s exit", __func__); + return 0; +} + +static void OsalOsalSemInterface(void) +{ + HDF_STATUS ret; + struct OsalSem hdfSem = { NULL }; + + ret = OsalSemInit(&hdfSem, 0); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SEM_CREATE); + ret = OsalSemPost(&hdfSem); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SEM_POST); + ret = OsalSemWait(&hdfSem, HDF_WAIT_FOREVER); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SEM_WAIT_FOREVER); + ret = OsalSemWait(&hdfSem, 1); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SEM_WAIT_TIMEOUT); + ret = OsalSemDestroy(&hdfSem); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_SEM_DESTROY); + + HDF_LOGE("[OSAL_UT_TEST]%s no init test", __func__); + ret = OsalSemPost(&hdfSem); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SEM_VISIT_AFTER_DESTROY); + ret = OsalSemWait(&hdfSem, HDF_WAIT_FOREVER); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SEM_VISIT_AFTER_DESTROY); + ret = OsalSemWait(&hdfSem, 1); + UT_TEST_CHECK_RET(ret == HDF_SUCCESS, OSAL_SEM_VISIT_AFTER_DESTROY); + OsalSemDestroy(&hdfSem); +} + +static void OsalTestSem(void) +{ + struct OsalThreadParam threadCfg; + int32_t ret; + + HDF_LOGI("[OSAL_UT_TEST]%s start", __func__); + + OsalOsalSemInterface(); + + UT_TEST_CHECK_RET(OsalSemInit(&g_hdfSem, 0) != HDF_SUCCESS, OSAL_SEM_CREATE); + (void)memset_s(&threadCfg, sizeof(threadCfg), 0, sizeof(threadCfg)); + threadCfg.name = "hdf_test"; + threadCfg.priority = OSAL_THREAD_PRI_LOW; + threadCfg.stackSize = HDF_TEST_STACK_SIZE; + ret = OsalThreadCreate(&g_threadPostSem, (OsalThreadEntry)ThreadTestPostSem, (void *)&g_threadPara); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + + (void)memset_s(&threadCfg, sizeof(threadCfg), 0, sizeof(threadCfg)); + threadCfg.name = "hdf_test"; + threadCfg.priority = OSAL_THREAD_PRI_DEFAULT; + threadCfg.stackSize = HDF_TEST_STACK_SIZE; + ret = OsalThreadCreate(&g_threadWaitSem, (OsalThreadEntry)ThreadTestWaitSem, (void *)&g_threadPara); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + ret = OsalThreadStart(&g_threadWaitSem, &threadCfg); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); + + ret = OsalThreadStart(&g_threadPostSem, &threadCfg); + UT_TEST_CHECK_RET(ret != HDF_SUCCESS, OSAL_THREAD_CREATE); +} + +void OsalTestOther(int flag) +{ + HDF_LOGI("[OSAL_UT_TEST]%s entry", __func__); + OsalTestWork(flag); + OsalTestListInit(); + OsalTestSem(); +} + +void OsalStopThread(void) +{ + g_testEndFlag = true; + OsalThreadDestroy(&g_threadPostSem); + OsalThreadDestroy(&g_threadWaitSem); +} diff --git a/test/unittest/osal/osal_list_test.h b/test/unittest/osal/osal_list_test.h new file mode 100644 index 00000000..aac0ba7d --- /dev/null +++ b/test/unittest/osal/osal_list_test.h @@ -0,0 +1,23 @@ +/* + * 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_LIST_TEST_H +#define OSAL_LIST_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +void OsalTestOther(int flag); +void OsalStopThread(void); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_LIST_TEST_H */ diff --git a/test/unittest/osal/osal_test_case_def.h b/test/unittest/osal/osal_test_case_def.h new file mode 100644 index 00000000..6e50baf0 --- /dev/null +++ b/test/unittest/osal/osal_test_case_def.h @@ -0,0 +1,126 @@ +/* + * 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_TEST_CASE_DEF_H +#define OSAL_TEST_CASE_DEF_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +enum HdfOsalTestCaseCmd { + OSAL_TEST_START, + OSAL_MUTEX_CREATE, + OSAL_MUTEX_LOCK_TIMEOUT, + OSAL_MUTEX_UNLOCK, + OSAL_MUTEX_LOCK_FOREVER, + OSAL_MUTEX_DESTROY, + OSAL_MUTEX_VISIT_DESTROY, + OSAL_MUTEX_STRESS_TEST, + OSAL_MUTEX_OTHER, + OSAL_SPIN_CREATE, + OSAL_SPIN_LOCK, + OSAL_SPIN_UNLOCK, + OSAL_SPIN_LOCK_IRQ, + OSAL_SPIN_UNLOCK_IRQ, + OSAL_SPIN_LOCK_IRQ_SAVE, + OSAL_SPIN_UNLOCK_IRQ_RESTORE, + OSAL_SPIN_DESTROY, + OSAL_SPIN_LOCK_AFTER_DESTROY, + OSAL_SPIN_STRESS_TEST, + OSAL_SPIN_OTHER, + OSAL_TIME_SLEEP, + OSAL_TIME_MSLEEP, + OSAL_TIME_USLEEP, + OSAL_TIME_GETTIME, + OSAL_TIME_DIFFTIME, + OSAL_IRQ_UNREG_ABNORMAL, + OSAL_IRQ_REG_NORMAL, + OSAL_IRQ_UNREG_NORMAL, + OSAL_IRQ_REG_NORMAL_STRESS, + OSAL_IRQ_UNREG_NORMAL_STRESS, + OSAL_TIMER_CREATE_ONCE, + OSAL_TIMER_CREATE_LOOP, + OSAL_TIMER_RUN_CHECK, + OSAL_TIMER_PARA_CHECK, + OSAL_TIMER_PERIOD_CHECK, + OSAL_TIMER_MODIFY_CHECK, + OSAL_TIMER_STOP_CHECK, + OSAL_THREAD_CREATE, + OSAL_THREAD_PARA_CHECK, + OSAL_THREAD_RUN_CHECK, + OSAL_FW_REQUEST, + OSAL_FW_READ, + OSAL_FW_DATA_CHECK, + OSAL_FW_SEEK, + OSAL_FW_RELEASE, + OSAL_FW_READ_AFTER_RELEASE, + OSAL_MALLOC_BIG, + OSAL_MALLOC_SMALL, + OSAL_MALLOC_BIG_STRESS, + OSAL_MALLOC_SMALL_STRESS, + OSAL_LIST_INIT, + OSAL_LIST_EMPTY, + OSAL_LIST_COUNT_CHECK, + OSAL_LIST_TAIL, + OSAL_LIST_HEAD, + OSAL_LIST_REMOVE, + OSAL_LIST_TRAVERSAL, + OSAL_LIST_TRAVERSAL_REMOVE, + OSAL_LIST_STRESS, + OSAL_SEM_CREATE, + OSAL_SEM_POST, + OSAL_SEM_POST_RESULT, + OSAL_SEM_WAIT_TIMEOUT, + OSAL_SEM_WAIT_FOREVER, + OSAL_SEM_DESTROY, + OSAL_SEM_VISIT_AFTER_DESTROY, + OSAL_WORK_QUEUE_CREATE, + OSAL_WORK_CREATE, + OSAL_DELAY_WORK_CREATE, + OSAL_WORK_ADD, + OSAL_DELAY_WORK_ADD, + OSAL_WORK_RUN_CHECK, + OSAL_DELAY_WORK_RUN_CHECK, + OSAL_WORK_CANCEL, + OSAL_DELAY_WORK_CANCEL, + OSAL_ATOMIC_SET, + OSAL_ATOMIC_READ, + OSAL_ATOMIC_INC, + OSAL_ATOMIC_DEC, + OSAL_TEST_BIT, + OSAL_TEST_SET_BIT, + OSAL_TEST_CLR_BIT, + OSAL_CLR_BIT, + OSAL_FILE_OPEN_RD, + OSAL_FILE_READ_RD, + OSAL_FILE_WRITE_RD, + OSAL_FILE_SEEK_RD, + OSAL_FILE_CLOSE_RD, + OSAL_FILE_OPEN_RDWR, + OSAL_FILE_READ_RDWR, + OSAL_FILE_WRITE_RDWR, + OSAL_FILE_SEEK_RDWR, + OSAL_FILE_CLOSE_RDWR, + OSAL_TEST_OTHER, + OSAL_TEST_ALL, + OSAL_TEST_END, + OSAL_TEST_MAX, +}; +#define TEST_FILE_PATH_NAME "/storage/hdf.txt" +#if defined(__KERNEL__) +#define TEST_FW_PATH_NAME "/lib/firmware/hdf_fw.img" +#define TEST_FW_NAME "hdf_fw.img" +#else +#define TEST_FW_PATH_NAME "/storage/hdf_fw.img" +#endif +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_TEST_CASE_DEF_H */ diff --git a/test/unittest/osal/osal_test_entry.c b/test/unittest/osal/osal_test_entry.c new file mode 100644 index 00000000..c53b3303 --- /dev/null +++ b/test/unittest/osal/osal_test_entry.c @@ -0,0 +1,37 @@ +/* + * 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_test_entry.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "osal_case_cmd_test.h" +#include "osal_get_case_test.h" + +int32_t HdfOsalEntry(HdfTestMsg *msg) +{ + int32_t result = 0; + if (msg->subCmd < OSAL_TEST_MAX) { + if (msg->subCmd == OSAL_TEST_START) { + result = OsaTestBegin(); + } else if (msg->subCmd == OSAL_TEST_END) { + result = OsaTestEnd(); + } else if (msg->subCmd == OSAL_TEST_ALL) { + result = OsaTestALLResult(); + } else { + result = OsalGetTestResult(msg->subCmd); + } + } else { + return HDF_FAILURE; + } + + HDF_LOGD("HdfTest:osal test result[%s-%d %d]", ((result != 0) ? "failed" : "pass"), result, msg->subCmd); + msg->result = (result != 0) ? HDF_FAILURE : HDF_SUCCESS; + + return HDF_SUCCESS; +} + diff --git a/test/unittest/osal/osal_test_entry.h b/test/unittest/osal/osal_test_entry.h new file mode 100644 index 00000000..4aeefbcb --- /dev/null +++ b/test/unittest/osal/osal_test_entry.h @@ -0,0 +1,17 @@ +/* + * 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_TEST_ENTRY_H +#define OSAL_TEST_ENTRY_H + +#include "hdf_main_test.h" +#include "osal_case_cmd_test.h" + +int32_t HdfOsalEntry(HdfTestMsg *msg); + +#endif // OSAL_TEST_ENTRY_H diff --git a/test/unittest/osal/osal_work_test.c b/test/unittest/osal/osal_work_test.c new file mode 100644 index 00000000..870624dc --- /dev/null +++ b/test/unittest/osal/osal_work_test.c @@ -0,0 +1,217 @@ +/* + * 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 "securec.h" +#include "hdf_log.h" +#include "hdf_workqueue.h" +#include "osal_atomic.h" +#include "osal_file.h" +#include "osal_case_cmd_test.h" +#include "osal_time.h" + +#define HDF_LOG_TAG osal_lite + +#define MSG_SEND_PERIOD 5 +#define MSG_NOSEND_CNT 1 +#define MSG_NOSEND_CHECK_CNT 2 +#define MSG_EVENT_AGAIN 3 +#define MSG_EVENT_AGAIN_CHECK 4 + +#define TEST_ITEM_HAVE_EVENT 0 +#define TEST_ITEM_NO_EVENT 1 +#define TEST_ITEM_HAVE_EVENT_TIMEOUT 2 + +#define OSAL_TEST_PERIOD 20 +static bool g_osalWorkStatus = true; +static bool g_osalDelayStatus = true; +static HdfWork g_work; +static HdfWorkQueue g_workQue; + +static HdfWork g_delayWork; +static uint32_t g_workPara = 1000; +static int g_delayTime = 100; +#define DELAY_TIME_DEFAULT 100 +#define DELAY_TIME_FOR_OUT 10000 + +static void TestWorkEntry(void *para) +{ + static int cnt = 0; + if (para != NULL) { + if (cnt % DELAY_TIME_DEFAULT == 0) { + HDF_LOGE("%s %d", __func__, *(uint32_t *)para); + } + cnt++; + } + g_osalWorkStatus = false; +} + +static void TestDelayWorkEntry(void *para) +{ + static int cnt = 0; + + if (para != NULL) { + if (cnt % DELAY_TIME_DEFAULT == 0) { + HDF_LOGE("%s %d", __func__, *(uint32_t *)para); + } + cnt++; + } + + g_osalDelayStatus = false; +} + +static void TestWorkInit(void) +{ + HdfWorkQueueInit(&g_workQue, "osal_workQueue"); + + HdfWorkInit(&g_work, TestWorkEntry, (void *)&g_workPara); + + HdfDelayedWorkInit(&g_delayWork, TestDelayWorkEntry, (void *)&g_workPara); +} + +void TestAddRoute(int cnt) +{ + if (cnt % MSG_SEND_PERIOD == 0) { + g_osalWorkStatus = true; + HdfAddWork(&g_workQue, &g_work); + g_osalDelayStatus = true; + g_delayTime = DELAY_TIME_DEFAULT; + HdfAddDelayedWork(&g_workQue, &g_delayWork, g_delayTime); + } else if (cnt % MSG_SEND_PERIOD == TEST_ITEM_NO_EVENT) { + UT_TEST_CHECK_RET(g_osalWorkStatus, OSAL_WORK_RUN_CHECK); + UT_TEST_CHECK_RET(g_osalDelayStatus, OSAL_TEST_OTHER); + } else if (cnt % MSG_SEND_PERIOD == MSG_NOSEND_CHECK_CNT) { + g_delayTime = DELAY_TIME_FOR_OUT; + g_osalDelayStatus = true; + HdfAddDelayedWork(&g_workQue, &g_delayWork, g_delayTime); + g_osalWorkStatus = true; + HdfAddWork(&g_workQue, &g_work); + HdfCancelWorkSync(&g_work); + } else if (cnt % MSG_SEND_PERIOD == MSG_EVENT_AGAIN) { + HdfCancelDelayedWorkSync(&g_delayWork); + } else if (cnt % MSG_SEND_PERIOD == MSG_EVENT_AGAIN_CHECK) { + UT_TEST_CHECK_RET(g_osalDelayStatus == false, OSAL_DELAY_WORK_RUN_CHECK); + } +} + +#define ATOMIC_INC_VALUE 2 +static void OsalTestAtomic(void) +{ + OsalAtomic atomic; + unsigned long testBits = 0; + int32_t value; + + HDF_LOGE("%s test begin", __func__); + + OsalAtomicSet(&atomic, 1); + value = OsalAtomicRead(&atomic); + UT_TEST_CHECK_RET(value != 1, OSAL_ATOMIC_SET); + UT_TEST_CHECK_RET(value != 1, OSAL_ATOMIC_READ); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + OsalAtomicInc(&atomic); + value = OsalAtomicRead(&atomic); + UT_TEST_CHECK_RET(value != ATOMIC_INC_VALUE, OSAL_ATOMIC_INC); + UT_TEST_CHECK_RET(value != ATOMIC_INC_VALUE, OSAL_ATOMIC_READ); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + OsalAtomicDec(&atomic); + value = OsalAtomicRead(&atomic); + UT_TEST_CHECK_RET(value != 1, OSAL_ATOMIC_DEC); + UT_TEST_CHECK_RET(value != 1, OSAL_ATOMIC_READ); + + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + value = OsalTestBit(1, &testBits); + UT_TEST_CHECK_RET(value != 0, OSAL_TEST_BIT); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + value = OsalTestSetBit(1, &testBits); + UT_TEST_CHECK_RET(value != 0, OSAL_TEST_SET_BIT); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + value = OsalTestBit(1, &testBits); + UT_TEST_CHECK_RET(value != 1, OSAL_TEST_BIT); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + value = OsalTestClearBit(1, &testBits); + UT_TEST_CHECK_RET(value != 1, OSAL_TEST_CLR_BIT); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + value = OsalTestBit(1, &testBits); + UT_TEST_CHECK_RET(value != 0, OSAL_TEST_BIT); + HDF_LOGE("%s %d %d", __func__, __LINE__, value); + + OsalClearBit(1, &testBits); + value = OsalTestBit(1, &testBits); + UT_TEST_CHECK_RET(value != 0, OSAL_CLR_BIT); + + HDF_LOGE("%s %d %d", __func__, __LINE__, value); +} + +#define TEST_FILE_WRITE_CHAR 0xfe +#define TEST_FILE_OFFSET 10 +#define TEST_FILE_LEN 72 +static void OsalTestFile(int flag) +{ + OsalFile file; + char buf[TEST_FILE_LEN]; + int32_t len; + + HDF_LOGE("%s test begin", __func__); + if (flag != 0) { + HDF_LOGE("%s file do not exist %d", __func__, flag); + return; + } + (void)memset_s(buf, sizeof(buf), 0, sizeof(buf)); + UT_TEST_CHECK_RET(OsalFileOpen(&file, TEST_FILE_PATH_NAME, OSAL_O_RD_ONLY, OSAL_S_IREAD) != HDF_SUCCESS, + OSAL_FILE_OPEN_RD); + len = OsalFileRead(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len != TEST_FILE_LEN, OSAL_FILE_READ_RD); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + len = OsalFileLseek(&file, 0, 0); + UT_TEST_CHECK_RET(len == -1, OSAL_FILE_SEEK_RD); + (void)memset_s(buf, sizeof(buf), TEST_FILE_WRITE_CHAR, sizeof(buf)); + len = OsalFileWrite(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len != -1, OSAL_FILE_WRITE_RD); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + len = OsalFileLseek(&file, TEST_FILE_OFFSET, 0); + UT_TEST_CHECK_RET(len != TEST_FILE_OFFSET, OSAL_FILE_SEEK_RD); + len = OsalFileRead(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len != (TEST_FILE_LEN - TEST_FILE_OFFSET), OSAL_FILE_READ_RD); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + OsalFileClose(&file); + len = OsalFileRead(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len >= 0, OSAL_FILE_READ_RD); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + + (void)memset_s(buf, sizeof(buf), 0, sizeof(buf)); + UT_TEST_CHECK_RET(OsalFileOpen(&file, TEST_FILE_PATH_NAME, OSAL_O_RDWR, OSAL_S_IREAD) != HDF_SUCCESS, + OSAL_FILE_OPEN_RDWR); + len = OsalFileRead(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len != TEST_FILE_LEN, OSAL_FILE_READ_RDWR); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + len = OsalFileLseek(&file, 0, 0); + UT_TEST_CHECK_RET(len == -1, OSAL_FILE_SEEK_RDWR); + (void)memset_s(buf, sizeof(buf), TEST_FILE_WRITE_CHAR, sizeof(buf)); + len = OsalFileWrite(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len == -1, OSAL_FILE_WRITE_RDWR); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + len = OsalFileLseek(&file, TEST_FILE_OFFSET, 0); + UT_TEST_CHECK_RET(len != TEST_FILE_OFFSET, OSAL_FILE_SEEK_RDWR); + len = OsalFileRead(&file, buf, sizeof(buf)); + UT_TEST_CHECK_RET(len != (TEST_FILE_LEN - TEST_FILE_OFFSET), OSAL_FILE_READ_RDWR); + HDF_LOGE("%s %d %d", __func__, __LINE__, len); + OsalFileClose(&file); +} + +void OsalTestWork(int flag) +{ + TestWorkInit(); + OsalTestAtomic(); + OsalTestFile(flag); +} + diff --git a/test/unittest/osal/osal_work_test.h b/test/unittest/osal/osal_work_test.h new file mode 100644 index 00000000..daeea3fc --- /dev/null +++ b/test/unittest/osal/osal_work_test.h @@ -0,0 +1,23 @@ +/* + * 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_LITE_TEST_WAIT_H +#define OSAL_LITE_TEST_WAIT_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +void OsalTestWork(int flag); +void TestAddRoute(int cnt); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OSAL_LITE_TEST_WAIT_H */ diff --git a/test/unittest/platform/common/emmc_test.c b/test/unittest/platform/common/emmc_test.c new file mode 100644 index 00000000..02dc29db --- /dev/null +++ b/test/unittest/platform/common/emmc_test.c @@ -0,0 +1,172 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "emmc_if.h" +#include "emmc_test.h" + +#define HDF_LOG_TAG emmc_test_c + +struct EmmcTestFunc { + enum EmmcTestCmd type; + int32_t (*Func)(struct EmmcTester *tester); +}; + +static DevHandle EmmcTestGetHandle(struct EmmcTester *tester) +{ + if (tester == NULL) { + HDF_LOGE("%s: tester is null", __func__); + return NULL; + } + return EmmcOpen(tester->busNum); +} + +static void EmmcTestReleaseHandle(DevHandle handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: sdio handle is null", __func__); + return; + } + EmmcClose(handle); +} + +static int32_t TestEmmcGetCid(struct EmmcTester *tester) +{ + int32_t ret, i; + uint8_t cid[EMMC_CID_LEN] = {0}; + + ret = EmmcGetCid(tester->handle, cid, EMMC_CID_LEN); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: EmmcGetCid fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + for (i = 0; i < EMMC_CID_LEN; i++) { + HDF_LOGE("%s: cid[%d] = 0x%x\n", __func__, i, cid[i]); + } + return HDF_SUCCESS; +} + +struct EmmcTestFunc g_emmcTestFunc[] = { + { EMMC_GET_CID_01, TestEmmcGetCid }, +}; + +static int32_t EmmcTestEntry(struct EmmcTester *tester, int32_t cmd) +{ + int32_t i; + int32_t ret; + bool isFind = false; + + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + tester->handle = EmmcTestGetHandle(tester); + if (tester->handle == NULL) { + HDF_LOGE("%s: emmc test get handle fail", __func__); + return HDF_FAILURE; + } + for (i = 0; i < sizeof(g_emmcTestFunc) / sizeof(g_emmcTestFunc[0]); i++) { + if (cmd == g_emmcTestFunc[i].type && g_emmcTestFunc[i].Func != NULL) { + ret = g_emmcTestFunc[i].Func(tester); + isFind = true; + break; + } + } + if (isFind == false) { + ret = HDF_ERR_NOT_SUPPORT; + HDF_LOGE("%s: cmd %d not support", __func__, cmd); + } + EmmcTestReleaseHandle(tester->handle); + return ret; +} + +static int32_t EmmcTestFillConfig(struct EmmcTester *tester, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "busNum", &(tester->busNum), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill bus num fail!", __func__); + return ret; + } + + ret = drsOps->GetUint32(node, "hostId", &(tester->hostId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill hostId fail!", __func__); + return ret; + } + + HDF_LOGE("%s: busNum:%d, hostId:%d.", __func__, tester->busNum, tester->hostId); + return HDF_SUCCESS; +} + +static int32_t EmmcTestBind(struct HdfDeviceObject *device) +{ + static struct EmmcTester tester; + + if (device == NULL) { + HDF_LOGE("%s: device or config is null!", __func__); + return HDF_ERR_IO; + } + + device->service = &tester.service; + HDF_LOGE("%s: EMMC_TEST service init success!", __func__); + return HDF_SUCCESS; +} + +static int32_t EmmcTestInit(struct HdfDeviceObject *device) +{ + struct EmmcTester *tester = NULL; + int32_t ret; + + if (device == NULL || device->service == NULL || device->property == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + + tester = (struct EmmcTester *)device->service; + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = EmmcTestFillConfig(tester, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config fail!", __func__); + return ret; + } + tester->TestEntry = EmmcTestEntry; + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static void EmmcTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } +} + +struct HdfDriverEntry g_emmcTestEntry = { + .moduleVersion = 1, + .Bind = EmmcTestBind, + .Init = EmmcTestInit, + .Release = EmmcTestRelease, + .moduleName = "PLATFORM_EMMC_TEST", +}; +HDF_INIT(g_emmcTestEntry); diff --git a/test/unittest/platform/common/emmc_test.h b/test/unittest/platform/common/emmc_test.h new file mode 100644 index 00000000..03bc6639 --- /dev/null +++ b/test/unittest/platform/common/emmc_test.h @@ -0,0 +1,33 @@ +/* + * 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 EMMC_TEST_H +#define EMMC_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" + +enum EmmcTestCmd { + EMMC_GET_CID_01 = 0, +}; + +struct EmmcTester { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*TestEntry)(struct EmmcTester *tester, int32_t cmd); + uint32_t busNum; + uint32_t hostId; + DevHandle handle; +}; + +static inline struct EmmcTester *GetEmmcTester(void) +{ + return (struct EmmcTester *)DevSvcManagerClntGetService("EMMC_TEST"); +} + +#endif /* EMMC_TEST_H */ diff --git a/test/unittest/platform/common/gpio_test.c b/test/unittest/platform/common/gpio_test.c new file mode 100644 index 00000000..7600efd6 --- /dev/null +++ b/test/unittest/platform/common/gpio_test.c @@ -0,0 +1,401 @@ +/* + * 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 "gpio_test.h" +#include "device_resource_if.h" +#include "gpio_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_irq.h" +#include "osal_time.h" + +#define HDF_LOG_TAG gpio_test + +#define GPIO_TEST_IRQ_TIMEOUT 1000 +#define GPIO_TEST_IRQ_DELAY 200 + +static int32_t GpioTestSetUp(struct GpioTester *tester) +{ + int32_t ret; + if (tester == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + ret = GpioGetDir(tester->gpio, &tester->oldDir); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get old dir fail! ret:%d", __func__, ret); + return ret; + } + ret = GpioRead(tester->gpio, &tester->oldVal); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read old val fail! ret:%d", __func__, ret); + return ret; + } + + tester->fails = 0; + tester->irqCnt = 0; + tester->irqTimeout = GPIO_TEST_IRQ_TIMEOUT; + return HDF_SUCCESS; +} + +static int32_t GpioTestTearDown(struct GpioTester *tester) +{ + int ret; + if (tester == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + ret = GpioSetDir(tester->gpio, tester->oldDir); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set old dir fail! ret:%d", __func__, ret); + return ret; + } + if (tester->oldDir == GPIO_DIR_IN) { + return HDF_SUCCESS; + } + ret = GpioWrite(tester->gpio, tester->oldVal); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: write old val fail! ret:%d", __func__, ret); + return ret; + } + + return HDF_SUCCESS; +} + +static int32_t TestCaseGpioSetGetDir(struct GpioTester *tester) +{ + int32_t ret; + uint16_t dirSet; + uint16_t dirGet; + + dirSet = GPIO_DIR_OUT; + dirGet = GPIO_DIR_IN; + +SET_GET_DIR: + ret = GpioSetDir(tester->gpio, dirSet); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set dir fail! ret:%d", __func__, ret); + return ret; + } + ret = GpioGetDir(tester->gpio, &dirGet); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get dir fail! ret:%d", __func__, ret); + return ret; + } + if (dirSet != dirGet) { + HDF_LOGE("%s: set dir:%u, but get:%u", __func__, dirSet, dirGet); + return HDF_FAILURE; + } + /* change the value and test one more time */ + if (dirSet == GPIO_DIR_OUT) { + dirSet = GPIO_DIR_IN; + dirGet = GPIO_DIR_OUT; + goto SET_GET_DIR; + } + return HDF_SUCCESS; +} + +static int32_t TestCaseGpioWriteRead(struct GpioTester *tester) +{ + int32_t ret; + uint16_t valWrite; + uint16_t valRead; + + ret = GpioSetDir(tester->gpio, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set dir fail! ret:%d", __func__, ret); + return ret; + } + valWrite = GPIO_VAL_LOW; + valRead = GPIO_VAL_HIGH; + +WRITE_READ_VAL: + ret = GpioWrite(tester->gpio, valWrite); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: write val:%u fail! ret:%d", __func__, valWrite, ret); + return ret; + } + ret = GpioRead(tester->gpio, &valRead); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read fail! ret:%d", __func__, ret); + return ret; + } + if (valWrite != valRead) { + HDF_LOGE("%s: write:%u, but get:%u", __func__, valWrite, valRead); + return HDF_FAILURE; + } + /* change the value and test one more time */ + if (valWrite == GPIO_VAL_HIGH) { + valWrite = GPIO_VAL_HIGH; + valRead = GPIO_VAL_LOW; + goto WRITE_READ_VAL; + } + return HDF_SUCCESS; +} + +static int32_t TestCaseGpioIrqHandler(uint16_t gpio, void *data) +{ + struct GpioTester *tester = (struct GpioTester *)data; + + HDF_LOGE("%s: >>>>>>>>>>>>>>>>>>>>>enter gpio:%u<<<<<<<<<<<<<<<<<<<<<<", __func__, gpio); + if (tester != NULL) { + tester->irqCnt++; + return GpioDisableIrq(gpio); + } + return HDF_FAILURE; +} + +static inline void TestHelperGpioInverse(uint16_t gpio, uint16_t mode) +{ + uint16_t dir = 0; + uint16_t valRead = 0; + + (void)GpioRead(gpio, &valRead); + (void)GpioWrite(gpio, (valRead == GPIO_VAL_LOW) ? GPIO_VAL_HIGH : GPIO_VAL_LOW); + (void)GpioRead(gpio, &valRead); + (void)GpioGetDir(gpio, &dir); + HDF_LOGD("%s, gpio:%u, val:%u, dir:%u, mode:%x", __func__, gpio, valRead, dir, mode); +} + +static int32_t TestCaseGpioIrq(struct GpioTester *tester, uint16_t mode, bool inverse) +{ + int32_t ret; + uint32_t timeout; + + ret = GpioSetIrq(tester->gpioIrq, mode, TestCaseGpioIrqHandler, (void *)tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set irq fail! ret:%d", __func__, ret); + return ret; + } + ret = GpioEnableIrq(tester->gpioIrq); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: enable irq fail! ret:%d", __func__, ret); + (void)GpioUnSetIrq(tester->gpioIrq); + return ret; + } + + for (timeout = 0; tester->irqCnt <= 0 && timeout <= tester->irqTimeout; + timeout += GPIO_TEST_IRQ_DELAY) { + if (inverse) { + // maybe can make a inverse ... + TestHelperGpioInverse(tester->gpioIrq, mode); + } + OsalMSleep(GPIO_TEST_IRQ_DELAY); + } + (void)GpioUnSetIrq(tester->gpioIrq); + +#if defined(_LINUX_USER_) || defined(__KERNEL__) + if (inverse) { + HDF_LOGI("%s: do not judge edge trigger!", __func__); + return HDF_SUCCESS; + } +#endif + if (tester->irqCnt <= 0) { + HDF_LOGE("%s: mode:%x on %u fail!", __func__, mode, tester->gpioIrq); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static int32_t TestCaseGpioIrqLevel(struct GpioTester *tester) +{ + uint16_t mode; + uint16_t valRead = 0; + + (void)GpioSetDir(tester->gpioIrq, GPIO_DIR_IN); + (void)GpioRead(tester->gpioIrq, &valRead); + mode = (valRead == GPIO_VAL_LOW) ? GPIO_IRQ_TRIGGER_LOW : GPIO_IRQ_TRIGGER_HIGH; + return TestCaseGpioIrq(tester, mode, false); +} + +static int32_t TestCaseGpioIrqEdge(struct GpioTester *tester) +{ + uint16_t mode; + + /* set dir to out for self trigger on liteos */ +#if defined(_LINUX_USER_) || defined(__KERNEL__) + (void)GpioSetDir(tester->gpioIrq, GPIO_DIR_IN); +#else + (void)GpioSetDir(tester->gpioIrq, GPIO_DIR_OUT); +#endif + mode = GPIO_IRQ_TRIGGER_FALLING | GPIO_IRQ_TRIGGER_RISING; + return TestCaseGpioIrq(tester, mode, true); +} + +int32_t TestCaseGpioIrqThread(struct GpioTester *tester) +{ + uint16_t mode; + /* set dir to out for self trigger on liteos */ +#if defined(_LINUX_USER_) || defined(__KERNEL__) + (void)GpioSetDir(tester->gpioIrq, GPIO_DIR_IN); +#else + (void)GpioSetDir(tester->gpioIrq, GPIO_DIR_OUT); +#endif + mode = GPIO_IRQ_TRIGGER_FALLING | GPIO_IRQ_TRIGGER_RISING | GPIO_IRQ_USING_THREAD; + return TestCaseGpioIrq(tester, mode, true); +} + +static int32_t TestCaseGpioReliability(struct GpioTester *tester) +{ + uint16_t val = 0; + + (void)GpioWrite(-1, val); /* invalid gpio number */ + (void)GpioWrite(tester->gpio, -1); /* invalid gpio value */ + + (void)GpioRead(-1, &val); /* invalid gpio number */ + (void)GpioRead(tester->gpio, NULL); /* invalid pointer */ + + (void)GpioSetDir(-1, val); /* invalid gpio number */ + (void)GpioSetDir(tester->gpio, -1); /* invalid value */ + + (void)GpioGetDir(-1, &val); /* invalid gpio number */ + (void)GpioGetDir(tester->gpio, NULL); /* invalid pointer */ + + /* invalid gpio number */ + (void)GpioSetIrq(-1, OSAL_IRQF_TRIGGER_RISING, TestCaseGpioIrqHandler, (void *)tester); + /* invalid irq mode */ + (void)GpioSetIrq(tester->gpioIrq, -1, TestCaseGpioIrqHandler, (void *)tester); + /* invalid irq handler */ + (void)GpioSetIrq(tester->gpioIrq, OSAL_IRQF_TRIGGER_RISING, NULL, (void *)tester); + /* invalid irq data */ + (void)GpioSetIrq(tester->gpioIrq, OSAL_IRQF_TRIGGER_RISING, TestCaseGpioIrqHandler, NULL); + + (void)GpioUnSetIrq(-1); /* invalid gpio number */ + + (void)GpioEnableIrq(-1); /* invalid gpio number */ + + (void)GpioDisableIrq(-1); /* invalid gpio number */ + + return HDF_SUCCESS; +} + +static int32_t GpioTestByCmd(struct GpioTester *tester, int32_t cmd) +{ + int32_t i; + + if (cmd == GPIO_TEST_SET_GET_DIR) { + return TestCaseGpioSetGetDir(tester); + } else if (cmd == GPIO_TEST_WRITE_READ) { + return TestCaseGpioWriteRead(tester); + } else if (cmd == GPIO_TEST_IRQ_LEVEL) { + return TestCaseGpioIrqLevel(tester); + } else if (cmd == GPIO_TEST_IRQ_EDGE) { + return TestCaseGpioIrqEdge(tester); + } else if (cmd == GPIO_TEST_IRQ_THREAD) { + return TestCaseGpioIrqThread(tester); + } else if (cmd == GPIO_TEST_RELIABILITY) { + return TestCaseGpioReliability(tester); + } + + for (i = 0; i < GPIO_TEST_MAX; i++) { + if (GpioTestByCmd(tester, i) != HDF_SUCCESS) { + tester->fails++; + } + } + HDF_LOGE("%s: **********PASS:%u FAIL:%u**************\n\n", + __func__, tester->total - tester->fails, tester->fails); + return (tester->fails > 0) ? HDF_FAILURE : HDF_SUCCESS; +} + +static int32_t GpioTestDoTest(struct GpioTester *tester, int32_t cmd) +{ + int32_t ret; + + if (tester == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + ret = GpioTestSetUp(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: setup fail!", __func__); + return ret; + } + + ret = GpioTestByCmd(tester, cmd); + + (void)GpioTestTearDown(tester); + return ret; +} + +static int32_t GpioTestReadConfig(struct GpioTester *tester, const struct DeviceResourceNode *node) +{ + int32_t ret; + uint32_t tmp; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "gpio", &tmp, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read gpio fail!", __func__); + return ret; + } + tester->gpio = (uint16_t)tmp; + + ret = drsOps->GetUint32(node, "gpioIrq", &tmp, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read gpioIrq fail!", __func__); + return ret; + } + tester->gpioIrq = (uint16_t)tmp; + tester->doTest = GpioTestDoTest; + + return HDF_SUCCESS; +} + +static int32_t GpioTestBind(struct HdfDeviceObject *device) +{ + int32_t ret; + static struct GpioTester tester; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("%s: device or property is null!", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + ret = GpioTestReadConfig(&tester, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config fail!", __func__); + return ret; + } + + tester.total = GPIO_TEST_MAX; + device->service = &tester.service; + +#ifdef GPIO_TEST_ON_INIT + HDF_LOGE("%s: test on init!", __func__); + tester.doTest(&tester, -1); +#endif + return HDF_SUCCESS; +} + +static int32_t GpioTestInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static void GpioTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + return; +} + +struct HdfDriverEntry g_gpioTestEntry = { + .moduleVersion = 1, + .Bind = GpioTestBind, + .Init = GpioTestInit, + .Release = GpioTestRelease, + .moduleName = "PLATFORM_GPIO_TEST", +}; +HDF_INIT(g_gpioTestEntry); diff --git a/test/unittest/platform/common/gpio_test.h b/test/unittest/platform/common/gpio_test.h new file mode 100644 index 00000000..6d8b1940 --- /dev/null +++ b/test/unittest/platform/common/gpio_test.h @@ -0,0 +1,43 @@ +/* + * 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 GPIO_TEST_H +#define GPIO_TEST_H + +#include "hdf_device_desc.h" + +enum GpioTestCmd { + GPIO_TEST_SET_GET_DIR = 0, + GPIO_TEST_WRITE_READ = 1, + GPIO_TEST_IRQ_LEVEL = 2, + GPIO_TEST_IRQ_EDGE = 3, + GPIO_TEST_IRQ_THREAD = 4, + GPIO_TEST_RELIABILITY = 5, + GPIO_TEST_MAX = 6, +}; + +struct GpioTester { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*doTest)(struct GpioTester *tester, int32_t cmd); + uint16_t gpio; + uint16_t gpioIrq; + uint16_t oldDir; + uint16_t oldVal; + uint16_t irqCnt; + uint16_t total; + uint16_t fails; + uint32_t irqTimeout; +}; + +static inline struct GpioTester *GpioTesterGet(void) +{ + return (struct GpioTester *)DevSvcManagerClntGetService("GPIO_TEST"); +} + +#endif /* GPIO_TEST_H */ diff --git a/test/unittest/platform/common/i2c_driver_test.c b/test/unittest/platform/common/i2c_driver_test.c new file mode 100644 index 00000000..e5e28545 --- /dev/null +++ b/test/unittest/platform/common/i2c_driver_test.c @@ -0,0 +1,124 @@ +/* + * 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 "i2c_test.h" +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" + +static struct I2cTestConfig g_config; + +static int32_t I2cTestDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + HDF_LOGD("%s: enter!", __func__); + + if (cmd == 0) { + if (reply == NULL) { + HDF_LOGE("%s: reply is null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufWriteBuffer(reply, &g_config, sizeof(g_config))) { + HDF_LOGE("%s: writ reply fail!", __func__); + return HDF_ERR_IO; + } + } else { + return HDF_ERR_NOT_SUPPORT; + } + + return HDF_SUCCESS; +} + +static int32_t I2cTestReadConfig(struct I2cTestConfig *config, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __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__); + return ret; + } + + ret = drsOps->GetUint16(node, "dev_addr", &config->devAddr, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read dev addr fail!", __func__); + return ret; + } + + ret = drsOps->GetUint16(node, "reg_len", &config->regLen, 1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read reg len fail!", __func__); + return ret; + } + + ret = drsOps->GetUint16(node, "reg_addr", &config->regAddr, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read reg addr fail!", __func__); + return ret; + } + + ret = drsOps->GetUint16(node, "buf_size", &config->bufSize, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read buf size fail!", __func__); + return ret; + } + + return HDF_SUCCESS; +} + +static int32_t I2cTestBind(struct HdfDeviceObject *device) +{ + int32_t ret; + static struct IDeviceIoService service; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("%s: device or config is null!", __func__); + return HDF_ERR_IO; + } + + ret = I2cTestReadConfig(&g_config, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config fail!", __func__); + return ret; + } + + service.Dispatch = I2cTestDispatch; + device->service = &service; + + return HDF_SUCCESS; +} + +static int32_t I2cTestInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static void I2cTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + return; +} + +struct HdfDriverEntry g_i2cTestEntry = { + .moduleVersion = 1, + .Bind = I2cTestBind, + .Init = I2cTestInit, + .Release = I2cTestRelease, + .moduleName = "PLATFORM_I2C_TEST", +}; +HDF_INIT(g_i2cTestEntry); diff --git a/test/unittest/platform/common/i2c_test.c b/test/unittest/platform/common/i2c_test.c new file mode 100644 index 00000000..47801f6e --- /dev/null +++ b/test/unittest/platform/common/i2c_test.c @@ -0,0 +1,373 @@ +/* + * 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 "i2c_test.h" +#include "hdf_base.h" +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "i2c_if.h" +#include "osal_mem.h" +#include "osal_thread.h" +#include "osal_time.h" +#include "securec.h" + +#define HDF_LOG_TAG i2c_test + +#define I2C_TEST_8BIT 8 +#define I2C_TEST_MSG_NUM 2 +#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_WAIT_TIMES 200 + +static struct I2cMsg g_msgs[I2C_TEST_MSG_NUM]; +static uint8_t *g_buf; +static uint8_t g_regs[I2C_TEST_REG_LEN]; + +static int32_t I2cTestGetConfig(struct I2cTestConfig *config) +{ + int32_t ret; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + const void *buf = NULL; + uint32_t len; + + HDF_LOGD("I2cTestGetConfig: enter!"); + service = HdfIoServiceBind("I2C_TEST"); + if (service == NULL) { + return HDF_ERR_NOT_SUPPORT; + } + + reply = HdfSBufObtain(sizeof(*config) + sizeof(uint64_t)); + if (reply == NULL) { + HDF_LOGE("I2cTestGetConfig: failed to obtain reply!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = service->dispatcher->Dispatch(&service->object, 0, NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cTestGetConfig: remote dispatch fail:%d", ret); + } + + if (!HdfSbufReadBuffer(reply, &buf, &len)) { + HDF_LOGE("I2cTestGetConfig: read buf fail!"); + HdfSBufRecycle(reply); + return HDF_ERR_IO; + } + + if (len != sizeof(*config)) { + HDF_LOGE("I2cTestGetConfig: config size:%u, but read size:%u!", sizeof(*config), len); + HdfSBufRecycle(reply); + return HDF_ERR_IO; + } + + if (memcpy_s(config, sizeof(*config), buf, sizeof(*config)) != EOK) { + HDF_LOGE("I2cTestGetConfig: memcpy buf fail!"); + HdfSBufRecycle(reply); + return HDF_ERR_IO; + } + + HdfSBufRecycle(reply); + HDF_LOGD("I2cTestGetConfig: exit!"); + return HDF_SUCCESS; +} + +struct I2cTester *I2cTesterGet(void) +{ + int32_t ret; + static struct I2cTester tester; + static bool hasInit = false; + + if (hasInit == true) { + return &tester; + } + + ret = I2cTestGetConfig(&tester.config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("I2cTesterGet: read config fail:%d", ret); + return NULL; + } + + tester.handle = I2cOpen(tester.config.busNum); + if (tester.handle == NULL) { + HDF_LOGE("I2cTesterGet: open i2cBus:%u fail! handle:%p", tester.config.busNum, tester.handle); + return NULL; + } + + hasInit = true; + return &tester; +} + +static int32_t I2cTestMallocBuf(struct I2cTester *tester) +{ + struct I2cTestConfig *config = &tester->config; + + if (g_buf == NULL) { + g_buf = OsalMemCalloc(config->bufSize); + if (g_buf == NULL) { + HDF_LOGE("I2cTestMallocBuf: malloc buf fail!"); + return HDF_ERR_MALLOC_FAIL; + } + } + + g_regs[0] = (uint8_t)config->regAddr; + if (config->regLen > 1) { + g_regs[1] = g_regs[0]; + g_regs[0] = (uint8_t)(config->regAddr >> I2C_TEST_8BIT); + } + + g_msgs[0].addr = config->devAddr; + g_msgs[0].flags = 0; + g_msgs[0].len = config->regLen; + g_msgs[0].buf = g_regs; + + g_msgs[1].addr = config->devAddr; + g_msgs[1].flags = I2C_FLAG_READ; + g_msgs[1].len = config->bufSize; + g_msgs[1].buf = g_buf; + + return HDF_SUCCESS; +} + +int32_t I2cTestSetUpAll(void) +{ + struct I2cTester *tester = NULL; + struct I2cTestConfig *cfg = NULL; + + HDF_LOGD("I2cTestSetUpAll: enter!"); + tester = I2cTesterGet(); + if (tester == NULL) { + HDF_LOGE("I2cTestSetUpAll: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + tester->total = I2C_TEST_CMD_MAX; + tester->fails = 0; + + cfg = &tester->config; + HDF_LOGE("I2cTestSetUpAll: test on bus:0x%x, addr:0x%x, reg:0x%x, reglen:0x%x, size:0x%x", + cfg->busNum, cfg->devAddr, cfg->regAddr, cfg->regLen, cfg->bufSize); + if (I2cTestMallocBuf(tester) != HDF_SUCCESS) { + HDF_LOGE("I2cTestSetUpAll: set up test case fail!"); + } + HDF_LOGD("I2cTestSetUpAll: exit!"); + return HDF_SUCCESS; +} + +int32_t I2cTestTearDownAll(void) +{ + if (g_buf != NULL) { + OsalMemFree(g_buf); + g_buf = NULL; + } + + return HDF_SUCCESS; +} + +int32_t I2cTestSetUpSingle(void) +{ + return HDF_SUCCESS; +} + +int32_t I2cTestTearDownSingle(void) +{ + return HDF_SUCCESS; +} + +int32_t I2cTestTransfer(void) +{ + int32_t ret; + struct I2cTester *tester = NULL; + + tester = I2cTesterGet(); + if (tester == NULL || tester->handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + /* transfer one write msg */ + ret = I2cTransfer(tester->handle, g_msgs, 1); + if (ret != 1) { + HDF_LOGE("I2cTestTransfer: I2cTransfer(write) err:%d", ret); + return HDF_FAILURE; + } + + /* transfer one read msg */ + ret = I2cTransfer(tester->handle, g_msgs + 1, 1); + if (ret != 1) { + HDF_LOGE("I2cTestTransfer: I2cTransfer(read) err:%d", ret); + return HDF_FAILURE; + } + + /* transfer two msgs including a read msg and a write msg */ + ret = I2cTransfer(tester->handle, g_msgs, I2C_TEST_MSG_NUM); + if (ret != I2C_TEST_MSG_NUM) { + HDF_LOGE("I2cTestTransfer: I2cTransfer(mix) err:%d", ret); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t I2cTestWriteRead(void) +{ + return HDF_SUCCESS; +} + +static int I2cTestThreadFunc(void *parm) +{ + int32_t i, ret; + struct I2cTester *tester = NULL; + + tester = I2cTesterGet(); + if (tester == NULL || tester->handle == NULL) { + *((int32_t *)parm) = 1; + return HDF_ERR_INVALID_OBJECT; + } + + for (i = 0; i < I2C_TEST_MLTTHD_TIMES; i++) { + ret = I2cTransfer(tester->handle, g_msgs, I2C_TEST_MSG_NUM); + if (ret != I2C_TEST_MSG_NUM) { +#ifdef __USER__ + HDF_LOGE("I2cTransfer-user err in multithread test:%d", ret); +#else + HDF_LOGE("I2cTransfer-kerl err in multithread test:%d", ret); +#endif + } + } + + *((int32_t *)parm) = 1; + return HDF_SUCCESS; +} + +int32_t I2cTestMultiThread(void) +{ + int32_t ret; + struct OsalThread thread1, thread2; + struct OsalThreadParam cfg1, cfg2; + int32_t count1, count2; + + count1 = count2 = 0; + + ret = OsalThreadCreate(&thread1, (OsalThreadEntry)I2cTestThreadFunc, (void *)&count1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("create test thread1 fail:%d", ret); + return HDF_FAILURE; + } + + ret = OsalThreadCreate(&thread2, (OsalThreadEntry)I2cTestThreadFunc, (void *)&count2); + if (ret != HDF_SUCCESS) { + HDF_LOGE("create test thread1 fail:%d", ret); + return HDF_FAILURE; + } + + cfg1.name = "I2cTestThread-1"; + cfg2.name = "I2cTestThread-2"; + cfg1.priority = cfg2.priority = OSAL_THREAD_PRI_DEFAULT; + cfg1.stackSize = cfg2.stackSize = I2C_TEST_STACK_SIZE; + + ret = OsalThreadStart(&thread1, &cfg1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("start test thread1 fail:%d", ret); + return HDF_FAILURE; + } + + ret = OsalThreadStart(&thread2, &cfg2); + if (ret != HDF_SUCCESS) { + HDF_LOGE("start test thread2 fail:%d", ret); + return HDF_FAILURE; + } + + while (count1 == 0 || count2 == 0) { + HDF_LOGE("waitting testing thread finish..."); + OsalMSleep(I2C_TEST_WAIT_TIMES); + } + + (void)OsalThreadDestroy(&thread1); + (void)OsalThreadDestroy(&thread2); + return HDF_SUCCESS; +} + +int32_t I2cTestReliability(void) +{ + struct I2cTester *tester = NULL; + + HDF_LOGD("I2cTestReliability: test dfr for I2cTransfer ..."); + tester = I2cTesterGet(); + if (tester == NULL || tester->handle == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + /* invalid device handle */ + (void)I2cTransfer(NULL, g_msgs, I2C_TEST_MSG_NUM); + /* invalid device msgs */ + (void)I2cTransfer(tester->handle, NULL, I2C_TEST_MSG_NUM); + /* invalid device msg number */ + (void)I2cTransfer(tester->handle, g_msgs, -1); + + return HDF_SUCCESS; +} + +struct I2cTestEntry { + int cmd; + int32_t (*func)(void); + const char *name; +}; + +static struct I2cTestEntry g_entry[] = { + { I2C_TEST_CMD_TRANSFER, I2cTestTransfer, "I2cTestTransfer" }, + { I2C_TEST_CMD_WRITE_READ, I2cTestWriteRead, "I2cTestWriteRead" }, + { I2C_TEST_CMD_MULTI_THREAD, I2cTestMultiThread, "I2cTestMultiThread" }, + { I2C_TEST_CMD_RELIABILITY, I2cTestReliability, "I2cTestReliability" }, + { I2C_TEST_CMD_SETUP_ALL, I2cTestSetUpAll, "I2cTestSetUpAll" }, + { I2C_TEST_CMD_TEARDOWN_ALL, I2cTestTearDownAll, "I2cTestTearDownAll" }, + { I2C_TEST_CMD_SETUP_SINGLE, I2cTestSetUpSingle, "I2cTestSetUpSingle" }, + { I2C_TEST_CMD_TEARDOWN_SINGLE, I2cTestTearDownSingle, "I2cTestTearDownSingle" }, +}; + +int32_t I2cTestExecute(int cmd) +{ + uint32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + + if (cmd > I2C_TEST_CMD_MAX) { + HDF_LOGE("I2cTestExecute: invalid cmd:%d", cmd); + ret = HDF_ERR_NOT_SUPPORT; + goto __EXIT__; + } + + for (i = 0; i < sizeof(g_entry) / sizeof(g_entry[0]); i++) { + if (g_entry[i].cmd != cmd || g_entry[i].func == NULL) { + continue; + } + ret = g_entry[i].func(); + break; + } + +__EXIT__: + HDF_LOGE("[I2cTestExecute][======cmd:%d====ret:%d======]", cmd, ret); + return ret; +} + +void I2cTestExecuteAll(void) +{ + int32_t i; + int32_t ret; + int32_t fails = 0; + + /* setup env for all test cases */ + (void)I2cTestExecute(I2C_TEST_CMD_SETUP_ALL); + + for (i = 0; i <= I2C_TEST_CMD_RELIABILITY; i++) { + ret = I2cTestExecute(i); + fails += (ret != HDF_SUCCESS) ? 1 : 0; + } + + /* teardown env for all test cases */ + (void)I2cTestExecute(I2C_TEST_CMD_TEARDOWN_ALL); + + HDF_LOGE("I2cTestExecuteALL: **********PASS:%d FAIL:%d************\n\n", + I2C_TEST_CMD_RELIABILITY + 1 - fails, fails); +} diff --git a/test/unittest/platform/common/i2c_test.h b/test/unittest/platform/common/i2c_test.h new file mode 100644 index 00000000..0e308184 --- /dev/null +++ b/test/unittest/platform/common/i2c_test.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 I2C_TEST_H +#define I2C_TEST_H + +#include "i2c_if.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t I2cTestExecute(int cmd); +void I2cTestExecuteAll(void); + +enum I2cTestCmd { + I2C_TEST_CMD_TRANSFER = 0, + I2C_TEST_CMD_WRITE_READ = 1, + I2C_TEST_CMD_MULTI_THREAD = 2, + I2C_TEST_CMD_RELIABILITY = 3, + I2C_TEST_CMD_SETUP_ALL = 5, + I2C_TEST_CMD_TEARDOWN_ALL = 6, + I2C_TEST_CMD_SETUP_SINGLE = 7, + I2C_TEST_CMD_TEARDOWN_SINGLE = 8, + I2C_TEST_CMD_MAX = 9, +}; + +struct I2cTestConfig { + uint16_t busNum; + uint16_t devAddr; + uint16_t regAddr; + uint16_t regLen; + uint16_t bufSize; +}; + +struct I2cTester { + struct I2cTestConfig config; + DevHandle handle; + uint16_t total; + uint16_t fails; +}; +#ifdef __cplusplus +} +#endif +#endif /* I2C_TEST_H */ diff --git a/test/unittest/platform/common/mipi_dsi_test.c b/test/unittest/platform/common/mipi_dsi_test.c new file mode 100644 index 00000000..b991e1e4 --- /dev/null +++ b/test/unittest/platform/common/mipi_dsi_test.c @@ -0,0 +1,233 @@ +/* + * 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_mem.h" +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "mipi_dsi_test.h" + +#define HDF_LOG_TAG mipi_dsi_test + +static int32_t MipiDsiTestMallocBuf(struct MipiDsiTest *test) +{ + static uint8_t buf = 0x29; + + test->msgs.dataType = 0x05; /* 0x05: data type */ + test->msgs.dataLen = 1; /* 1: data len */ + test->msgs.delay = 0; + test->msgs.payload = &buf; + + return HDF_SUCCESS; +} + +static int32_t MipiDsiTestSetUp(struct MipiDsiTest *test) +{ + if (test == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + + if (test->handle == NULL) { + test->handle = MipiDsiOpen(test->devNo); + } + if (test->handle == NULL) { + HDF_LOGE("%s: fail!", __func__); + return HDF_FAILURE; + } + + test->fails = 0; + HDF_LOGD("%s: devNo:0x%x", __func__, test->devNo); + return MipiDsiTestMallocBuf(test); +} + +static void MipiDsiTestTearDown(struct MipiDsiTest *test) +{ + if (test == NULL) { + return; + } + if (test->handle != NULL) { + MipiDsiClose(test->handle); + test->handle = NULL; + } +} + +static int32_t CmpStVal(struct MipiCfg *a, struct MipiCfg *b) +{ + if (a->lane == b->lane && + a->mode == b->mode && + a->format == b->format && + a->burstMode == b->burstMode && + a->pixelClk == b->pixelClk && + a->phyDataRate == b->phyDataRate && + a->timing.xPixels == b->timing.xPixels && + a->timing.hsaPixels == b->timing.hsaPixels && + a->timing.hbpPixels == b->timing.hbpPixels && + a->timing.hlinePixels == b->timing.hlinePixels && + a->timing.vsaLines == b->timing.vsaLines && + a->timing.vbpLines == b->timing.vbpLines && + a->timing.vfpLines == b->timing.vfpLines && + a->timing.ylines == b->timing.ylines && + a->timing.edpiCmdSize == b->timing.edpiCmdSize) { + return true; + } + return false; +} + +static int32_t MipiDsiGetCfgTest(struct MipiDsiTest *test) +{ + int32_t ret; + struct MipiCfg cfg; + + ret = MipiDsiGetCfg(test->handle, &cfg); + if (ret == HDF_SUCCESS) { + if (CmpStVal(&cfg, &test->cfg)) { + return HDF_SUCCESS; + } + } + return HDF_FAILURE; +} + +static int32_t MipiDsiTxRxTest(struct MipiDsiTest *test) +{ + int32_t ret; + uint8_t data = 0x0A; /* 0x0A: lcd status reg */ + struct DsiCmdDesc cmd = { + .dataType = 0x06, /* 0x06: read data type */ + .dataLen = 1, /* 1: data len */ + .delay = 0, + .payload = &data, + }; + uint8_t buf = 0; + + ret = MipiDsiTx(test->handle, &test->msgs); + if (ret == HDF_SUCCESS) { + ret = MipiDsiRx(test->handle, &cmd, 1, &buf); /* 1: read len */ + if (ret == HDF_SUCCESS || ret == HDF_ERR_NOT_SUPPORT) { + return HDF_SUCCESS; + } + } else if (ret == HDF_ERR_NOT_SUPPORT) { + return HDF_SUCCESS; + } + HDF_LOGE("%s: fail", __func__); + return HDF_FAILURE; +} + +static int32_t MipiDsiToLpToHsTest(struct MipiDsiTest *test) +{ + MipiDsiSetHsMode(test->handle); + MipiDsiSetLpMode(test->handle); + return HDF_SUCCESS; +} + +static int32_t MipiDsiTestByCmd(struct MipiDsiTest *test, int32_t cmd) +{ + int32_t ret = HDF_FAILURE; + + switch (cmd) { + case MIPI_DSI_TEST_SET_CFG: + ret = MipiDsiSetCfg(test->handle, &test->cfg); + break; + case MIPI_DSI_TEST_GET_CFG: + ret = MipiDsiGetCfgTest(test); + break; + case MIPI_DSI_TEST_TX_RX: + ret = MipiDsiTxRxTest(test); + break; + case MIPI_DSI_TEST_TO_LP_TO_HS: + ret = MipiDsiToLpToHsTest(test); + break; + default: + HDF_LOGE("%s: not support", __func__); + break; + } + HDF_LOGI("test cmd %u, ret %d", cmd, ret); + return ret; +} + +static int32_t MipiDsiTestDoTest(struct MipiDsiTest *test, int32_t cmd) +{ + int32_t ret; + + if (test == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + ret = MipiDsiTestSetUp(test); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: setup fail!", __func__); + return ret; + } +#ifdef MIPI_DSI_TEST_ON_INIT + int32_t i; + for (i = 0; i < test->total; i++) { + if (MipiDsiTestByCmd(test, i) != HDF_SUCCESS) { + test->fails++; + } + } + HDF_LOGI("\n\n%s: **********PASS:%u FAIL:%u**************\n\n", + __func__, test->total - test->fails, test->fails); + ret = (test->fails > 0) ? HDF_FAILURE : HDF_SUCCESS; +#else + ret = MipiDsiTestByCmd(test, cmd); +#endif + MipiDsiTestTearDown(test); + return ret; +} + +static int32_t MipiDsiTestBind(struct HdfDeviceObject *device) +{ + static struct MipiDsiTest test; + + test.cfg.lane = DSI_2_LANES; + test.cfg.mode = DSI_VIDEO_MODE; + test.cfg.format = FORMAT_RGB_24_BIT; + test.cfg.burstMode = VIDEO_BURST_MODE; + test.cfg.timing.xPixels = 480; /* 480: width */ + test.cfg.timing.hsaPixels = 10; /* 10: horizontal sync porch */ + test.cfg.timing.hbpPixels = 20; /* 20: horizontal back porch */ + test.cfg.timing.hlinePixels = 530; /* 530: horizontal total width */ + test.cfg.timing.vsaLines = 2; /* 2: vertiacl sync width */ + test.cfg.timing.vbpLines = 14; /* 14: vertiacl back porch */ + test.cfg.timing.vfpLines = 16; /* 16: vertiacl front porch */ + test.cfg.timing.ylines = 960; /* 960: height */ + /* 0 : no care */ + test.cfg.timing.edpiCmdSize = 0; + /* + * pixel clk(kHZ): + * calculate: (width + hbp + hfp + hsw) * (height + vbp + vfp + vsw) * frameRate / 1000 + */ + test.cfg.pixelClk = 31546; /* 31546: pixel clk */ + /* + * phy data rate(Mbps): + * calculate: (pixelClk / 1000) * 24 / laneNum + */ + test.cfg.phyDataRate = 379; /* 379: mipi clk */ + test.devNo = 0; + test.total = MIPI_DSI_TEST_MAX; + test.doTest = MipiDsiTestDoTest; + device->service = &test.service; +#ifdef MIPI_DSI_TEST_ON_INIT + HDF_LOGI("%s: test on init!", __func__); + test.doTest(&test, -1); +#endif + return HDF_SUCCESS; +} + +static int32_t MipiDsiTestInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +struct HdfDriverEntry g_mipiDsiTestEntry = { + .moduleVersion = 1, + .Bind = MipiDsiTestBind, + .Init = MipiDsiTestInit, + .moduleName = "PLATFORM_MIPI_DSI_TEST", +}; +HDF_INIT(g_mipiDsiTestEntry); diff --git a/test/unittest/platform/common/mipi_dsi_test.h b/test/unittest/platform/common/mipi_dsi_test.h new file mode 100644 index 00000000..76229e43 --- /dev/null +++ b/test/unittest/platform/common/mipi_dsi_test.h @@ -0,0 +1,39 @@ +/* + * 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 MIPI_DSI_TEST_H +#define MIPI_DSI_TEST_H + +#include "hdf_device_desc.h" +#include "mipi_dsi_if.h" + +enum MipiDsiTestCmd { + MIPI_DSI_TEST_SET_CFG = 0, + MIPI_DSI_TEST_GET_CFG = 1, + MIPI_DSI_TEST_TX_RX = 2, + MIPI_DSI_TEST_TO_LP_TO_HS = 3, + MIPI_DSI_TEST_MAX = 4, +}; + +struct MipiDsiTest { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*doTest)(struct MipiDsiTest *test, int32_t cmd); + DevHandle handle; + struct DsiCmdDesc msgs; + struct MipiCfg cfg; + uint8_t devNo; + uint32_t total; + uint32_t fails; +}; + +static inline struct MipiDsiTest *MipiDsiTestServiceGet(void) +{ + return (struct MipiDsiTest *)DevSvcManagerClntGetService("PLATFORM_MIPI_DSI_TEST"); +} +#endif /* MIPI_DSI_TEST_H */ diff --git a/test/unittest/platform/common/platform_driver_test.c b/test/unittest/platform/common/platform_driver_test.c new file mode 100644 index 00000000..55917a14 --- /dev/null +++ b/test/unittest/platform/common/platform_driver_test.c @@ -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. + */ + +#include "i2c_test.h" +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" + +static void DoAllPlatformTest(void) +{ +#ifdef PLATFORM_TEST_ON_INIT +#ifdef LOSCFG_DRIVERS_HDF_PLATFORM_I2C + HDF_LOGE("DoAllPlatformTest: do i2c test ..."); + I2cTestExecuteAll(); +#endif +#endif +} + +static int32_t PlatformTestBind(struct HdfDeviceObject *device) +{ + struct IDeviceIoService service; + + if (device == NULL) { + HDF_LOGE("%s: device is null!", __func__); + return HDF_ERR_IO; + } + + device->service = &service; + DoAllPlatformTest(); + HDF_LOGE("PlatformTestBind: done!"); + return HDF_SUCCESS; +} + +static int32_t PlatformTestInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static void PlatformTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + return; +} + +struct HdfDriverEntry g_platformTestEntry = { + .moduleVersion = 1, + .Bind = PlatformTestBind, + .Init = PlatformTestInit, + .Release = PlatformTestRelease, + .moduleName = "PLATFORM_TEST_DRIVER", +}; +HDF_INIT(g_platformTestEntry); diff --git a/test/unittest/platform/common/pwm_test.c b/test/unittest/platform/common/pwm_test.c new file mode 100644 index 00000000..6c291326 --- /dev/null +++ b/test/unittest/platform/common/pwm_test.c @@ -0,0 +1,388 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "pwm_test.h" + +#define HDF_LOG_TAG pwm_test_c +struct PwmTestFunc { + enum PwmTestCmd type; + int32_t (*Func)(struct PwmTest *test); +}; + +static DevHandle PwmTestGetHandle(struct PwmTest *test) +{ + return PwmOpen(test->num); +} + +static void PwmTestReleaseHandle(DevHandle handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: pwm handle is null", __func__); + return; + } + PwmClose(handle); +} + +static int32_t PwmSetConfigTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmSetConfig(test->handle, &(test->cfg)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (memcmp(&cfg, &(test->cfg), sizeof(cfg)) != 0) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmGetConfigTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmSetPeriodTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmSetPeriod(test->handle, test->cfg.period); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (cfg.period != test->cfg.period) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmSetDutyTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmSetDuty(test->handle, test->cfg.duty); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (cfg.duty != test->cfg.duty) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmSetPolarityTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmSetPolarity(test->handle, test->cfg.polarity); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (cfg.polarity != test->cfg.polarity) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmEnableTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmEnable(test->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (cfg.status == 0) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +static int32_t PwmDisableTest(struct PwmTest *test) +{ + int32_t ret; + struct PwmConfig cfg = {0}; + + ret = PwmDisable(test->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + ret = PwmGetConfig(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error, ret %d", __func__, ret); + return HDF_FAILURE; + } + if (cfg.status == 1) { + HDF_LOGE("%s: failed", __func__); + return HDF_FAILURE; + } + HDF_LOGE("============= %s: success =============", __func__); + return ret; +} + +#define TEST_PERIOD 2147483647 +#define TEST_DUTY 2147483647 +#define TEST_POLARITY 10 +static int32_t PwmReliabilityTest(struct PwmTest *test) +{ + struct PwmConfig cfg = {0}; + + (void)PwmSetConfig(test->handle, &(test->cfg)); + (void)PwmSetConfig(test->handle, NULL); + (void)PwmGetConfig(test->handle, &cfg); + (void)PwmGetConfig(test->handle, NULL); + + (void)PwmSetPeriod(test->handle, 0); + (void)PwmSetPeriod(test->handle, TEST_PERIOD); + + (void)PwmSetDuty(test->handle, 0); + (void)PwmSetDuty(test->handle, TEST_DUTY); + + (void)PwmSetPolarity(test->handle, 0); + (void)PwmSetPolarity(test->handle, TEST_POLARITY); + + (void)PwmEnable(test->handle); + (void)PwmEnable(test->handle); + + (void)PwmDisable(test->handle); + (void)PwmDisable(test->handle); + HDF_LOGE("============= %s: success =============", __func__); + return HDF_SUCCESS; +} + +static int32_t PwmTestAll(struct PwmTest *test) +{ + int32_t total = 0; + int32_t error = 0; + + if (PwmSetPeriodTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmSetDutyTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmSetPolarityTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmGetConfigTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmEnableTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmSetConfigTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmDisableTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (PwmReliabilityTest(test) != HDF_SUCCESS) { + error++; + } + total++; + + HDF_LOGE("============= %s: Pwm Test Total %d Error %d =============", __func__, total, error); + return HDF_SUCCESS; +} + +static struct PwmTestFunc g_pwmTestFunc[] = { + { PWM_SET_PERIOD_TEST, PwmSetPeriodTest }, + { PWM_SET_DUTY_TEST, PwmSetDutyTest }, + { PWM_SET_POLARITY_TEST, PwmSetPolarityTest }, + { PWM_ENABLE_TEST, PwmEnableTest }, + { PWM_DISABLE_TEST, PwmDisableTest }, + { PWM_SET_CONFIG_TEST, PwmSetConfigTest }, + { PWM_GET_CONFIG_TEST, PwmGetConfigTest }, + { PWM_RELIABILITY_TEST, PwmReliabilityTest }, + { PWM_TEST_ALL, PwmTestAll }, +}; + +static int32_t PwmTestEntry(struct PwmTest *test, int32_t cmd) +{ + int32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + + if (test == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + test->handle = PwmTestGetHandle(test); + if (test->handle == NULL) { + HDF_LOGE("%s: spi test get handle fail", __func__); + return HDF_FAILURE; + } + for (i = 0; i < sizeof(g_pwmTestFunc) / sizeof(g_pwmTestFunc[0]); i++) { + if (cmd == g_pwmTestFunc[i].type && g_pwmTestFunc[i].Func != NULL) { + ret = g_pwmTestFunc[i].Func(test); + HDF_LOGE("%s: cmd %d ret %d", __func__, cmd, ret); + break; + } + } + + PwmTestReleaseHandle(test->handle); + return ret; +} + +static int32_t PwmTestBind(struct HdfDeviceObject *device) +{ + static struct PwmTest test; + + if (device != NULL) { + device->service = &test.service; + } else { + HDF_LOGE("%s: device is NULL", __func__); + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t PwmTestInitFromHcs(struct PwmTest *test, const struct DeviceResourceNode *node) +{ + int32_t ret; + uint32_t tmp; + + struct DeviceResourceIface *face = NULL; + + face = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (face == NULL) { + HDF_LOGE("%s: face is null", __func__); + return HDF_FAILURE; + } + if (face->GetUint32 == NULL) { + HDF_LOGE("%s: GetUint32 not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + ret = face->GetUint32(node, "num", &(test->num), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read num fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "period", &(test->cfg.period), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read period fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "duty", &(test->cfg.duty), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read duty fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "polarity", &tmp, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read polarity fail", __func__); + return HDF_FAILURE; + } + test->cfg.polarity = tmp; + ret = face->GetUint32(node, "status", &tmp, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read status fail", __func__); + return HDF_FAILURE; + } + test->cfg.status = tmp; + return HDF_SUCCESS; +} + +static int32_t PwmTestInit(struct HdfDeviceObject *device) +{ + struct PwmTest *test = NULL; + + if (device == NULL || device->service == NULL || device->property == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + test = (struct PwmTest *)device->service; + if (PwmTestInitFromHcs(test, device->property) != HDF_SUCCESS) { + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + test->TestEntry = PwmTestEntry; + return HDF_SUCCESS; +} + +static void PwmTestRelease(struct HdfDeviceObject *device) +{ + (void)device; + HDF_LOGE("%s: success", __func__); +} + +struct HdfDriverEntry g_pwmTestEntry = { + .moduleVersion = 1, + .Bind = PwmTestBind, + .Init = PwmTestInit, + .Release = PwmTestRelease, + .moduleName = "PLATFORM_PWM_TEST", +}; +HDF_INIT(g_pwmTestEntry); + diff --git a/test/unittest/platform/common/pwm_test.h b/test/unittest/platform/common/pwm_test.h new file mode 100644 index 00000000..b82a8b3e --- /dev/null +++ b/test/unittest/platform/common/pwm_test.h @@ -0,0 +1,42 @@ +/* + * 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 PWM_TEST_H +#define PWM_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" +#include "pwm_if.h" + +enum PwmTestCmd { + PWM_SET_PERIOD_TEST = 0, + PWM_SET_DUTY_TEST, + PWM_SET_POLARITY_TEST, + PWM_ENABLE_TEST, + PWM_DISABLE_TEST, + PWM_SET_CONFIG_TEST, + PWM_GET_CONFIG_TEST, + PWM_RELIABILITY_TEST, + PWM_TEST_ALL, +}; + +struct PwmTest { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*TestEntry)(struct PwmTest *test, int32_t cmd); + uint32_t num; + struct PwmConfig cfg; + DevHandle handle; +}; + +static inline struct PwmTest *GetPwmTest(void) +{ + return (struct PwmTest *)DevSvcManagerClntGetService("PWM_TEST"); +} + +#endif /* PWM_TEST_H */ diff --git a/test/unittest/platform/common/sdio_test.c b/test/unittest/platform/common/sdio_test.c new file mode 100644 index 00000000..800afbf8 --- /dev/null +++ b/test/unittest/platform/common/sdio_test.c @@ -0,0 +1,476 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "sdio_if.h" +#include "sdio_test.h" + +#define HDF_LOG_TAG sdio_test_c + +#define TEST_DATA_LEN 3 +#define TEST_BLOCKSIZE 512 +#define TEST_SDIO_BASE_ADDR 0x100 +#define TEST_FUNC_NUM 1 +#define TEST_ADDR_OFFSET 0x10 +#define TEST_FIXED_OFFSET 0x09 +#define TEST_TIME_OUT 1000 +#define TEST_ADDR_ADD 1 +#define TEST_FUNC0_ADDR 0xFE + +struct SdioTestFunc { + enum SdioTestCmd type; + int32_t (*Func)(struct SdioTester *tester); +}; + +static DevHandle SdioTestGetHandle(struct SdioTester *tester) +{ + if (tester == NULL) { + HDF_LOGE("%s: tester is null", __func__); + return NULL; + } + return SdioOpen(tester->busNum); +} + +static void SdioTestReleaseHandle(DevHandle handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: sdio handle is null", __func__); + return; + } + SdioClose(handle); +} + +static int32_t TestSdioIncrAddrReadAndWriteOtherBytes(struct SdioTester *tester) +{ + int32_t ret; + uint8_t data[TEST_DATA_LEN] = {0}; + const uint32_t addr = TEST_SDIO_BASE_ADDR * TEST_FUNC_NUM + TEST_ADDR_OFFSET + TEST_ADDR_ADD; + + ret = SdioReadBytes(tester->handle, &data[0], addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, data[0]:%d\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]); + return HDF_SUCCESS; +} + +static int32_t TestSdioIncrAddrReadAndWriteOneByte(struct SdioTester *tester) +{ + int32_t ret; + uint8_t val; + uint32_t addr; + + addr = TEST_SDIO_BASE_ADDR * TEST_FUNC_NUM + TEST_ADDR_OFFSET; + /* read 1 bits */ + ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d\n", __func__, val); + /* write 1 bits */ + ret = SdioWriteBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioWriteBytes fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: write, val:%d\n", __func__, val); + /* read 1 bits */ + addr++; + ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d.", __func__, val); + /* read 1 bits */ + addr++; + ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytes fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d.", __func__, val); + return HDF_SUCCESS; +} + +static int32_t TestSdioIncrAddrReadAndWriteBytes(struct SdioTester *tester) +{ + int32_t ret; + + SdioClaimHost(tester->handle); + ret = TestSdioIncrAddrReadAndWriteOneByte(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: TestSdioIncrAddrReadAndWriteOneByte fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + ret = TestSdioIncrAddrReadAndWriteOtherBytes(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: TestSdioIncrAddrReadAndWriteOtherBytes fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + + return ret; +} + +static int32_t TestSdioFixedAddrReadAndWriteOtherBytes(struct SdioTester *tester) +{ + int32_t ret; + uint8_t data[TEST_DATA_LEN] = {0}; + const uint32_t addr = TEST_SDIO_BASE_ADDR * TEST_FUNC_NUM + TEST_FIXED_OFFSET + TEST_ADDR_ADD; + + /* read bits */ + ret = SdioReadBytes(tester->handle, &data[0], addr, 1, 0); + if (ret != HDF_SUCCESS) { + 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]); + /* 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]); + return ret; +} + +static int32_t TestSdioFixedAddrReadAndWriteOneByte(struct SdioTester *tester) +{ + int32_t ret; + uint32_t addr; + uint8_t val; + + addr = TEST_SDIO_BASE_ADDR * TEST_FUNC_NUM + TEST_FIXED_OFFSET; + /* read 1 bits */ + ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytesFromFixedAddr fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d\n", __func__, val); + /* write 1 bits */ + ret = SdioWriteBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioWriteBytesToFixedAddr fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: write, val:%d.", __func__, val); + /* read 1 bits */ + addr++; + ret = SdioReadBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytesFromFixedAddr fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d.", __func__, val); + /* read 1 bits */ + addr++; + ret = SdioWriteBytes(tester->handle, &val, addr, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytesFromFixedAddr fail! ret=%d.", __func__, ret); + return HDF_FAILURE; + } + HDF_LOGE("%s: read, val:%d.", __func__, val); + + return ret; +} + +static int32_t TestSdioFixedAddrReadAndWriteBytes(struct SdioTester *tester) +{ + int32_t ret; + + SdioClaimHost(tester->handle); + ret = TestSdioFixedAddrReadAndWriteOtherBytes(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: TestSdioFixedAddrReadAndWriteOtherBytes fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + ret = TestSdioFixedAddrReadAndWriteOneByte(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: TestSdioFixedAddrReadAndWriteOneByte fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + + return ret; +} + +static int32_t TestSdioFunc0ReadAndWriteBytes(struct SdioTester *tester) +{ + int32_t ret; + uint8_t val; + + SdioClaimHost(tester->handle); + /* read sdio rev */ + ret = SdioReadBytesFromFunc0(tester->handle, &val, TEST_FUNC0_ADDR, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytesFromFunc0 fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + HDF_LOGE("%s: Func0 Read, val :%d.", __func__, val); + + /* write sdio rev */ + ret = SdioWriteBytesToFunc0(tester->handle, &val, TEST_FUNC0_ADDR, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioWriteBytesToFunc0 fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + + /* read sdio rev again */ + ret = SdioReadBytesFromFunc0(tester->handle, &val, TEST_FUNC0_ADDR, 1, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioReadBytesFromFunc0 fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + + HDF_LOGE("%s: Func0 Read, val :%d.", __func__, val); + return ret; +} + +static int32_t TestSdioSetAndGetFuncInfo(struct SdioTester *tester) +{ + int32_t ret; + SdioCommonInfo info = {0}; + + ret = SdioGetCommonInfo(tester->handle, &info, SDIO_FUNC_INFO); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioGetCommonInfo fail! ret=%d.", __func__, ret); + return ret; + } + HDF_LOGE("%s: succ! Timeout=%d.", __func__, info.funcInfo.enTimeout); + + info.funcInfo.enTimeout = TEST_TIME_OUT; + ret = SdioSetCommonInfo(tester->handle, &info, SDIO_FUNC_INFO); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioSetCommonInfo fail! ret=%d.", __func__, ret); + return ret; + } + + ret = SdioGetCommonInfo(tester->handle, &info, SDIO_FUNC_INFO); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioGetCommonInfo fail! ret=%d.", __func__, ret); + return ret; + } + HDF_LOGE("%s: again succ! Timeout=%d.", __func__, info.funcInfo.enTimeout); + + return HDF_SUCCESS; +} + +static int32_t TestSdioSetAndGetCommonInfo(struct SdioTester *tester) +{ + int32_t ret; + + SdioClaimHost(tester->handle); + ret = TestSdioSetAndGetFuncInfo(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: TestSdioSetAndGetFuncInfo fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + return ret; +} + +static int32_t TestSdioSetBlockSize(struct SdioTester *tester) +{ + int32_t ret; + SdioClaimHost(tester->handle); + ret = SdioSetBlockSize(tester->handle, TEST_BLOCKSIZE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioSetBlockSize fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + return ret; +} + +static int32_t TestSdioEnableFunc(struct SdioTester *tester) +{ + int32_t ret; + + SdioClaimHost(tester->handle); + ret = SdioEnableFunc(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioEnableFunc fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + return ret; +} + +static int32_t TestSdioDisableFunc(struct SdioTester *tester) +{ + int32_t ret; + + SdioClaimHost(tester->handle); + ret = SdioDisableFunc(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: SdioDisableFunc fail! ret=%d.", __func__, ret); + SdioReleaseHost(tester->handle); + return HDF_FAILURE; + } + SdioReleaseHost(tester->handle); + return ret; +} + +struct SdioTestFunc g_sdioTestFunc[] = { + { SDIO_DISABLE_FUNC_01, TestSdioDisableFunc }, + { SDIO_ENABLE_FUNC_01, TestSdioEnableFunc }, + { SDIO_SET_BLOCK_SIZE_01, TestSdioSetBlockSize }, + { SDIO_INCR_ADDR_READ_AND_WRITE_BYTES_01, TestSdioIncrAddrReadAndWriteBytes }, + { SDIO_FIXED_ADDR_READ_AND_WRITE_BYTES_01, TestSdioFixedAddrReadAndWriteBytes }, + { SDIO_FUNC0_READ_AND_WRITE_BYTES_01, TestSdioFunc0ReadAndWriteBytes }, + { SDIO_SET_AND_GET_COMMON_INFO_01, TestSdioSetAndGetCommonInfo }, +}; + +static int32_t SdioTestEntry(struct SdioTester *tester, int32_t cmd) +{ + int32_t i; + int32_t ret; + bool isFind = false; + + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL", __func__); + return HDF_ERR_INVALID_OBJECT; + } + tester->handle = SdioTestGetHandle(tester); + if (tester->handle == NULL) { + HDF_LOGE("%s: sdio test get handle fail", __func__); + return HDF_FAILURE; + } + for (i = 0; i < sizeof(g_sdioTestFunc) / sizeof(g_sdioTestFunc[0]); i++) { + if (cmd == g_sdioTestFunc[i].type && g_sdioTestFunc[i].Func != NULL) { + ret = g_sdioTestFunc[i].Func(tester); + isFind = true; + break; + } + } + if (isFind == false) { + ret = HDF_ERR_NOT_SUPPORT; + HDF_LOGE("%s: cmd %d not support", __func__, cmd); + } + SdioTestReleaseHandle(tester->handle); + return ret; +} + +static int32_t SdioTestFillConfig(struct SdioTester *tester, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "busNum", &(tester->busNum), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill bus num fail!", __func__); + return ret; + } + + ret = drsOps->GetUint32(node, "funcNum", &(tester->funcNum), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill funcNum fail!", __func__); + return ret; + } + ret = drsOps->GetUint32(node, "vendorId", &(tester->vendorId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill vendorId fail!", __func__); + return ret; + } + ret = drsOps->GetUint32(node, "deviceId", &(tester->deviceId), 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fill deviceId fail!", __func__); + return ret; + } + + HDF_LOGE("%s: busNum:%d, funcNum:%d, vendorId:0x%x, deviceId:0x%x.", __func__, + tester->busNum, tester->funcNum, tester->vendorId, tester->deviceId); + return HDF_SUCCESS; +} + +static int32_t SdioTestBind(struct HdfDeviceObject *device) +{ + static struct SdioTester tester; + + if (device == NULL) { + HDF_LOGE("%s: device or config is null!", __func__); + return HDF_ERR_IO; + } + + device->service = &tester.service; + HDF_LOGE("%s: Sdio_TEST service init success!", __func__); + return HDF_SUCCESS; +} + +static int32_t SdioTestInit(struct HdfDeviceObject *device) +{ + struct SdioTester *tester = NULL; + int32_t ret; + + if (device == NULL || device->service == NULL || device->property == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + + tester = (struct SdioTester *)device->service; + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = SdioTestFillConfig(tester, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config fail!", __func__); + return ret; + } + tester->TestEntry = SdioTestEntry; + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static void SdioTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } +} + +struct HdfDriverEntry g_sdioTestEntry = { + .moduleVersion = 1, + .Bind = SdioTestBind, + .Init = SdioTestInit, + .Release = SdioTestRelease, + .moduleName = "PLATFORM_SDIO_TEST", +}; +HDF_INIT(g_sdioTestEntry); diff --git a/test/unittest/platform/common/sdio_test.h b/test/unittest/platform/common/sdio_test.h new file mode 100644 index 00000000..2e69ada9 --- /dev/null +++ b/test/unittest/platform/common/sdio_test.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 SDIO_TEST_H +#define SDIO_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" + +enum SdioTestCmd { + SDIO_DISABLE_FUNC_01 = 0, + SDIO_ENABLE_FUNC_01, + SDIO_SET_BLOCK_SIZE_01, + SDIO_INCR_ADDR_READ_AND_WRITE_BYTES_01, + SDIO_FIXED_ADDR_READ_AND_WRITE_BYTES_01, + SDIO_FUNC0_READ_AND_WRITE_BYTES_01, + SDIO_SET_AND_GET_COMMON_INFO_01, +}; + +struct SdioTester { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*TestEntry)(struct SdioTester *tester, int32_t cmd); + uint32_t busNum; + uint32_t funcNum; + uint32_t vendorId; + uint32_t deviceId; + DevHandle handle; +}; + +static inline struct SdioTester *GetSdioTest(void) +{ + return (struct SdioTester *)DevSvcManagerClntGetService("SDIO_TEST"); +} + +#endif /* SDIO_TEST_H */ diff --git a/test/unittest/platform/common/spi_test.c b/test/unittest/platform/common/spi_test.c new file mode 100644 index 00000000..507376ee --- /dev/null +++ b/test/unittest/platform/common/spi_test.c @@ -0,0 +1,298 @@ +/* + * 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_base.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "spi_if.h" +#include "spi_test.h" + +#define HDF_LOG_TAG spi_test_c +struct SpiTestFunc { + enum SpiTestCmd type; + int32_t (*Func)(struct SpiTest *test); +}; + +static DevHandle SpiTestGetHandle(struct SpiTest *test) +{ + struct SpiDevInfo info; + + info.busNum = test->bus; + info.csNum = test->cs; + return SpiOpen(&info); +} + +static void SpiTestReleaseHandle(DevHandle handle) +{ + if (handle == NULL) { + HDF_LOGE("%s: spi handle is null", __func__); + return; + } + SpiClose(handle); +} + +#define BITS_PER_WORD 10 +#define MAX_SPEED_HZ 10000000 +static int32_t SpiSetCfgTest(struct SpiTest *test) +{ + int32_t ret; + struct SpiCfg cfg; + + cfg.mode = SPI_CLK_PHASE | SPI_MODE_LOOP; + cfg.bitsPerWord = BITS_PER_WORD; + cfg.maxSpeedHz = MAX_SPEED_HZ; + cfg.transferMode = SPI_INTERRUPT_TRANSFER; + ret = SpiSetCfg(test->handle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return ret; +} + +static int32_t SpiTransferTest(struct SpiTest *test) +{ + int32_t i; + struct SpiMsg msg; + + msg.rbuf = test->rbuf; + msg.wbuf = test->wbuf; + msg.len = test->len; + msg.csChange = 1; // switch off the CS after transfer + msg.delayUs = 0; + msg.speed = 0; // use default speed + if (SpiTransfer(test->handle, &msg, 1) != HDF_SUCCESS) { + HDF_LOGE("%s: spi transfer err", __func__); + return HDF_FAILURE; + } + for (i = 0; i < test->len; i++) { + HDF_LOGE("%s: wbuf[%d] = 0x%x rbuff[%d] = 0x%x", __func__, i, test->wbuf[i], i, test->rbuf[i]); + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t SpiWriteTest(struct SpiTest *test) +{ + if (SpiWrite(test->handle, test->wbuf, test->len) != HDF_SUCCESS) { + HDF_LOGE("%s: spi write err\n", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t SpiReadTest(struct SpiTest *test) +{ + if (SpiRead(test->handle, test->rbuf, test->len) != HDF_SUCCESS) { + HDF_LOGE("%s: spi read err\n", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t SpiReliabilityTest(struct SpiTest *test) +{ + struct SpiCfg cfg = {0}; + struct SpiMsg msg = {0}; + + (void)SpiSetCfg(test->handle, &cfg); + (void)SpiSetCfg(test->handle, NULL); + (void)SpiTransfer(test->handle, &msg, 1); + (void)SpiTransfer(test->handle, NULL, -1); + (void)SpiWrite(test->handle, test->wbuf, test->len); + (void)SpiWrite(test->handle, NULL, -1); + (void)SpiRead(test->handle, test->rbuf, test->len); + (void)SpiRead(test->handle, NULL, -1); + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t SpiTestAll(struct SpiTest *test) +{ + int32_t total = 0; + int32_t error = 0; + + if (SpiSetCfgTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (SpiTransferTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (SpiWriteTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (SpiReadTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (SpiReliabilityTest(test) != HDF_SUCCESS) { + error++; + } + total++; + HDF_LOGE("%s: Spi Test Total %d Error %d", __func__, total, error); + return HDF_SUCCESS; +} + +struct SpiTestFunc g_spiTestFunc[] = { + {SPI_SET_CFG_TEST, SpiSetCfgTest}, + {SPI_TRANSFER_TEST, SpiTransferTest}, + {SPI_WRITE_TEST, SpiWriteTest}, + {SPI_READ_TEST, SpiReadTest}, + {SPI_RELIABILITY_TEST, SpiReliabilityTest}, + {SPI_PERFORMANCE_TEST, NULL}, + {SPI_TEST_ALL, SpiTestAll}, +}; + +static int32_t SpiTestEntry(struct SpiTest *test, int32_t cmd) +{ + int32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + + if (test == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + test->handle = SpiTestGetHandle(test); + if (test->handle == NULL) { + HDF_LOGE("%s: spi test get handle fail", __func__); + return HDF_FAILURE; + } + for (i = 0; i < sizeof(g_spiTestFunc) / sizeof(g_spiTestFunc[0]); i++) { + if (cmd == g_spiTestFunc[i].type && g_spiTestFunc[i].Func != NULL) { + ret = g_spiTestFunc[i].Func(test); + HDF_LOGE("%s: cmd %d ret %d", __func__, cmd, ret); + break; + } + } + SpiTestReleaseHandle(test->handle); + return ret; +} + +static int32_t SpiTestBind(struct HdfDeviceObject *device) +{ + static struct SpiTest test; + + if (device != NULL) { + device->service = &test.service; + } else { + HDF_LOGE("%s: device is NULL", __func__); + } + return HDF_SUCCESS; +} + +static int32_t SpiTestInitFromHcs(struct SpiTest *test, const struct DeviceResourceNode *node) +{ + int32_t ret; + int32_t i; + uint32_t *tmp = NULL; + struct DeviceResourceIface *face = NULL; + + face = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (face == NULL) { + HDF_LOGE("%s: face is null", __func__); + return HDF_FAILURE; + } + if (face->GetUint32 == NULL || face->GetUint32Array == NULL) { + HDF_LOGE("%s: GetUint32 or GetUint32Array not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + ret = face->GetUint32(node, "bus", &test->bus, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read bus fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "cs", &test->cs, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read cs fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "len", &test->len, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read len fail", __func__); + return HDF_FAILURE; + } + test->wbuf = (uint8_t *)OsalMemCalloc(test->len); + if (test->wbuf == NULL) { + HDF_LOGE("%s: wbuf OsalMemCalloc error\n", __func__); + return HDF_ERR_MALLOC_FAIL; + } + tmp = (uint32_t *)OsalMemCalloc(test->len * sizeof(uint32_t)); + if (tmp == NULL) { + HDF_LOGE("%s: tmp OsalMemCalloc error\n", __func__); + OsalMemFree(test->wbuf); + return HDF_ERR_MALLOC_FAIL; + } + ret = face->GetUint32Array(node, "wbuf", tmp, test->len, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read wbuf fail", __func__); + OsalMemFree(test->wbuf); + OsalMemFree(tmp); + return HDF_FAILURE; + } + for (i = 0; i < test->len; i++) { + test->wbuf[i] = tmp[i]; + } + OsalMemFree(tmp); + test->rbuf = (uint8_t *)OsalMemCalloc(test->len); + if (test->rbuf == NULL) { + HDF_LOGE("%s: rbuf OsalMemCalloc error\n", __func__); + OsalMemFree(test->wbuf); + return HDF_ERR_MALLOC_FAIL; + } + return HDF_SUCCESS; +} + +static int32_t SpiTestInit(struct HdfDeviceObject *device) +{ + struct SpiTest *test = NULL; + + if (device == NULL || device->service == NULL || device->property == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + test = (struct SpiTest *)device->service; + SpiTestInitFromHcs(test, device->property); + HDF_LOGE("%s: success", __func__); + test->TestEntry = SpiTestEntry; + return HDF_SUCCESS; +} + +static void SpiTestRelease(struct HdfDeviceObject *device) +{ + struct SpiTest *test = NULL; + + if (device == NULL) { + return; + } + test = (struct SpiTest *)device->service; + if (test == NULL) { + return; + } + if (test->wbuf != NULL) { + OsalMemFree(test->wbuf); + } + if (test->rbuf != NULL) { + OsalMemFree(test->rbuf); + } +} + +struct HdfDriverEntry g_spiTestEntry = { + .moduleVersion = 1, + .Bind = SpiTestBind, + .Init = SpiTestInit, + .Release = SpiTestRelease, + .moduleName = "PLATFORM_SPI_TEST", +}; +HDF_INIT(g_spiTestEntry); diff --git a/test/unittest/platform/common/spi_test.h b/test/unittest/platform/common/spi_test.h new file mode 100644 index 00000000..31d474a3 --- /dev/null +++ b/test/unittest/platform/common/spi_test.h @@ -0,0 +1,42 @@ +/* + * 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 SPI_TEST_H +#define SPI_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" + +enum SpiTestCmd { + SPI_SET_CFG_TEST = 0, + SPI_TRANSFER_TEST, + SPI_WRITE_TEST, + SPI_READ_TEST, + SPI_RELIABILITY_TEST, + SPI_PERFORMANCE_TEST, + SPI_TEST_ALL, +}; + +struct SpiTest { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*TestEntry)(struct SpiTest *test, int32_t cmd); + uint32_t bus; + uint32_t cs; + uint32_t len; + uint8_t *wbuf; + uint8_t *rbuf; + DevHandle handle; +}; + +static inline struct SpiTest *GetSpiTest(void) +{ + return (struct SpiTest *)DevSvcManagerClntGetService("SPI_TEST"); +} + +#endif /* SPI_TEST_H */ diff --git a/test/unittest/platform/common/uart_test.c b/test/unittest/platform/common/uart_test.c new file mode 100644 index 00000000..8808232f --- /dev/null +++ b/test/unittest/platform/common/uart_test.c @@ -0,0 +1,330 @@ +/* + * 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_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "uart_if.h" +#include "uart_test.h" + +#define HDF_LOG_TAG uart_test_c +struct UartTestFunc { + enum UartTestCmd type; + int32_t (*Func)(struct UartTest *test); +}; + +#define BITS_PER_WORD 10 +#define MAX_SPEED_HZ 10000000 +static int32_t UartWriteTest(struct UartTest *test) +{ + if (UartWrite(test->handle, test->wbuf, test->len) != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartReadTest(struct UartTest *test) +{ + if (UartRead(test->handle, test->rbuf, test->len) != 0) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +#define BAUD_921600 921600 +static int32_t UartSetBaudTest(struct UartTest *test) +{ + if (UartSetBaud(test->handle, BAUD_921600) != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartGetBaudTest(struct UartTest *test) +{ + uint32_t baud; + + if (UartGetBaud(test->handle, &baud) != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: baud %d", __func__, baud); + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartSetAttributeTest(struct UartTest *test) +{ + struct UartAttribute attribute; + + attribute.dataBits = UART_ATTR_DATABIT_7; + attribute.parity = UART_ATTR_PARITY_NONE; + attribute.stopBits = UART_ATTR_STOPBIT_1; + attribute.rts = UART_ATTR_RTS_DIS; + attribute.cts = UART_ATTR_CTS_DIS; + attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; + attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; + if (UartSetAttribute(test->handle, &attribute) != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartGetAttributeTest(struct UartTest *test) +{ + struct UartAttribute attribute; + + if (UartGetAttribute(test->handle, &attribute) != HDF_SUCCESS) { + 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("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartSetTransModeTest(struct UartTest *test) +{ + if (UartSetTransMode(test->handle, UART_MODE_RD_NONBLOCK) != HDF_SUCCESS) { + HDF_LOGE("%s: error", __func__); + return HDF_FAILURE; + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartReliabilityTest(struct UartTest *test) +{ + uint32_t baud; + struct UartAttribute attribute = {0}; + + (void)UartSetTransMode(test->handle, UART_MODE_RD_NONBLOCK); + (void)UartSetTransMode(test->handle, -1); + (void)UartWrite(test->handle, test->wbuf, test->len); + (void)UartWrite(test->handle, NULL, -1); + (void)UartRead(test->handle, test->rbuf, test->len); + (void)UartRead(test->handle, NULL, -1); + (void)UartSetBaud(test->handle, BAUD_921600); + (void)UartSetBaud(test->handle, -1); + (void)UartGetBaud(test->handle, &baud); + (void)UartGetBaud(test->handle, NULL); + (void)UartSetAttribute(test->handle, &attribute); + (void)UartSetAttribute(test->handle, NULL); + (void)UartGetAttribute(test->handle, &attribute); + (void)UartGetAttribute(test->handle, NULL); + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartTestAll(struct UartTest *test) +{ + int32_t total = 0; + int32_t error = 0; + + if (UartSetTransModeTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartWriteTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartReadTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartSetBaudTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartGetBaudTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartSetAttributeTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartGetAttributeTest(test) != HDF_SUCCESS) { + error++; + } + total++; + if (UartReliabilityTest(test) != HDF_SUCCESS) { + error++; + } + total++; + HDF_LOGE("%s: Uart Test Total %d Error %d", __func__, total, error); + return HDF_SUCCESS; +} + +struct UartTestFunc g_uartTestFunc[] = { + { UAER_WRITE_TEST, UartWriteTest }, + { UART_READ_TEST, UartReadTest }, + { UART_SET_BAUD_TEST, UartSetBaudTest }, + { UART_GET_BAUD_TEST, UartGetBaudTest }, + { UART_SET_ATTRIBUTE_TEST, UartSetAttributeTest }, + { UART_GET_ATTRIBUTE_TEST, UartGetAttributeTest }, + { UART_SET_TRANSMODE_TEST, UartSetTransModeTest }, + { UART_RELIABILITY_TEST, UartReliabilityTest }, + { UART_PERFORMANCE_TEST, NULL }, + { UART_TEST_ALL, UartTestAll }, +}; + +static int32_t UartTestEntry(struct UartTest *test, int32_t cmd) +{ + int32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + + if (test == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + test->handle = UartOpen(test->port); + if (test->handle == NULL) { + HDF_LOGE("%s: spi test get handle fail", __func__); + return HDF_FAILURE; + } + for (i = 0; i < sizeof(g_uartTestFunc) / sizeof(g_uartTestFunc[0]); i++) { + if (cmd == g_uartTestFunc[i].type && g_uartTestFunc[i].Func != NULL) { + ret = g_uartTestFunc[i].Func(test); + HDF_LOGE("%s: cmd %d ret %d", __func__, cmd, ret); + break; + } + } + UartClose(test->handle); + return ret; +} + +static int32_t UartTestBind(struct HdfDeviceObject *device) +{ + static struct UartTest test; + + if (device != NULL) { + device->service = &test.service; + } else { + HDF_LOGE("%s: device is NULL", __func__); + } + HDF_LOGE("%s: success", __func__); + return HDF_SUCCESS; +} + +static int32_t UartTestInitFromHcs(struct UartTest *test, const struct DeviceResourceNode *node) +{ + int32_t ret; + int32_t i; + uint32_t *tmp = NULL; + struct DeviceResourceIface *face = NULL; + + face = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (face == NULL) { + HDF_LOGE("%s: face is null", __func__); + return HDF_FAILURE; + } + if (face->GetUint32 == NULL || face->GetUint32Array == NULL) { + HDF_LOGE("%s: GetUint32 or GetUint32Array not support", __func__); + return HDF_ERR_NOT_SUPPORT; + } + ret = face->GetUint32(node, "port", &test->port, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read port fail", __func__); + return HDF_FAILURE; + } + ret = face->GetUint32(node, "len", &test->len, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read len fail", __func__); + return HDF_FAILURE; + } + test->wbuf = (uint8_t *)OsalMemCalloc(test->len); + if (test->wbuf == NULL) { + HDF_LOGE("%s: wbuf OsalMemCalloc error\n", __func__); + return HDF_ERR_MALLOC_FAIL; + } + tmp = (uint32_t *)OsalMemCalloc(test->len * sizeof(uint32_t)); + if (tmp == NULL) { + HDF_LOGE("%s: tmp OsalMemCalloc error\n", __func__); + OsalMemFree(test->wbuf); + return HDF_ERR_MALLOC_FAIL; + } + ret = face->GetUint32Array(node, "wbuf", tmp, test->len, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read wbuf fail", __func__); + OsalMemFree(test->wbuf); + OsalMemFree(tmp); + return HDF_FAILURE; + } + for (i = 0; i < test->len; i++) { + test->wbuf[i] = tmp[i]; + } + OsalMemFree(tmp); + test->rbuf = (uint8_t *)OsalMemCalloc(test->len); + if (test->rbuf == NULL) { + HDF_LOGE("%s: rbuf OsalMemCalloc error\n", __func__); + OsalMemFree(test->wbuf); + return HDF_ERR_MALLOC_FAIL; + } + return HDF_SUCCESS; +} + +static int32_t UartTestInit(struct HdfDeviceObject *device) +{ + struct UartTest *test = NULL; + + if (device == NULL || device->service == NULL || device->property == NULL) { + HDF_LOGE("%s: invalid parameter", __func__); + return HDF_ERR_INVALID_PARAM; + } + test = (struct UartTest *)device->service; + UartTestInitFromHcs(test, device->property); + HDF_LOGE("%s: success", __func__); + test->TestEntry = UartTestEntry; + return HDF_SUCCESS; +} + +static void UartTestRelease(struct HdfDeviceObject *device) +{ + struct UartTest *test = NULL; + + if (device == NULL) { + return; + } + test = (struct UartTest *)device->service; + if (test == NULL) { + return; + } + if (test->wbuf != NULL) { + OsalMemFree(test->wbuf); + } + if (test->rbuf != NULL) { + OsalMemFree(test->rbuf); + } +} + +struct HdfDriverEntry g_uartTestEntry = { + .moduleVersion = 1, + .Bind = UartTestBind, + .Init = UartTestInit, + .Release = UartTestRelease, + .moduleName = "PLATFORM_UART_TEST", +}; +HDF_INIT(g_uartTestEntry); diff --git a/test/unittest/platform/common/uart_test.h b/test/unittest/platform/common/uart_test.h new file mode 100644 index 00000000..d0bf9bf1 --- /dev/null +++ b/test/unittest/platform/common/uart_test.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 UART_TEST_H +#define UART_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" + +enum UartTestCmd { + UAER_WRITE_TEST = 0, + UART_READ_TEST, + UART_SET_BAUD_TEST, + UART_GET_BAUD_TEST, + UART_SET_ATTRIBUTE_TEST, + UART_GET_ATTRIBUTE_TEST, + UART_SET_TRANSMODE_TEST, + UART_RELIABILITY_TEST, + UART_PERFORMANCE_TEST, + UART_TEST_ALL, +}; + +struct UartTest { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*TestEntry)(struct UartTest *test, int32_t cmd); + uint32_t port; + uint32_t len; + uint8_t *wbuf; + uint8_t *rbuf; + DevHandle handle; +}; + +static inline struct UartTest *GetUartTest(void) +{ + return (struct UartTest *)DevSvcManagerClntGetService("UART_TEST"); +} + +#endif /* UART_TEST_H */ diff --git a/test/unittest/platform/common/watchdog_test.c b/test/unittest/platform/common/watchdog_test.c new file mode 100644 index 00000000..7d76b86b --- /dev/null +++ b/test/unittest/platform/common/watchdog_test.c @@ -0,0 +1,281 @@ +/* + * 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 "watchdog_test.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_time.h" +#include "watchdog_if.h" + +#define HDF_LOG_TAG watchdog_test + +#define WATCHDOG_TEST_CASE_NUM 5 +#define WATCHDOG_TEST_TIMEOUT 2 +#define WATCHDOG_TEST_FEED_TIME 6 + +static int32_t WatchdogTestSetUp(struct WatchdogTester *tester) +{ + if (tester == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + if (tester->handle == NULL) { + tester->handle = WatchdogOpen(0); + } + if (tester->handle == NULL) { + return HDF_ERR_DEVICE_BUSY; + } + tester->total = WATCHDOG_TEST_CASE_NUM; + tester->fails = 0; + + return HDF_SUCCESS; +} + +static void WatchdogTestTearDown(struct WatchdogTester *tester) +{ + int ret; + + if (tester == NULL || tester->handle == NULL) { + return; + } + + ret = WatchdogStop(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: stop fail! ret:%d", __func__, ret); + return; + } + + WatchdogClose(tester->handle); + tester->handle = NULL; +} + +static int32_t TestCaseWatchdogSetGetTimeout(struct WatchdogTester *tester) +{ + int32_t ret; + uint32_t timeoutGet = 0; + const uint32_t timeoutSet = WATCHDOG_TEST_TIMEOUT; + + ret = WatchdogSetTimeout(tester->handle, timeoutSet); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set timeout fail! ret:%d", __func__, ret); + return ret; + } + ret = WatchdogGetTimeout(tester->handle, &timeoutGet); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get timeout fail! ret:%d", __func__, ret); + return ret; + } + if (timeoutSet != timeoutGet) { + HDF_LOGE("%s: set:%u, but get:%u", __func__, timeoutSet, timeoutGet); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t TestCaseWatchdogStartStop(struct WatchdogTester *tester) +{ + int32_t ret; + int32_t status; + + ret = WatchdogStart(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: satrt fail! ret:%d", __func__, ret); + return ret; + } + status = WATCHDOG_STOP; + ret = WatchdogGetStatus(tester->handle, &status); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get status fail! ret:%d", __func__, ret); + return ret; + } + if (status != WATCHDOG_START) { + HDF_LOGE("%s: status is:%d after start", __func__, status); + return HDF_FAILURE; + } + + ret = WatchdogStop(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: stop fail! ret:%d", __func__, ret); + return ret; + } + status = WATCHDOG_START; + ret = WatchdogGetStatus(tester->handle, &status); + if (status != WATCHDOG_STOP) { + HDF_LOGE("%s: status is:%d after stop", __func__, status); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +static int32_t TestCaseWatchdogFeed(struct WatchdogTester *tester) +{ + int32_t ret; + int32_t i; + + ret = WatchdogStart(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: satrt fail! ret:%d", __func__, ret); + return ret; + } + + for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) { + HDF_LOGE("%s: feeding watchdog %d times... ", __func__, i); + ret = WatchdogFeed(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: feed dog fail! ret:%d", __func__, ret); + return ret; + } + OsalSleep(1); + } + + HDF_LOGE("%s: no reset ... feeding test OK!!!", __func__); + return HDF_SUCCESS; +} + +static int32_t TestCaseWatchdogBark(struct WatchdogTester *tester) +{ +#ifdef WATCHDOG_TEST_BARK_RESET + int32_t ret; + int32_t i; + + ret = WatchdogStart(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: satrt fail! ret:%d", __func__, ret); + return ret; + } + + for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) { + HDF_LOGE("%s: watiting dog buck %d times... ", __func__, i); + OsalSleep(1); + } + + HDF_LOGE("%s: dog has't buck!!! ", __func__, i); + return HDF_FAILURE; +#else + (void)tester; + return HDF_SUCCESS; +#endif +} + +static int32_t TestCaseWatchdogReliability(struct WatchdogTester *tester) +{ + int32_t status; + uint32_t timeout; + + HDF_LOGE("%s: test dfr for WatchdogGetStatus ...", __func__); + /* invalid device handle */ + (void)WatchdogGetStatus(NULL, &status); + /* invalid status pointer */ + (void)WatchdogGetStatus(tester->handle, NULL); + + HDF_LOGE("%s: test dfr for WatchdogStart&Stop ...", __func__); + /* invalid device handle */ + (void)WatchdogStart(NULL); + /* invalid device handle */ + (void)WatchdogStop(NULL); + + HDF_LOGE("%s: test dfr for WatchdogSet&GetTimeout ...", __func__); + /* invalid device handle */ + (void)WatchdogSetTimeout(NULL, WATCHDOG_TEST_TIMEOUT); + /* invalid device handle */ + (void)WatchdogGetTimeout(NULL, &timeout); + /* invalid timout pointer */ + (void)WatchdogGetTimeout(tester->handle, NULL); + + HDF_LOGE("%s: test dfr for WatchdogFeed ...", __func__); + /* invalid device handle */ + (void)WatchdogFeed(NULL); + + return HDF_SUCCESS; +} + +static int32_t WatchdogTestByCmd(struct WatchdogTester *tester, int32_t cmd) +{ + int32_t i; + + if (cmd == WATCHDOG_TEST_SET_GET_TIMEOUT) { + return TestCaseWatchdogSetGetTimeout(tester); + } else if (cmd == WATCHDOG_TEST_START_STOP) { + return TestCaseWatchdogStartStop(tester); + } else if (cmd == WATCHDOG_TEST_FEED) { + return TestCaseWatchdogFeed(tester); + } else if (cmd == WATCHDOG_TEST_BARK) { + return TestCaseWatchdogBark(tester); + } else if (cmd == WATCHDOG_TEST_RELIABILITY) { + return TestCaseWatchdogReliability(tester); + } + + for (i = 0; i < WATCHDOG_TEST_MAX; i++) { + if (WatchdogTestByCmd(tester, i) != HDF_SUCCESS) { + tester->fails++; + } + } + HDF_LOGE("%s: **********PASS:%u FAIL:%u**************\n\n", + __func__, tester->total - tester->fails, tester->fails); + return (tester->fails > 0) ? HDF_FAILURE : HDF_SUCCESS; +} + +static int32_t WatchdogDoTest(struct WatchdogTester *tester, int32_t cmd) +{ + int32_t ret; + + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL!", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + ret = WatchdogTestSetUp(tester); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: setup fail!", __func__); + return ret; + } + + ret = WatchdogTestByCmd(tester, cmd); + + WatchdogTestTearDown(tester); + return ret; +} + +static int32_t WatchdogTestBind(struct HdfDeviceObject *device) +{ + static struct WatchdogTester tester; + + if (device == NULL) { + HDF_LOGE("%s: device is null!", __func__); + return HDF_ERR_IO; + } + + tester.doTest = WatchdogDoTest; + device->service = &tester.service; + return HDF_SUCCESS; +} + +static int32_t WatchdogTestInit(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static void WatchdogTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + return; +} + +struct HdfDriverEntry g_watchdogTestEntry = { + .moduleVersion = 1, + .Bind = WatchdogTestBind, + .Init = WatchdogTestInit, + .Release = WatchdogTestRelease, + .moduleName = "PLATFORM_WATCHDOG_TEST", +}; +HDF_INIT(g_watchdogTestEntry); diff --git a/test/unittest/platform/common/watchdog_test.h b/test/unittest/platform/common/watchdog_test.h new file mode 100644 index 00000000..3fbb5d29 --- /dev/null +++ b/test/unittest/platform/common/watchdog_test.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 WATCHDOG_TEST_H +#define WATCHDOG_TEST_H + +#include "hdf_device_desc.h" +#include "hdf_platform.h" + +enum WatchdogTestCmd { + WATCHDOG_TEST_SET_GET_TIMEOUT = 0, + WATCHDOG_TEST_START_STOP = 1, + WATCHDOG_TEST_FEED = 2, + WATCHDOG_TEST_RELIABILITY = 3, + WATCHDOG_TEST_BARK = 4, + WATCHDOG_TEST_MAX = 5, +}; + +struct WatchdogTester { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + int32_t (*doTest)(struct WatchdogTester *tester, int32_t cmd); + uint16_t total; + uint16_t fails; + DevHandle handle; +}; + +static inline struct WatchdogTester *WatchdogTesterGet(void) +{ + return (struct WatchdogTester *)DevSvcManagerClntGetService("WATCHDOG_TEST"); +} + +#endif /* WATCHDOG_TEST_H */ diff --git a/test/unittest/platform/hdf_emmc_entry_test.c b/test/unittest/platform/hdf_emmc_entry_test.c new file mode 100644 index 00000000..e39a08cc --- /dev/null +++ b/test/unittest/platform/hdf_emmc_entry_test.c @@ -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. + */ + +#include "hdf_emmc_entry_test.h" +#include "emmc_if.h" +#include "emmc_test.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hdf_emmc_entry_test + +int32_t HdfEmmcUnitTestEntry(HdfTestMsg *msg) +{ + struct EmmcTester *tester = NULL; + + if (msg == NULL) { + HDF_LOGE("HdfEmmcUnitTestEntry: msg is NULL"); + return HDF_FAILURE; + } + tester = GetEmmcTester(); + if (tester == NULL || tester->TestEntry == NULL) { + HDF_LOGE("HdfEmmcUnitTestEntry: tester/TestEntry is NULL"); + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = tester->TestEntry(tester, msg->subCmd); + return msg->result; +} diff --git a/test/unittest/platform/hdf_emmc_entry_test.h b/test/unittest/platform/hdf_emmc_entry_test.h new file mode 100644 index 00000000..3e9d599b --- /dev/null +++ b/test/unittest/platform/hdf_emmc_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_EMMC_ENTRY_TEST_H +#define HDF_EMMC_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfEmmcUnitTestEntry(HdfTestMsg *msg); + +#endif // HDF_EMMC_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_gpio_entry_test.c b/test/unittest/platform/hdf_gpio_entry_test.c new file mode 100644 index 00000000..9cd7adbb --- /dev/null +++ b/test/unittest/platform/hdf_gpio_entry_test.c @@ -0,0 +1,33 @@ +/* + * 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_gpio_entry_test.h" +#include "gpio_if.h" +#include "gpio_test.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hdf_gpio_entry_test + +int32_t HdfGpioTestEntry(HdfTestMsg *msg) +{ + struct GpioTester *tester = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + + tester = GpioTesterGet(); + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL!\n", __func__); + return HDF_FAILURE; + } + + msg->result = tester->doTest(tester, msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/test/unittest/platform/hdf_gpio_entry_test.h b/test/unittest/platform/hdf_gpio_entry_test.h new file mode 100644 index 00000000..56bb6aeb --- /dev/null +++ b/test/unittest/platform/hdf_gpio_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_GPIO_ENTRY_TEST_H +#define HDF_GPIO_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfGpioTestEntry(HdfTestMsg *msg); + +#endif // HDF_GPIO_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_i2c_entry_test.c b/test/unittest/platform/hdf_i2c_entry_test.c new file mode 100644 index 00000000..b01481bd --- /dev/null +++ b/test/unittest/platform/hdf_i2c_entry_test.c @@ -0,0 +1,25 @@ +/* + * 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_i2c_entry_test.h" +#include "hdf_log.h" +#include "i2c_if.h" +#include "i2c_test.h" + +#define HDF_LOG_TAG hdf_i2c_entry_test + +int32_t HdfI2cTestEntry(HdfTestMsg *msg) +{ + if (msg == NULL) { + return HDF_FAILURE; + } + + msg->result = I2cTestExecute(msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/test/unittest/platform/hdf_i2c_entry_test.h b/test/unittest/platform/hdf_i2c_entry_test.h new file mode 100644 index 00000000..0b9f10cb --- /dev/null +++ b/test/unittest/platform/hdf_i2c_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_I2C_ENTRY_TEST_H +#define HDF_I2C_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfI2cTestEntry(HdfTestMsg *msg); + +#endif // HDF_I2C_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_mipi_dsi_entry_test.c b/test/unittest/platform/hdf_mipi_dsi_entry_test.c new file mode 100644 index 00000000..aab32cbf --- /dev/null +++ b/test/unittest/platform/hdf_mipi_dsi_entry_test.c @@ -0,0 +1,33 @@ +/* + * 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_mipi_dsi_entry_test.h" +#include "hdf_log.h" +#include "mipi_dsi_if.h" +#include "mipi_dsi_test.h" + +#define HDF_LOG_TAG hdf_mipi_dsi_entry_test + +int32_t HdfMipiDsiEntry(HdfTestMsg *msg) +{ + struct MipiDsiTest *test = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + + test = MipiDsiTestServiceGet(); + if (test == NULL) { + HDF_LOGE("%s: get servie fail!\n", __func__); + return HDF_FAILURE; + } + + msg->result = test->doTest(test, msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/test/unittest/platform/hdf_mipi_dsi_entry_test.h b/test/unittest/platform/hdf_mipi_dsi_entry_test.h new file mode 100644 index 00000000..c25d16af --- /dev/null +++ b/test/unittest/platform/hdf_mipi_dsi_entry_test.h @@ -0,0 +1,15 @@ +/* + * 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_MIPI_DSI_ENTRY_TEST_H +#define HDF_MIPI_DSI_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfMipiDsiEntry(HdfTestMsg *msg); +#endif // HDF_MIPI_DSI_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_pwm_entry_test.c b/test/unittest/platform/hdf_pwm_entry_test.c new file mode 100644 index 00000000..bb274ea2 --- /dev/null +++ b/test/unittest/platform/hdf_pwm_entry_test.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 "hdf_pwm_entry_test.h" +#include "hdf_log.h" +#include "pwm_if.h" +#include "pwm_test.h" + +#define HDF_LOG_TAG hdf_pwm_entry_test + +int32_t HdfPwmUnitTestEntry(HdfTestMsg *msg) +{ + struct PwmTest *test = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + test = GetPwmTest(); + if (test == NULL || test->TestEntry == NULL) { + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = test->TestEntry(test, msg->subCmd); + return msg->result; +} diff --git a/test/unittest/platform/hdf_pwm_entry_test.h b/test/unittest/platform/hdf_pwm_entry_test.h new file mode 100644 index 00000000..4a4d1f72 --- /dev/null +++ b/test/unittest/platform/hdf_pwm_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_PWM_ENTRY_TEST_H +#define HDF_PWM_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfPwmUnitTestEntry(HdfTestMsg *msg); + +#endif /* HDF_PWM_ENTRY_TEST_H */ diff --git a/test/unittest/platform/hdf_rtc_entry_test.c b/test/unittest/platform/hdf_rtc_entry_test.c new file mode 100644 index 00000000..1285bf9c --- /dev/null +++ b/test/unittest/platform/hdf_rtc_entry_test.c @@ -0,0 +1,634 @@ +/* + * 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_rtc_entry_test.h" +#include "hdf_log.h" +#include "osal_time.h" +#include "rtc_base.h" +#include "rtc_if.h" + +#define HDF_LOG_TAG hdf_rtc_entry_test + +#define RTC_TEST_TIME 60 +#define RTC_TEST_TIME_MAX_YEAR 2222 +#define RTC_TEST_TIME_YEAR 2020 +#define RTC_TEST_TIME_MONTH 8 +#define RTC_TEST_TIME_DAY 8 +#define RTC_TEST_TIME_HOUR 8 +#define RTC_TEST_TIME_MIN 8 +#define RTC_TEST_TIME_SECOND 8 +#define RTC_TEST_FREQ 32768 +#define RTC_TEST_USER_VALUE 0x8 +#define RTC_TEST_USER_MAX_INDEX 8 +#define RTC_TEST_WAIT_TIME_S 3 +#define RTC_TEST_WR_WAIT_MS 30 + +DevHandle g_rtcHandle = NULL; + +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) +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"); + g_rtcIrqCallback = HDF_SUCCESS; + } else { + g_rtcIrqCallback = HDF_FAILURE; + } + return 0; +} +#endif + +static int32_t RtcTestInit(void) +{ + g_rtcHandle = RtcOpen(); + if (g_rtcHandle == NULL) { + HDF_LOGE("RtcTestInit: g_rtcHandle NULL"); + return -1; + } + return 0; +} + +static int32_t RtcTestUniInit(void) +{ + if (g_rtcHandle != NULL) { + RtcClose(g_rtcHandle); + g_rtcHandle = NULL; + } + + return 0; +} + +static int32_t IsSameRtcTestTime(const struct RtcTime *readTime, const struct RtcTime *writeTime) +{ + if ((readTime->year != writeTime->year) || (readTime->month != writeTime->month) || + (readTime->day != writeTime->day) || (readTime->weekday != writeTime->weekday) || + (readTime->hour != writeTime->hour) || (readTime->minute != writeTime->minute) || + (readTime->second < writeTime->second)) { + return -1; + } + return 0; +} + +static int32_t RtcReadWriteTimeTest(struct RtcTime *writeTime) +{ + int32_t ret; + struct RtcTime readTime = {0}; + + if (g_rtcHandle == NULL) { + HDF_LOGE("RtcReadWriteTimeTest g_rtcHandle null"); + return -1; + } + ret = RtcWriteTime(g_rtcHandle, writeTime); + if (ret != 0) { + HDF_LOGE("RtcReadWriteTimeTest write fail"); + return -1; + } + + OsalMSleep(RTC_TEST_WR_WAIT_MS); + ret = RtcReadTime(g_rtcHandle, &readTime); + if (ret != 0) { + HDF_LOGE("RtcReadWriteTimeTest read fail"); + return -1; + } + + if (IsSameRtcTestTime(&readTime, writeTime) != 0) { + HDF_LOGE("RtcReadWriteTimeTest: different time"); + return -1; + } + return 0; +} + +static int32_t RtcReadWriteAlarmTimeTest(struct RtcTime *writeTime) +{ + int32_t ret; + struct RtcTime readTime = {0}; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcWriteAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, writeTime); + if (ret != 0) { + HDF_LOGE("RtcReadWriteAlarmTimeTest write fail"); + 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"); + return -1; + } + + if (IsSameRtcTestTime(&readTime, writeTime) != 0) { + return -1; + } + return 0; +} + +static int32_t RtcReadWriteTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + /* 2020-08-08 Saturday 09:08:08 .000 */ + tm.year = RTC_TEST_TIME_YEAR; + tm.month = RTC_TEST_TIME_MONTH; + tm.day = RTC_TEST_TIME_DAY; + tm.hour = RTC_TEST_TIME_HOUR; + tm.minute = RTC_TEST_TIME_MIN; + tm.second = RTC_TEST_TIME_SECOND; + tm.millisecond = 0; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + + ret = RtcReadWriteTimeTest(&tm); + if (ret != 0) { + HDF_LOGE("RtcReadWriteTime fail"); + return -1; + } + + return 0; +} + +static int32_t RtcReadWriteMaxTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + tm.year = RTC_TEST_TIME_MAX_YEAR; + tm.month = RTC_MAX_MONTH + 1; + tm.day = RTC_GREAT_MONTH_DAY + 1; + tm.hour = RTC_DAY_HOURS; + tm.minute = RTC_MAX_MINUTE; + tm.second = RTC_MAX_SECOND; + tm.millisecond = RTC_MAX_MS; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + ret = RtcReadWriteTimeTest(&tm); + if (ret == 0) { + HDF_LOGE("RtcReadWriteMaxTime fail"); + return -1; + } + + return 0; +} + +static int32_t RtcReadWriteMinTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + tm.year = RTC_BEGIN_YEAR - 1; + tm.month = 0; + tm.day = 0; + tm.hour = 0; + tm.minute = 0; + tm.second = 0; + tm.millisecond = 0; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + ret = RtcReadWriteTimeTest(&tm); + if (ret == 0) { + HDF_LOGE("RtcReadWriteMinTime fail"); + return -1; + } + + return 0; +} + +static int32_t RtcReadWriteAlarmTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + /* 2020-08-08 Saturday 09:08:08 .000 */ + tm.year = RTC_TEST_TIME_YEAR; + tm.month = RTC_TEST_TIME_MONTH; + tm.day = RTC_TEST_TIME_DAY; + tm.hour = RTC_TEST_TIME_HOUR + RTC_UNIT_DIFF; + tm.minute = RTC_TEST_TIME_MIN; + tm.second = RTC_TEST_TIME_SECOND; + tm.millisecond = 0; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + ret = RtcReadWriteAlarmTimeTest(&tm); + if (ret != 0) { + HDF_LOGE("RtcReadWriteAlarmTime read fail"); + return -1; + } + + return 0; +} + +static int32_t RtcReadWriteMaxAlarmTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + tm.year = RTC_TEST_TIME_MAX_YEAR; + tm.month = RTC_MAX_MONTH + 1; + tm.day = RTC_GREAT_MONTH_DAY + 1; + tm.hour = RTC_DAY_HOURS; + tm.minute = RTC_MAX_MINUTE; + tm.second = RTC_MAX_SECOND; + tm.millisecond = RTC_MAX_MS; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + ret = RtcReadWriteAlarmTimeTest(&tm); + if (ret == 0) { + HDF_LOGE("RtcReadWriteMaxAlarmTime read fail"); + return -1; + } + + return 0; +} + +static int32_t RtcReadWriteMinAlarmTime(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime time; + + time.year = RTC_BEGIN_YEAR - 1; + time.month = 0; + time.day = 0; + time.hour = 0; + time.minute = 0; + time.second = 0; + time.millisecond = 0; + weekday = RtcGetWeekDay(&time); + time.weekday = weekday; + ret = RtcReadWriteAlarmTimeTest(&time); + if (ret == 0) { + HDF_LOGE("RtcReadWriteMinAlarmTime read fail"); + return -1; + } + + return 0; +} + +#if defined(CONFIG_DRIVERS_HDF_PLATFORM_RTC) +static int32_t RtcAlarmEnable(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime tm; + + /* 2020-08-08 Saturday 08:09:08 .000 */ + tm.year = RTC_TEST_TIME_YEAR; + tm.month = RTC_TEST_TIME_MONTH; + tm.day = RTC_TEST_TIME_DAY; + tm.hour = RTC_TEST_TIME_HOUR; + tm.minute = RTC_TEST_TIME_MIN + RTC_UNIT_DIFF; + tm.second = RTC_TEST_TIME_SECOND; + tm.millisecond = 0; + weekday = RtcGetWeekDay(&tm); + tm.weekday = weekday; + ret = RtcReadWriteAlarmTimeTest(&tm); + if (ret != 0) { + HDF_LOGE("RtcReadWriteAlarmTime read fail"); + return -1; + } + ret = RtcAlarmInterruptEnable(g_rtcHandle, RTC_ALARM_INDEX_A, 1); + if (ret != 0) { + HDF_LOGE("RtcAlarmInterruptEnable fail"); + return -1; + } + return 0; +} +#endif + +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) +static int32_t RtcAlarmIrqAttachConfig(void) +{ + int32_t ret; + const uint32_t freq = RTC_TEST_FREQ; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, RtcAlarmACallback); + if (ret != 0) { + HDF_LOGE("RtcRegisterAlarmCallback fail"); + return -1; + } + ret = RtcSetFreq(g_rtcHandle, freq); + if (ret != 0) { + HDF_LOGE("RtcSetFreq fail"); + return -1; + } + ret = RtcAlarmInterruptEnable(g_rtcHandle, RTC_ALARM_INDEX_A, 1); + if (ret != 0) { + HDF_LOGE("RtcAlarmInterruptEnable fail"); + return -1; + } + return 0; +} + +static int32_t RtcAlarmIrq(void) +{ + int32_t ret; + uint8_t weekday; + struct RtcTime time; + + if (g_rtcHandle == NULL) { + return -1; + } + + /* set time 2020-08-08 Saturday 08:08:08 .000 */ + time.year = RTC_TEST_TIME_YEAR; + time.month = RTC_TEST_TIME_MONTH; + time.day = RTC_TEST_TIME_DAY; + time.hour = RTC_TEST_TIME_HOUR; + time.minute = RTC_TEST_TIME_MIN; + time.second = RTC_TEST_TIME_SECOND; + time.millisecond = 0; + weekday = RtcGetWeekDay(&time); + time.weekday = weekday; + ret = RtcAlarmIrqAttachConfig(); + if (ret != 0) { + HDF_LOGE("RtcWriteTime fail"); + return -1; + } + ret = RtcWriteTime(g_rtcHandle, &time); + if (ret != 0) { + HDF_LOGE("RtcWriteTime fail"); + 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"); + return -1; + } + OsalSleep(RTC_TEST_WAIT_TIME_S); + if (g_rtcIrqCallback == HDF_FAILURE) { + HDF_LOGE("RtcWriteAlarm fail"); + return -1; + } + g_rtcIrqCallback = HDF_FAILURE; + return 0; +} + +static int32_t RtcRegisterCallback(void) +{ + int32_t ret; + + if (g_rtcHandle == NULL) { + return -1; + } + ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, RtcAlarmACallback); + if (ret != 0) { + HDF_LOGE("RtcRegisterCallback fail"); + return -1; + } + return 0; +} + +static int32_t RtcRegisterNullCallback(void) +{ + int32_t ret; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, NULL); + if (ret == 0) { + HDF_LOGE("RtcRegisterCallback fail"); + return -1; + } + return 0; +} + +static int32_t RtcSetNormalFreq(void) +{ + int32_t ret; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ); + if (ret != 0) { + HDF_LOGE("RtcSetNormalFreq fail"); + return -1; + } + return 0; +} + +static int32_t RtcSetMaxFreq(void) +{ + int32_t ret; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ * RTC_TIME_UNIT); + if (ret == 0) { + HDF_LOGE("RtcSetMaxFreq fail"); + return -1; + } + return 0; +} + +static int32_t RtcSetMinFreq(void) +{ + int32_t ret; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcSetFreq(g_rtcHandle, 0); + if (ret == 0) { + HDF_LOGE("RtcSetMinFreq fail"); + return -1; + } + ret = RtcSetFreq(g_rtcHandle, RTC_TEST_FREQ); + return ret; +} + +static int32_t RtcReadWriteUserReg(void) +{ + int32_t ret; + uint8_t value = RTC_TEST_USER_VALUE; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcWriteReg(g_rtcHandle, 0, value); + if (ret != 0) { + HDF_LOGE("RtcReadWriteUserReg write fail"); + return -1; + } + ret = RtcReadReg(g_rtcHandle, 0, &value); + if (ret != 0) { + HDF_LOGE("RtcSetMinFreq read fail"); + return -1; + } + if (value != RTC_TEST_USER_VALUE) { + return -1; + } + return 0; +} + +static int32_t RtcReadWriteMaxUserIndex(void) +{ + int32_t ret; + uint8_t value = RTC_TEST_USER_VALUE; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcWriteReg(g_rtcHandle, RTC_TEST_USER_MAX_INDEX, value); + if (ret == 0) { + HDF_LOGE("RtcReadWriteUserReg write fail"); + return -1; + } + ret = RtcReadReg(g_rtcHandle, RTC_TEST_USER_MAX_INDEX, &value); + if (ret == 0) { + HDF_LOGE("RtcSetMinFreq read fail"); + return -1; + } + return 0; +} + +static int32_t RtcTestSample(void) +{ + int32_t ret; + struct RtcTime tm; + const uint32_t freq = RTC_TEST_FREQ; + + if (g_rtcHandle == NULL) { + return -1; + } + + ret = RtcRegisterAlarmCallback(g_rtcHandle, RTC_ALARM_INDEX_A, RtcAlarmACallback); + if (ret != 0) { + return -1; + } + ret = RtcSetFreq(g_rtcHandle, freq); + if (ret != 0) { + return -1; + } + ret = RtcAlarmInterruptEnable(g_rtcHandle, RTC_ALARM_INDEX_A, 1); + if (ret != 0) { + return -1; + } + + tm.year = RTC_TEST_TIME_YEAR; + tm.month = RTC_JANUARY; + tm.day = RTC_TEST_TIME_DAY; + tm.hour = 0; + tm.minute = 0; + tm.second = 0; + tm.millisecond = 0; + + ret = RtcWriteTime(g_rtcHandle, &tm); + if (ret != 0) { + return -1; + } + + tm.second = RTC_TEST_TIME_SECOND; + ret = RtcWriteAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, &tm); + if (ret != 0) { + return -1; + } + OsalMSleep(RTC_TEST_WR_WAIT_MS); + ret = RtcReadAlarm(g_rtcHandle, RTC_ALARM_INDEX_A, &tm); + if (ret != 0) { + return -1; + } + + ret = RtcReadTime(g_rtcHandle, &tm); + if (ret != 0) { + return -1; + } + + return 0; +} +#endif + +static int32_t RtcReadWriteReliability(void) +{ + int i; + for (i = 0; i < RTC_TEST_TIME; i++) { + (void)RtcReadWriteTime(); + (void)RtcReadWriteAlarmTime(); +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) + (void)RtcSetNormalFreq(); +#endif + } + return 0; +} + +// add test case entry +HdfTestCaseList g_hdfRtcTestCaseList[] = { + { RTC_INIT, RtcTestInit }, + { RTC_UNINIT, RtcTestUniInit }, + { RTC_WR_TIME, RtcReadWriteTime }, + { RTC_WR_MAX_TIME, RtcReadWriteMaxTime }, + { RTC_WR_MIN_TIME, RtcReadWriteMinTime }, + { RTC_WR_ALARM_TIME, RtcReadWriteAlarmTime }, + { RTC_WR_ALARM_MAX_TIME, RtcReadWriteMaxAlarmTime }, + { RTC_WR_ALARM_MIN_TIME, RtcReadWriteMinAlarmTime }, +#if defined(CONFIG_DRIVERS_HDF_PLATFORM_RTC) + { RTC_ALARM_ENABLE, RtcAlarmEnable }, +#endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_RTC) + { RTC_ALARM_IRQ, RtcAlarmIrq }, + { RTC_REGISTER_CALLBACK, RtcRegisterCallback }, + { RTC_REGISTER_CALLBACK_NULL, RtcRegisterNullCallback }, + { RTC_WR_FREQ, RtcSetNormalFreq }, + { RTC_WR_MAX_FREQ, RtcSetMaxFreq }, + { RTC_WR_MIN_FREQ, RtcSetMinFreq }, + { RTC_WR_USER_REG, RtcReadWriteUserReg }, + { RTC_WR_USER_REG_MAX_INDEX, RtcReadWriteMaxUserIndex }, + { RTC_FUNCTION_TEST, RtcTestSample }, +#endif + { RTC_WR_RELIABILITY, RtcReadWriteReliability }, +}; + +int32_t HdfRtcEntry(HdfTestMsg *msg) +{ + int i; + + if (msg == NULL) { + return HDF_FAILURE; + } + + for (i = 0; i < sizeof(g_hdfRtcTestCaseList) / sizeof(g_hdfRtcTestCaseList[0]); ++i) { + if (msg->subCmd != g_hdfRtcTestCaseList[i].subCmd) { + continue; + } + if (g_hdfRtcTestCaseList[i].testFunc == NULL) { + msg->result = HDF_FAILURE; + continue; + } + msg->result = g_hdfRtcTestCaseList[i].testFunc(); + if (msg->result != HDF_SUCCESS) { + continue; + } + } + + return HDF_SUCCESS; +} diff --git a/test/unittest/platform/hdf_rtc_entry_test.h b/test/unittest/platform/hdf_rtc_entry_test.h new file mode 100644 index 00000000..98df0ef6 --- /dev/null +++ b/test/unittest/platform/hdf_rtc_entry_test.h @@ -0,0 +1,37 @@ +/* + * 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_RTC_ENTRY_TEST_H +#define HDF_RTC_ENTRY_TEST_H + +#include "hdf_main_test.h" + +typedef enum { + RTC_INIT, + RTC_UNINIT, + RTC_WR_TIME, + RTC_WR_MAX_TIME, + RTC_WR_MIN_TIME, + RTC_WR_ALARM_TIME, + RTC_WR_ALARM_MAX_TIME, + RTC_WR_ALARM_MIN_TIME, + RTC_ALARM_ENABLE, + RTC_ALARM_IRQ, + RTC_REGISTER_CALLBACK, + RTC_REGISTER_CALLBACK_NULL, + RTC_WR_FREQ, + RTC_WR_MAX_FREQ, + RTC_WR_MIN_FREQ, + RTC_WR_USER_REG, + RTC_WR_USER_REG_MAX_INDEX, + RTC_WR_RELIABILITY, + RTC_FUNCTION_TEST, +} HdfRtcTestCaseCmd; + +int32_t HdfRtcEntry(HdfTestMsg *msg); +#endif // HDF_RTC_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_sdio_entry_test.c b/test/unittest/platform/hdf_sdio_entry_test.c new file mode 100644 index 00000000..a46153bc --- /dev/null +++ b/test/unittest/platform/hdf_sdio_entry_test.c @@ -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. + */ + +#include "hdf_sdio_entry_test.h" +#include "hdf_log.h" +#include "sdio_if.h" +#include "sdio_test.h" + +#define HDF_LOG_TAG hdf_sdio_entry_test + +int32_t HdfSdioUnitTestEntry(HdfTestMsg *msg) +{ + struct SdioTester *tester = NULL; + + if (msg == NULL) { + HDF_LOGE("HdfSdioUnitTestEntry: msg is NULL"); + return HDF_FAILURE; + } + tester = GetSdioTest(); + if (tester == NULL || tester->TestEntry == NULL) { + HDF_LOGE("HdfSdioUnitTestEntry: tester/TestEntry is NULL"); + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = tester->TestEntry(tester, msg->subCmd); + return msg->result; +} diff --git a/test/unittest/platform/hdf_sdio_entry_test.h b/test/unittest/platform/hdf_sdio_entry_test.h new file mode 100644 index 00000000..5ab67c2e --- /dev/null +++ b/test/unittest/platform/hdf_sdio_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_SDIO_ENTRY_TEST_H +#define HDF_SDIO_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfSdioUnitTestEntry(HdfTestMsg *msg); + +#endif // HDF_SDIO_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/platform/hdf_spi_entry_test.c b/test/unittest/platform/hdf_spi_entry_test.c new file mode 100644 index 00000000..1887b5ef --- /dev/null +++ b/test/unittest/platform/hdf_spi_entry_test.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 "hdf_spi_entry_test.h" +#include "hdf_log.h" +#include "spi_if.h" +#include "spi_test.h" + +#define HDF_LOG_TAG hdf_spi_entry_test + +int32_t HdfSpiUnitTestEntry(HdfTestMsg *msg) +{ + struct SpiTest *test = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + test = GetSpiTest(); + if (test == NULL || test->TestEntry == NULL) { + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = test->TestEntry(test, msg->subCmd); + return msg->result; +} diff --git a/test/unittest/platform/hdf_spi_entry_test.h b/test/unittest/platform/hdf_spi_entry_test.h new file mode 100644 index 00000000..3d08df1b --- /dev/null +++ b/test/unittest/platform/hdf_spi_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_SPI_ENTRY_TEST_H +#define HDF_SPI_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfSpiUnitTestEntry(HdfTestMsg *msg); + +#endif /* HDF_SPI_ENTRY_TEST_H */ diff --git a/test/unittest/platform/hdf_uart_entry_test.c b/test/unittest/platform/hdf_uart_entry_test.c new file mode 100644 index 00000000..7103a5c0 --- /dev/null +++ b/test/unittest/platform/hdf_uart_entry_test.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 "hdf_uart_entry_test.h" +#include "hdf_log.h" +#include "uart_if.h" +#include "uart_test.h" + +#define HDF_LOG_TAG hdf_uart_entry_test + +int32_t HdfUartUnitTestEntry(HdfTestMsg *msg) +{ + struct UartTest *test = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + test = GetUartTest(); + if (test == NULL || test->TestEntry == NULL) { + msg->result = HDF_FAILURE; + return HDF_FAILURE; + } + msg->result = test->TestEntry(test, msg->subCmd); + return msg->result; +} diff --git a/test/unittest/platform/hdf_uart_entry_test.h b/test/unittest/platform/hdf_uart_entry_test.h new file mode 100644 index 00000000..ed0b83f5 --- /dev/null +++ b/test/unittest/platform/hdf_uart_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_UART_ENTRY_TEST_H +#define HDF_UART_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfUartUnitTestEntry(HdfTestMsg *msg); + +#endif /* HDF_UART_ENTRY_TEST_H */ \ No newline at end of file diff --git a/test/unittest/platform/hdf_watchdog_entry_test.c b/test/unittest/platform/hdf_watchdog_entry_test.c new file mode 100644 index 00000000..ad1e61c1 --- /dev/null +++ b/test/unittest/platform/hdf_watchdog_entry_test.c @@ -0,0 +1,33 @@ +/* + * 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_watchdog_entry_test.h" +#include "hdf_log.h" +#include "watchdog_if.h" +#include "watchdog_test.h" + +#define HDF_LOG_TAG hdf_watchdog_entry_test + +int32_t HdfWatchdogTestEntry(HdfTestMsg *msg) +{ + struct WatchdogTester *tester = NULL; + + if (msg == NULL) { + return HDF_FAILURE; + } + + tester = WatchdogTesterGet(); + if (tester == NULL) { + HDF_LOGE("%s: tester is NULL!\n", __func__); + return HDF_FAILURE; + } + + msg->result = tester->doTest(tester, msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/test/unittest/platform/hdf_watchdog_entry_test.h b/test/unittest/platform/hdf_watchdog_entry_test.h new file mode 100644 index 00000000..ac9f8c73 --- /dev/null +++ b/test/unittest/platform/hdf_watchdog_entry_test.h @@ -0,0 +1,16 @@ +/* + * 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_WATCHDOG_ENTRY_TEST_H +#define HDF_WATCHDOG_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfWatchdogTestEntry(HdfTestMsg *msg); + +#endif // HDF_WATCHDOG_ENTRY_TEST_H \ No newline at end of file diff --git a/test/unittest/sensor/hdf_sensor_test.c b/test/unittest/sensor/hdf_sensor_test.c new file mode 100644 index 00000000..45526d45 --- /dev/null +++ b/test/unittest/sensor/hdf_sensor_test.c @@ -0,0 +1,233 @@ +/* + * 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_base.h" +#include "hdf_device_desc.h" +#include "hdf_sensor_test.h" +#include "osal_math.h" +#include "osal_time.h" +#include "osal_timer.h" +#include "sensor_common.h" +#include "sensor_device_manager.h" +#include "sensor_driver_type.h" + +#define HDF_LOG_TAG hdf_sensor_test_c + +#define HDF_SENSOR_TEST_VALUE 1024000000 // 1g = 9.8m/s^2 +#define SENSOR_TEST_MAX_RANGE 8 +#define SENSOR_TEST_MAX_POWER 230 + +static struct SensorTestDrvData *GetSensorTestDrvData(void) +{ + static struct SensorTestDrvData sensorTestDrvData = { + .threadStatus = SENSOR_THREAD_NONE, + .initStatus = false, + .interval = SENSOR_TEST_SAMPLING_200_MS, + }; + + return &sensorTestDrvData; +} +static void SensorReadTestData(void) +{ + int32_t value = HDF_SENSOR_TEST_VALUE; + struct SensorReportEvent event; + OsalTimespec time; + + (void)memset_s(&event, sizeof(event), 0, sizeof(event)); + (void)memset_s(&time, sizeof(time), 0, sizeof(time)); + (void)OsalGetTime(&time); + + event.timestamp = time.sec * SENSOR_SECOND_CONVERT_NANOSECOND + time.usec * SENSOR_CONVERT_UNIT; // nanosecond + event.sensorId = SENSOR_TAG_NONE; + event.option = 0; + event.mode = SENSOR_WORK_MODE_REALTIME; + event.dataLen = sizeof(value); + event.data = (uint8_t *)&value; + ReportSensorEvent(&event); +} + +static int32_t SensorReadDataThreadTestWorker(void *arg) +{ + (void)arg; + int64_t interval; + CHECK_NULL_PTR_RETURN_VALUE(arg, HDF_ERR_INVALID_PARAM); + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + drvData->threadStatus = SENSOR_THREAD_START; + while (true) { + if (drvData->threadStatus == SENSOR_THREAD_RUNNING) { + SensorReadTestData(); + interval = OsalDivS64(drvData->interval, (SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT)); + OsalMSleep(interval); + } else if (drvData->threadStatus == SENSOR_THREAD_STOPPING) { + drvData->threadStatus = SENSOR_THREAD_STOPPED; + break; + } else { + OsalMSleep(SENSOR_TEST_SAMPLING_200_MS / SENSOR_CONVERT_UNIT / SENSOR_CONVERT_UNIT); + } + + if ((!drvData->initStatus) || (drvData->interval < 0) || drvData->threadStatus != SENSOR_THREAD_RUNNING) { + continue; + } + } + + HDF_LOGE("%s: Sensor test thread have exited", __func__); + return HDF_SUCCESS; +} + +static int32_t SensorInitTestConfig(void) +{ + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + if (drvData->threadStatus != SENSOR_THREAD_NONE && drvData->threadStatus != SENSOR_THREAD_DESTROY) { + HDF_LOGE("%s: Sensor test thread have created", __func__); + return HDF_SUCCESS; + } + + int32_t ret = CreateSensorThread(&drvData->thread, SensorReadDataThreadTestWorker, "hdf_sensor_test", drvData); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Sensor test create thread failed", __func__); + drvData->threadStatus = SENSOR_THREAD_NONE; + return HDF_FAILURE; + } + drvData->initStatus = true; + + return HDF_SUCCESS; +} + +static int32_t SensorGetInfoTest(struct SensorBasicInfo *info) +{ + (void)info; + + return HDF_SUCCESS; +} + +static int32_t SensorEnableTest(void) +{ + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + drvData->threadStatus = SENSOR_THREAD_RUNNING; + return HDF_SUCCESS; +} + +static int32_t SensorDisableTest(void) +{ + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + drvData->threadStatus = SENSOR_THREAD_STOPPED; + + return HDF_SUCCESS; +} + +static int32_t SensorSetBatchTest(int64_t samplingInterval, int64_t interval) +{ + (void)interval; + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + drvData->interval = samplingInterval; + return HDF_SUCCESS; +} + +static int32_t SensorSetModeTest(int32_t mode) +{ + return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE; +} + +static int32_t SensorSetOptionTest(uint32_t option) +{ + (void)option; + return HDF_SUCCESS; +} + +static int32_t SensorTestDispatch(struct HdfDeviceIoClient *client, + int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)client; + (void)cmd; + (void)data; + (void)reply; + + return HDF_SUCCESS; +} + +int32_t BindSensorDriverTest(struct HdfDeviceObject *device) +{ + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + static struct IDeviceIoService service = { + .object = {0}, + .Dispatch = SensorTestDispatch, + }; + device->service = &service; + return HDF_SUCCESS; +} + +int32_t InitSensorDriverTest(struct HdfDeviceObject *device) +{ + int32_t ret; + (void)device; + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + struct SensorDeviceInfo deviceInfo = { + .sensorInfo = { + .sensorName = "sensor_test", + .vendorName = "huawei", + .firmwareVersion = "1.0", + .hardwareVersion = "1.0", + .sensorTypeId = SENSOR_TAG_NONE, + .sensorId = SENSOR_TAG_NONE, + .maxRange = SENSOR_TEST_MAX_RANGE, + .accuracy = 1, + .power = SENSOR_TEST_MAX_POWER, + }, + .ops = { + .GetInfo = SensorGetInfoTest, + .Enable = SensorEnableTest, + .Disable = SensorDisableTest, + .SetBatch = SensorSetBatchTest, + .SetMode = SensorSetModeTest, + .SetOption = SensorSetOptionTest, + }, + }; + + ret = SensorInitTestConfig(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: sensor test config failed", __func__); + return HDF_FAILURE; + } + + ret = AddSensorDevice(&deviceInfo); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: sensor test register failed", __func__); + (void)DestroySensorThread(&drvData->thread, &drvData->threadStatus); + return HDF_FAILURE; + } + + HDF_LOGI("%s: init sensor test driver success", __func__); + return HDF_SUCCESS; +} + +void ReleaseSensorDriverTest(struct HdfDeviceObject *device) +{ + (void)device; + struct SensorTestDrvData *drvData = GetSensorTestDrvData(); + + (void)DestroySensorThread(&drvData->thread, &drvData->threadStatus); + (void)DeleteSensorDevice(SENSOR_TAG_NONE); +} + +struct HdfDriverEntry g_sensorTestDevEntry = { + .moduleVersion = 1, + .moduleName = "HDF_SENSOR_TEST_DRIVER", + .Bind = BindSensorDriverTest, + .Init = InitSensorDriverTest, + .Release = ReleaseSensorDriverTest, +}; + +HDF_INIT(g_sensorTestDevEntry); diff --git a/test/unittest/sensor/hdf_sensor_test.h b/test/unittest/sensor/hdf_sensor_test.h new file mode 100644 index 00000000..b4b598d8 --- /dev/null +++ b/test/unittest/sensor/hdf_sensor_test.h @@ -0,0 +1,23 @@ +/* + * 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_SENSOR_DRIVER_TEST_H +#define HDF_SENSOR_DRIVER_TEST_H + +#include "osal_thread.h" + +#define SENSOR_TEST_SAMPLING_200_MS 200000000 + +struct SensorTestDrvData { + uint8_t threadStatus; + uint8_t initStatus; + int64_t interval; + struct OsalThread thread; +}; + +#endif // HDF_SENSOR_DRIVER_TEST_H \ No newline at end of file diff --git a/test/unittest/wifi/hdf_wifi_test.c b/test/unittest/wifi/hdf_wifi_test.c new file mode 100644 index 00000000..30f5053b --- /dev/null +++ b/test/unittest/wifi/hdf_wifi_test.c @@ -0,0 +1,66 @@ +/* + * 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_wifi_test.h" +#include "flow_control_test.h" +#include "hdf_module_test.h" +#include "hdf_log.h" +#include "hdf_message_test.h" +#include "hdf_netbuf_test.h" +#include "net_device_test.h" +#include "osal.h" + +// add test case entry +static HdfTestCaseList g_hdfWiFiTestCaseList[] = { + {WIFI_NET_DEVICE_INIT, WiFiNetDviceTestInit}, + {WIFI_NET_DEVICE_DEINIT, WiFiNetDviceTestDeInit}, + {WIFI_NET_DEVICE_ADD, WiFiNetDviceTestAdd}, + {WIFI_NET_DEVICE_DELETE, WiFiNetDviceTestDelete}, + {WIFI_NET_DEVICE_GET, WiFiNetDviceTestGetDevice}, + {WIFI_NET_DEVICE_GET_COUNT, WiFiNetDviceTestGetCount}, + {WIFI_NET_DEVICE_GET_CAP, WiFiNetDviceTestGetCap}, + {WIFI_NET_DEVICE_SET_ADDR, WiFiNetDviceTestSetAddr}, + {WIFI_NET_DEVICE_SET_STATUS, WiFiNetDviceTestSetStatus}, + {WIFI_NET_DEVICE_SET_LINK_STATUS, WiFiNetDviceTestSetLinkStatus}, + {WIFI_NET_DEVICE_RX, WiFiNetDviceTestRx}, + {WIFI_NET_DEVICE_DHCPC, WifiNetDeviceDhcpClient}, + {WIFI_NET_DEVICE_DHCPS, WifiNetDeviceDhcpServer}, + {WIFI_NET_BUF_TEST, HdfNetBufTest}, + {WIFI_NET_BUF_QUEUE_TEST, HdfNetBufQueueTest}, + {WIFI_MODULE_CREATE_MODULE, WiFiModuleTestCreateModule}, + {WIFI_MODULE_DELETE_MODULE, WiFiModuleTestDeleteModule}, + {WIFI_MODULE_ADD_FEATURE, WiFiModuleTestAddFeature}, + {WIFI_MODULE_DELETE_FEATURE, WiFiModuleTestDelFeature}, + {WIFI_FLOW_CONTROL_INIT, WiFiFlowControlTestInit}, + {WIFI_FLOW_CONTROL_DEINIT, WiFiFlowControlTestDeinit}, + {WIFI_FLOW_CONTROL_GET_QUEUE_ID, WiFiFlowControlTestGetEapolQueueId}, + {WIFI_FLOW_CONTROL_SEND_DATA, WiFiFlowControlTestSendData}, + {WIFI_MESSAGE_QUEUE_001, MessageQueueTest001}, + {WIFI_MESSAGE_QUEUE_002, MessageQueueTest002}, + {WIFI_MESSAGE_QUEUE_003, MessageQueueTest003}, + {WIFI_MESSAGE_SINGLE_NODE_001, MessageSingleNodeTest001}, + {WIFI_MESSAGE_SINGLE_NODE_002, MessageSingleNodeTest002}, + {WIFI_MESSAGE_SINGLE_NODE_003, MessageSingleNodeTest003}, + {WIFI_MESSAGE_SINGLE_NODE_004, MessageSingleNodeTest004}, + {WIFI_MESSAGE_SINGLE_NODE_005, MessageSingleNodeTest005}, +}; + +int32_t HdfWifiEntry(HdfTestMsg *msg) +{ + int32_t result, i; + + 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); + msg->result = (result == 0) ? HDF_SUCCESS : HDF_FAILURE; + return HDF_SUCCESS; + } + } + return HDF_SUCCESS; +} \ No newline at end of file diff --git a/test/unittest/wifi/hdf_wifi_test.h b/test/unittest/wifi/hdf_wifi_test.h new file mode 100644 index 00000000..3cf27f56 --- /dev/null +++ b/test/unittest/wifi/hdf_wifi_test.h @@ -0,0 +1,62 @@ +/* + * 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_WIFI_TEST_H +#define HDF_WIFI_TEST_H + +#include "hdf_base.h" +#include "hdf_main_test.h" + +typedef enum { + /* flow control. */ + WIFI_FLOW_CONTROL_INIT, + WIFI_FLOW_CONTROL_DEINIT, + WIFI_FLOW_CONTROL_GET_QUEUE_ID, + WIFI_FLOW_CONTROL_SEND_DATA, + WIFI_FLOW_CONTROL_END = 50, + /* netdevice. */ + WIFI_NET_DEVICE_INIT = WIFI_FLOW_CONTROL_END, + WIFI_NET_DEVICE_DEINIT, + WIFI_NET_DEVICE_ADD, + WIFI_NET_DEVICE_DELETE, + WIFI_NET_DEVICE_GET, + WIFI_NET_DEVICE_GET_COUNT, + WIFI_NET_DEVICE_GET_CAP, + WIFI_NET_DEVICE_SET_ADDR, + WIFI_NET_DEVICE_SET_STATUS, + WIFI_NET_DEVICE_SET_LINK_STATUS, + WIFI_NET_DEVICE_RX, + WIFI_NET_DEVICE_DHCPC, + WIFI_NET_DEVICE_DHCPS, + WIFI_NET_DEVICE_END = 100, + /* netbuff */ + WIFI_NET_BUF_TEST = WIFI_NET_DEVICE_END, + WIFI_NET_BUF_QUEUE_TEST, + WIFI_NET_BUFF_END = 150, + /* module */ + WIFI_MODULE_CREATE_MODULE = WIFI_NET_BUFF_END, + WIFI_MODULE_DELETE_MODULE, + WIFI_MODULE_ADD_FEATURE, + WIFI_MODULE_DELETE_FEATURE, + WIFI_MODULE_END = 200, + + /* message */ + WIFI_MESSAGE_QUEUE_001 = WIFI_MODULE_END, + WIFI_MESSAGE_QUEUE_002, + WIFI_MESSAGE_QUEUE_003, + WIFI_MESSAGE_SINGLE_NODE_001, + WIFI_MESSAGE_SINGLE_NODE_002, + WIFI_MESSAGE_SINGLE_NODE_003, + WIFI_MESSAGE_SINGLE_NODE_004, + WIFI_MESSAGE_SINGLE_NODE_005, + WIFI_MESSAGE_END = 300, +} HdfWiFiTestCaseCmd; + +int32_t HdfWifiEntry(HdfTestMsg *msg); + +#endif // HDF_WIFI_TEST_H \ No newline at end of file diff --git a/tools/hc-gen/Makefile b/tools/hc-gen/Makefile new file mode 100644 index 00000000..3b75b8ee --- /dev/null +++ b/tools/hc-gen/Makefile @@ -0,0 +1,84 @@ +# 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. + +TARGET := hc-gen +YACC_LEX_PREFIX :=HcsCompiler +C_FLAGS := -std=gnu99 -Wall -Werror -Wno-attributes -Wall +CC := gcc +YACC := bison +LEX := flex +Q = @ + +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) + +ORIGIN_SOURCES := $(wildcard src/*) +ORIGIN_SOURCES += $(wildcard $(BOUNDS_CHECK_LIB)/src/*) + +C_SOURCES := $(filter %.c,$(ORIGIN_SOURCES)) +YACC_SOURCES := $(filter %.y,$(ORIGIN_SOURCES)) +LEX_SOURCES := $(filter %.l,$(ORIGIN_SOURCES)) +YACC_GEN_SOURCES := $(patsubst %.y,$(OUT_DIR)/%_tab.c,$(YACC_SOURCES)) +LEX_GEN_SOURCES := $(patsubst %.l,$(OUT_DIR)/%_lex.c,$(LEX_SOURCES)) + +C_OBJECTS := $(patsubst %.c,$(OUT_DIR)/%.o,$(C_SOURCES)) +GEN_OBJECTS += $(patsubst %.c,%.o,$(YACC_GEN_SOURCES) $(LEX_GEN_SOURCES)) +OBJECTS := $(GEN_OBJECTS) $(C_OBJECTS) + +C_FLAGS += $(addprefix -I,$(INCLUDE_DIR)) +INCLUDE_DIR += $(OUT_DIR) + +UNAME := $(shell uname -a) +ifneq ($(findstring Linux,$(UNAME)),) + C_FLAGS += -D OS_LINUX +else + C_FLAGS += -D OS_WIN + C_FLAGS += -D MINGW32 +endif + +ifeq ($(BUILD_TYPE),debug) + C_FLAGS += -g +else ifeq ($(BUILD_TYPE),asan) + C_FLAGS += -g -fsanitize=address +else + # release + C_FLAGS += -O2 -s -ffunction-sections -fdata-sections -Wl,--gc-sections +endif + +all: $(TARGET) + +$(YACC_GEN_SOURCES) : $(OUT_DIR)/%_tab.c : %.y + $(Q)mkdir -p $(dir $(@)) + $(Q)$(YACC) -o $@ -v -d -pHcsCompiler $< + +$(LEX_GEN_SOURCES) : $(OUT_DIR)/%_lex.c : %.l | $(YACC_GEN_SOURCES) + $(Q)mkdir -p $(dir $(@)) + $(Q)$(LEX) -o $@ -PHcsCompiler $< + +$(C_OBJECTS) : $(OUT_DIR)/%.o : %.c + $(Q)mkdir -p $(dir $(@)) + $(Q)$(CC) -c -o $@ $(C_FLAGS) $^ + +$(GEN_OBJECTS) : %.o : %.c + $(Q)$(CC) -c -o $@ $(C_FLAGS) $^ + +$(TARGET) : $(OBJECTS) | $(GEN_OBJECTS) + $(Q)$(CC) -o $@ $(C_FLAGS) $^ + +test: all + python3 $(TEST_CASE)/hcgen_test.py $(TARGET) + +test_update: all + python3 $(TEST_CASE)/update_case.py $(TARGET) + +clean: + $(Q)rm -rf $(OUT_DIR) + $(Q)rm -f $(TARGET) + +.PHONY: clean all test test_update diff --git a/tools/hc-gen/include/hcs_ast.h b/tools/hc-gen/include/hcs_ast.h old mode 100755 new mode 100644 index c9ed848e..962b645d --- a/tools/hc-gen/include/hcs_ast.h +++ b/tools/hc-gen/include/hcs_ast.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_AST_H diff --git a/tools/hc-gen/include/hcs_compiler.h b/tools/hc-gen/include/hcs_compiler.h old mode 100755 new mode 100644 index efefbda5..3e6371cb --- a/tools/hc-gen/include/hcs_compiler.h +++ b/tools/hc-gen/include/hcs_compiler.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_H diff --git a/tools/hc-gen/include/hcs_decompiler.h b/tools/hc-gen/include/hcs_decompiler.h old mode 100755 new mode 100644 index aa164e0b..32bd8800 --- a/tools/hc-gen/include/hcs_decompiler.h +++ b/tools/hc-gen/include/hcs_decompiler.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_DECOMPILE_H diff --git a/tools/hc-gen/include/hcs_file.h b/tools/hc-gen/include/hcs_file.h old mode 100755 new mode 100644 index 375cf8a3..7411dd6d --- a/tools/hc-gen/include/hcs_file.h +++ b/tools/hc-gen/include/hcs_file.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_FILE_H diff --git a/tools/hc-gen/include/hcs_gener.h b/tools/hc-gen/include/hcs_gener.h old mode 100755 new mode 100644 index 8d00a029..ae29334a --- a/tools/hc-gen/include/hcs_gener.h +++ b/tools/hc-gen/include/hcs_gener.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_GENER_H diff --git a/tools/hc-gen/include/hcs_log.h b/tools/hc-gen/include/hcs_log.h old mode 100755 new mode 100644 index 70defdca..bc71064a --- a/tools/hc-gen/include/hcs_log.h +++ b/tools/hc-gen/include/hcs_log.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_LOG_H diff --git a/tools/hc-gen/include/hcs_mem.h b/tools/hc-gen/include/hcs_mem.h old mode 100755 new mode 100644 index 7b3a4be0..ba5e636d --- a/tools/hc-gen/include/hcs_mem.h +++ b/tools/hc-gen/include/hcs_mem.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_MEM_H diff --git a/tools/hc-gen/include/hcs_opcode.h b/tools/hc-gen/include/hcs_opcode.h old mode 100755 new mode 100644 index cb29fc57..0c32eacb --- a/tools/hc-gen/include/hcs_opcode.h +++ b/tools/hc-gen/include/hcs_opcode.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_OPCODE_H diff --git a/tools/hc-gen/include/hcs_option.h b/tools/hc-gen/include/hcs_option.h old mode 100755 new mode 100644 index 5dd642c7..034d940c --- a/tools/hc-gen/include/hcs_option.h +++ b/tools/hc-gen/include/hcs_option.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_OPTION_H diff --git a/tools/hc-gen/include/hcs_parser.h b/tools/hc-gen/include/hcs_parser.h old mode 100755 new mode 100644 index dc01f9e3..3d74465e --- a/tools/hc-gen/include/hcs_parser.h +++ b/tools/hc-gen/include/hcs_parser.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_PARSER_H diff --git a/tools/hc-gen/include/hcs_types.h b/tools/hc-gen/include/hcs_types.h old mode 100755 new mode 100644 index f1c3e633..8725c2bf --- a/tools/hc-gen/include/hcs_types.h +++ b/tools/hc-gen/include/hcs_types.h @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 HCS_COMPILER_TYPES_H diff --git a/tools/hc-gen/src/hcs_ast.c b/tools/hc-gen/src/hcs_ast.c old mode 100755 new mode 100644 index 3273e2b3..5b2365f4 --- a/tools/hc-gen/src/hcs_ast.c +++ b/tools/hc-gen/src/hcs_ast.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -252,6 +229,7 @@ void HcsAstRemoveChildLink(ParserObjectBase *parent, ParserObjectBase *child) while (pre != NULL) { if (pre->next == child) { pre->next = pre->next->next; + break; } pre = pre->next; @@ -699,12 +677,12 @@ static int32_t AstDumpWalkCallback(ParserObject *current, int32_t walkDepth) case PARSEROP_STRING: HCS_PRINT(" %s", current->configTerm.stringValue); break; - case PARSEROP_CONFNODE: { + case PARSEROP_CONFNODE: if (current->configNode.nodeType != CONFIG_NODE_NOREF) { HCS_PRINT("%-10s %-10s", HcsParserNodeTypeToStr(current->configNode.nodeType), current->configNode.refNodePath ? current->configNode.refNodePath : ""); } - } break; + break; case PARSEROP_NODEREF: HCS_PRINT("%-10s %"PRIx64, "NodeReference", current->objectBase.value); break; diff --git a/tools/hc-gen/src/hcs_bytecode_gen.c b/tools/hc-gen/src/hcs_bytecode_gen.c old mode 100755 new mode 100644 index 1a5e70e7..39512292 --- a/tools/hc-gen/src/hcs_bytecode_gen.c +++ b/tools/hc-gen/src/hcs_bytecode_gen.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -202,7 +179,7 @@ int32_t HcsBytecodeOutput() } HcsCloseOutput(outputFIle); - HCS_INFO("Total size: %u ", astRoot->objectBase.size); + HCS_DEBUG("Total size: %u ", astRoot->objectBase.size); if (ret == NOERR && HcsOptShouldGenHexdump()) { ret = HcsBinaryToHexdump(HcsGetOutPutFileName()); } diff --git a/tools/hc-gen/src/hcs_compiler.l b/tools/hc-gen/src/hcs_compiler.l index ff1a4931..a0029e8d 100755 --- a/tools/hc-gen/src/hcs_compiler.l +++ b/tools/hc-gen/src/hcs_compiler.l @@ -7,38 +7,15 @@ %{ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_parser.h" -#include "hcs_gen_parser.h" +#include "hcs_compiler_tab.h" #ifdef LEXER_DEBUG_ENABLE #define LEXER_DEBUG(...) printf(__VA_ARGS__) @@ -53,7 +30,7 @@ extern void HcsCompilererror (char *s); "/*" {BEGIN(CMT);} "*/" {BEGIN(INITIAL); } ([^*]|\n)+|. -<> {LEXER_DEBUG("%d:unterminated coment\n", HcsCompilerlineno); return 0;} +<> {LEXER_DEBUG("%d:unterminated comment\n", HcsCompilerlineno); return 0;} "//".*\n "{" { LEXER_DEBUG("{\n"); return HcsCompilertext[0]; }; "}" { LEXER_DEBUG("}\n"); return HcsCompilertext[0]; }; diff --git a/tools/hc-gen/src/hcs_compiler.y b/tools/hc-gen/src/hcs_compiler.y index ebb9cb59..9ccc0b00 100755 --- a/tools/hc-gen/src/hcs_compiler.y +++ b/tools/hc-gen/src/hcs_compiler.y @@ -1,33 +1,10 @@ %{ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -188,4 +165,4 @@ void HcsCompilerrestart(FILE *input_file); void HcsParserRestart(FILE *inputFile) { HcsCompilerrestart(inputFile); -} \ No newline at end of file +} diff --git a/tools/hc-gen/src/hcs_decompile_gen.c b/tools/hc-gen/src/hcs_decompile_gen.c old mode 100755 new mode 100644 index 38935730..5959fc52 --- a/tools/hc-gen/src/hcs_decompile_gen.c +++ b/tools/hc-gen/src/hcs_decompile_gen.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_decompiler.c b/tools/hc-gen/src/hcs_decompiler.c old mode 100755 new mode 100644 index de352ba7..2aac4443 --- a/tools/hc-gen/src/hcs_decompiler.c +++ b/tools/hc-gen/src/hcs_decompiler.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_file.c b/tools/hc-gen/src/hcs_file.c old mode 100755 new mode 100644 index 51a379cc..34b50002 --- a/tools/hc-gen/src/hcs_file.c +++ b/tools/hc-gen/src/hcs_file.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -132,7 +109,7 @@ static const char *GetFileName(const char *path) } } - return i > 0 ? path + i + 1 : path; + return i >= 0 ? path + i + 1 : path; } static const char *CopyFileName(const char *path) @@ -390,7 +367,7 @@ struct HcsFile *HcsOpenOutputFile(const char *suffix) return NULL; } - HCS_INFO("Output: %s", outputFileName); + HCS_DEBUG("Output: %s", outputFileName); struct HcsFile *outputFile = HcsMemZalloc(sizeof(struct HcsFile)); if (outputFile == NULL) { HCS_ERROR("oom"); diff --git a/tools/hc-gen/src/hcs_hexdump.c b/tools/hc-gen/src/hcs_hexdump.c old mode 100755 new mode 100644 index 7e938298..59d634a5 --- a/tools/hc-gen/src/hcs_hexdump.c +++ b/tools/hc-gen/src/hcs_hexdump.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_main.c b/tools/hc-gen/src/hcs_main.c old mode 100755 new mode 100644 index 737ce0d7..7156fd9d --- a/tools/hc-gen/src/hcs_main.c +++ b/tools/hc-gen/src/hcs_main.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 "hcs_compiler.h" diff --git a/tools/hc-gen/src/hcs_mem.c b/tools/hc-gen/src/hcs_mem.c old mode 100755 new mode 100644 index 8e5e28a3..410c66a2 --- a/tools/hc-gen/src/hcs_mem.c +++ b/tools/hc-gen/src/hcs_mem.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_middle.c b/tools/hc-gen/src/hcs_middle.c old mode 100755 new mode 100644 index 29fd632b..35301f84 --- a/tools/hc-gen/src/hcs_middle.c +++ b/tools/hc-gen/src/hcs_middle.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -482,7 +459,7 @@ int32_t HcsDoOptimize() if (moduleName == NULL) { return EINVALARG; } - HCS_INFO("compile module : %s", moduleName); + HCS_DEBUG("compile module : %s", moduleName); /* expend node ref and node copy */ ret = HcsWalkAst(root, AST_WALK_BACKEND, NULL, HcsMiddleProcessCallback); if (ret) { diff --git a/tools/hc-gen/src/hcs_opcode.c b/tools/hc-gen/src/hcs_opcode.c old mode 100755 new mode 100644 index 64214236..3bfac2df --- a/tools/hc-gen/src/hcs_opcode.c +++ b/tools/hc-gen/src/hcs_opcode.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_option.c b/tools/hc-gen/src/hcs_option.c old mode 100755 new mode 100644 index 6e2e9e41..3958660b --- a/tools/hc-gen/src/hcs_option.c +++ b/tools/hc-gen/src/hcs_option.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -100,7 +77,7 @@ void ShowUsage() void ShowVersionInfo() { HCS_PRINT("Hcs compiler v%u.%u\n", HCS_COMPILER_VERSION_MAJOR, HCS_COMPILER_VERSION_MINOR); - HCS_PRINT("Copyright (c) Huawei Technologies Co., Ltd. 2020\n"); + HCS_PRINT("Copyright (c) 2020-2021 Huawei Device Co., Ltd.\n"); } static int32_t ProcessOption(int32_t argc, char *argv[]) @@ -177,4 +154,4 @@ int32_t DoOption(int32_t argc, char *argv[]) bool HcsVerbosePrint() { return g_verbosePrint; -} \ No newline at end of file +} diff --git a/tools/hc-gen/src/hcs_parser.c b/tools/hc-gen/src/hcs_parser.c old mode 100755 new mode 100644 index 39a9633a..7e595cef --- a/tools/hc-gen/src/hcs_parser.c +++ b/tools/hc-gen/src/hcs_parser.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/tools/hc-gen/src/hcs_text_gen.c b/tools/hc-gen/src/hcs_text_gen.c old mode 100755 new mode 100644 index 70ae4b97..00cce070 --- a/tools/hc-gen/src/hcs_text_gen.c +++ b/tools/hc-gen/src/hcs_text_gen.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 diff --git a/utils/include/hdf_cstring.h b/utils/include/hdf_cstring.h old mode 100755 new mode 100644 index dedda5cf..8e261c5f --- a/utils/include/hdf_cstring.h +++ b/utils/include/hdf_cstring.h @@ -1,39 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_CSTRING_H #define HDF_CSTRING_H -#include -#include +#include "hdf_base.h" #ifdef __cplusplus extern "C" { @@ -44,7 +20,6 @@ struct HdfCString { char value[0]; }; -bool HdfStringToInt(const char* str, int *value); uint32_t HdfStringMakeHashKey(const char *key, uint32_t mask); struct HdfCString *HdfCStringObtain(const char *str); void HdfCStringRecycle(struct HdfCString *inst); diff --git a/utils/include/hdf_slist.h b/utils/include/hdf_slist.h old mode 100755 new mode 100644 index b9bf13e5..94ec646e --- a/utils/include/hdf_slist.h +++ b/utils/include/hdf_slist.h @@ -1,40 +1,15 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_SINGLE_LIST_H #define HDF_SINGLE_LIST_H -#include -#include -#include +#include "hdf_base.h" #ifdef __cplusplus extern "C" { @@ -50,8 +25,8 @@ struct HdfSList { struct HdfSListIterator { int stepOnNext; - struct HdfSListNode *previous; // points to the item before the current one - struct HdfSListNode *current; // points to the current item (to detect item removal) + struct HdfSListNode *prev; // points to the item before the current one + struct HdfSListNode *curr; // points to the current item (to detect item removal) }; typedef void (*HdfSListDeleter)(struct HdfSListNode *); diff --git a/utils/include/hdf_sref.h b/utils/include/hdf_sref.h old mode 100755 new mode 100644 index 00f7297d..bfc4b6c5 --- a/utils/include/hdf_sref.h +++ b/utils/include/hdf_sref.h @@ -1,63 +1,40 @@ -/* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef HDF_SREF_H -#define HDF_SREF_H - -#include "osal_atomic.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct HdfSRef; - -struct IHdfSRefListener { - void (*OnFirstAcquire)(struct HdfSRef *); - void (*OnLastRelease)(struct HdfSRef *); -}; - -struct HdfSRef { - OsalAtomic refs; - struct IHdfSRefListener *listener; - void (*Acquire)(struct HdfSRef *); - void (*Release)(struct HdfSRef *); -}; - -void HdfSRefAcquire(struct HdfSRef *sref); -void HdfSRefRelease(struct HdfSRef *sref); -void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener); - -#ifdef __cplusplus -} -#endif - -#endif /* HDF_SREF_H */ +/* + * 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_SREF_H +#define HDF_SREF_H + +#include "osal_atomic.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct HdfSRef; + +struct IHdfSRefListener { + void (*OnFirstAcquire)(struct HdfSRef *); + void (*OnLastRelease)(struct HdfSRef *); +}; + +struct HdfSRef { + OsalAtomic refs; + struct IHdfSRefListener *listener; + void (*Acquire)(struct HdfSRef *); + void (*Release)(struct HdfSRef *); +}; + +void HdfSRefAcquire(struct HdfSRef *sref); +void HdfSRefRelease(struct HdfSRef *sref); +void HdfSRefConstruct(struct HdfSRef *sref, struct IHdfSRefListener *listener); + +#ifdef __cplusplus +} +#endif + +#endif /* HDF_SREF_H */ diff --git a/utils/src/hdf_cstring.c b/utils/src/hdf_cstring.c old mode 100755 new mode 100644 index 33217993..4b30bb2e --- a/utils/src/hdf_cstring.c +++ b/utils/src/hdf_cstring.c @@ -1,38 +1,12 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_cstring.h" -#include -#include -#include #include "hdf_log.h" #include "osal_mem.h" #include "securec.h" @@ -47,24 +21,6 @@ uint32_t HdfStringMakeHashKey(const char *key, uint32_t mask) return (hashValue & 0x7FFFFFFF) | mask; } -bool HdfStringToInt(const char *str, int *value) -{ - if (str == NULL || value == NULL) { - return false; - } - - char *end = NULL; - errno = 0; - const int base = 10; - long result = strtol(str, &end, base); - if (end == str || end[0] != '\0' || errno == ERANGE || result > INT_MAX || result < INT_MIN) { - return false; - } - - *value = (int)result; - return true; -} - struct HdfCString *HdfCStringObtain(const char *str) { struct HdfCString *instance = NULL; diff --git a/utils/src/hdf_slist.c b/utils/src/hdf_slist.c old mode 100755 new mode 100644 index c6fd97aa..fdd13671 --- a/utils/src/hdf_slist.c +++ b/utils/src/hdf_slist.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_slist.h" @@ -227,64 +204,64 @@ void HdfSListIteratorInit(struct HdfSListIterator *iterator, struct HdfSList *li if (iterator == NULL || list == NULL) { if (iterator != NULL) { iterator->stepOnNext = 0; - iterator->previous = NULL; - iterator->current = NULL; + iterator->prev = NULL; + iterator->curr = NULL; } return; } iterator->stepOnNext = 0; - iterator->previous = (struct HdfSListNode *)list; - iterator->current = list->root; + iterator->prev = (struct HdfSListNode *)list; + iterator->curr = list->root; } bool HdfSListIteratorHasNext(struct HdfSListIterator *iterator) { - if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + if ((iterator == NULL) || (iterator->curr == NULL) || (iterator->prev == NULL)) { return false; } if (!iterator->stepOnNext) { - return iterator->current != NULL; + return iterator->curr != NULL; } - if (iterator->previous->next != iterator->current) { + if (iterator->prev->next != iterator->curr) { // current item has been removed - return iterator->previous->next != NULL; + return iterator->prev->next != NULL; } // current items has not been removed - return iterator->current->next != NULL; + return iterator->curr->next != NULL; } struct HdfSListNode *HdfSListIteratorNext(struct HdfSListIterator *iterator) { - if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + if ((iterator == NULL) || (iterator->curr == NULL) || (iterator->prev == NULL)) { return NULL; } if (iterator->stepOnNext) { - if (iterator->previous->next == iterator->current) { - iterator->previous = iterator->current; - iterator->current = iterator->current->next; + if (iterator->prev->next == iterator->curr) { + iterator->prev = iterator->curr; + iterator->curr = iterator->curr->next; } else { // curr was removed from the list, set it again but don't advance prev - iterator->current = iterator->previous->next; + iterator->curr = iterator->prev->next; } } else { iterator->stepOnNext = 1; } - return iterator->current; + return iterator->curr; } void HdfSListIteratorRemove(struct HdfSListIterator *iterator) { - if ((iterator == NULL) || (iterator->current == NULL) || (iterator->previous == NULL)) { + if ((iterator == NULL) || (iterator->curr == NULL) || (iterator->prev == NULL)) { return; } - iterator->current = iterator->current->next; - iterator->previous->next = iterator->current; + iterator->curr = iterator->curr->next; + iterator->prev->next = iterator->curr; iterator->stepOnNext = 0; } @@ -294,8 +271,8 @@ void HdfSListIteratorInsert(struct HdfSListIterator *iterator, struct HdfSListNo return; } - link->next = iterator->current; - iterator->previous->next = link; - iterator->previous = link; + link->next = iterator->curr; + iterator->prev->next = link; + iterator->prev = link; } diff --git a/utils/src/hdf_sref.c b/utils/src/hdf_sref.c old mode 100755 new mode 100644 index 0ec4c874..9ea9733a --- a/utils/src/hdf_sref.c +++ b/utils/src/hdf_sref.c @@ -1,32 +1,9 @@ /* - * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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_sref.h"