-- Copyright (c) 2026 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--          http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local accessor = require('access.accessor')
local scanner = require('access.scanner')
local driver = require('driver.driver')
local mux = require('mux.mux')
local cjson = require('cjson')
local protocol = require('protocol.protocol')
local utils = require('mc.utils')
local log = require('mc.logging')
local cache = require('cache')
local skynet = require('skynet')
local object_pool = require('object_pool')
local aggregate = require('aggregate')
local shared_object = require('shared_object')
local vos = require('utils.vos')
local custom_messages = require('messages.custom')
local hw_log = require('hw_utils.hw_log')
local telemetry = require('telemetry')
local hw_wait_access = require('hw_utils.hw_wait_access')
local wait_hw_access = hw_wait_access.wait_hw_access
local hw_utils = require('hw_utils.utils')

local metrics = require('telemetry.metrics')
local meter = metrics.get_meter('hwproxy')

local chip_access_counter = meter:create_counter('bmc.hw.chip.io')
local chip_scanner_counter = meter:create_counter('bmc.hw.chip.scanner')
local chip_accessor_counter = meter:create_counter('bmc.hw.chip.accessor')

local trace = require('telemetry.trace')

local s_match = string.match
local s_format = string.format
local t_concat = table.concat
local skynet_sleep = skynet.sleep
local cjson_encode = cjson.encode
local to_hex = utils.to_hex
local time_ms = utils.time_ms
local close_exec = utils.close_exec
local object_pool_new = object_pool.new
local object_pool_recycle = object_pool.recycle
local binary_to_dbus_type = utils.binary_to_dbus_type
local debounce_and_precision = hw_utils.debounce_and_precision

local FLASH_WRITEREAD_ACCESS_TYPE = 4
local FLASH_WRITE_ACCESS_TYPE = 3
local FLASH_ERASE_ACCESS_TYPE = 2
local BLOCK_ACCESS_TYPE = 1
local BIT_ACCESS_TYPE = 0
-- 以下为FLASH IO接口中提供的总线原始方法和擦除方法。FLASH器件也支持BLOCK IO方法,BLOCK IO中的读写方法是已经根据通信协议中的标准读、页编程命令实现的功能封装接口
local ACCESS_TYPE_MAP = {
    [FLASH_WRITEREAD_ACCESS_TYPE] = 'raw_write_read',
    [FLASH_WRITE_ACCESS_TYPE] = 'raw_write',
    [FLASH_ERASE_ACCESS_TYPE] = 'erase',
}
local BLOCK_MASK = 0xffffffff
local DEFAULT_MASK = 0xffffffff
local EXTEND_READ_OFFSET = 0xffffffff
local TEST_RESULT_SUCCEED = 'Succeed'
local TEST_RESULT_FAILED = 'Failed'

local PRIORITY_SECONDARY = 'Secondary'

local SCAN_OK = '\00'
local SCAN_FAILURE = '\01'
local SCAN_PRE_FAILURE = '\02'
local SCAN_DISABLED = 0

local SELFREQUESTOR = 'bmc.kepler.hwproxy'
local DISCOVERY_REQUESTOR = 'bmc.kepler.hwdiscovery'

local PROTOCOL_SMBUS = 0x02 -- smbus协议标志
local PROTOCOL_MCTP_OVER_SMC = 0x03 -- mctp over smc标志

local CHIP_INTERFACE = 'bmc.kepler.Chip'

local ACCESS_SUCCESS = 0
local ACCESS_FAILED = 1

local max_queue_len = tonumber(skynet.getenv('CHIP_REQUEST_QUEUE_MAX_LEN') or 500)
local function convert_to_value_queue_len(queue_len)
    if queue_len < 100 then
        return 100 -- 实测队列正常场景下使用长度不超过50, 因此设置2倍作为最小值保留余量
    elseif queue_len > 1000 then
        return 1000 -- 超过1000时最大场景Bus数*bus上器件数*5种队列*1000条消息会超过框架限制导致oom, 防护失效
    end
    return queue_len
end

local function empty_cb() end

local MAX_QUEUE_LEN <const> = convert_to_value_queue_len(max_queue_len)

local function read_write_with_retry_times(func, retry_times, ...)
    -- retry_times为0表示不重试
    local ok, ret_msg
    for i = 0, retry_times do
        ok, ret_msg = pcall(func, ...)
        if ok then
            return ok, ret_msg
        end
        log:debug('read or write failed, retry times: %s', i)
    end
    return ok, ret_msg
end

local function check_accessible_status(accessible_status, chip_name, chip)
    if not accessible_status then
        log:raise('the chip %s access has been closed, please manually open it!', chip_name)
    end

    if chip and chip.stopped then
        log:raise('the chip %s access has been closed after reboot', chip_name)
    end
end

local function check_queue_is_over_limit(chip, cache, queue_type, name, bus_name, accessible_status)
    check_accessible_status(accessible_status, name, chip)
    local flag = cache.queue_over_flag[queue_type]
    if flag then
        error(custom_messages.ChipRequestLimitExceeded(name))
    end

    local len = cache.queue_len[queue_type]
    if len >= MAX_QUEUE_LEN then
        cache.queue_over_flag[queue_type] = true
        log:error('the %s queue len of %s is over limit, bus name: %s, queue len : %s', queue_type, name, bus_name, len)
        error(custom_messages.ChipRequestLimitExceeded(name))
    end
end

local function send_datastream2main(...)
    skynet.send('.hwproxy', 'lua', 'trace_chip', ...)
end

---@class chip
local chip = {}
-- 定义字段索引常量
local NAME_FIELD = 1
local CLASS_NAME_FIELD = 2
local PROTOCOL_FIELD = 3
local DRIVER_FIELD = 4
local MUX_FIELD = 5
local R_CHIP_FIELD = 6
local ACCESSORS_FIELD = 7
local SCANNERS_FIELD = 8
local READ_RETRY_TIMES_FIELD = 9
local WRITE_RETRY_TIMES_FIELD = 10
local RESET_ACCESSOR_FIELD = 11
local CONSEC_FAILED_ACCESS_CNT_FIELD = 12
local TREE_OBJ_FIELD = 13
local HOST_BUS_FIELD = 14
local BUS_NAME_FIELD = 15
local L_CHIP_FIELD = 16
local LOW_CACHE_FIELD = 17
local HIGH_CACHE_FIELD = 18
local SECONDARY_CACHE_FIELD = 19
local CHANNEL_ID_FIELD = 20
local CHANNEL_CHAIN_FIELD = 21
local OPENED_CHANNEL_ID_FIELD = 22
local ACCESSIBLE_STATUS_FIELD = 23
local TREE_OBJS_FIELD = 24
local AGGREGATE_SECTIONS_FIELD = 25
local SMC_DFX_INFOS_FIELD = 26
local THREAD_HANDLER_FIELD = 27
local WRITE_SUCCESS_COUNT_FIELD = 28
local READ_SUCCESS_COUNT_FIELD = 29
local WRITE_FAIL_COUNT_FIELD = 30
local READ_FAIL_COUNT_FIELD = 31
local START_WRITE_READ_TIME_FIELD = 32
local REF_COUNT_FIELD = 33
local ISMONITORED_FIELD = 34
local CHIP_TEST_FETCHES_FIELD = 35
local ERR_TABLE_FIELD = 36
local CHIP_TEST_PARAS_FIELD = 37
local SWITCH_SUPPORT_FIELD = 38
local STOP_FIELD = 39
local IS_HEALTH_STATUS_MODIFIED_FIELD = 40
local DELAY_FIELD = 44
-- 属性定义需要在方法之前,修改属性需同步修改常量值
local COMBO_WRITE_READ_METHOD = 41
local WRITE_METHOD = 42
local READ_METHOD = 43
local FIELD_MAP = {
    name = NAME_FIELD,
    class_name = CLASS_NAME_FIELD,
    protocol = PROTOCOL_FIELD,
    driver = DRIVER_FIELD,
    mux = MUX_FIELD,
    r_chips = R_CHIP_FIELD,
    accessors = ACCESSORS_FIELD,
    scanners = SCANNERS_FIELD,
    read_retry_times = READ_RETRY_TIMES_FIELD,
    write_retry_times = WRITE_RETRY_TIMES_FIELD,
    reset_accessor = RESET_ACCESSOR_FIELD,
    consec_failed_access_cnt = CONSEC_FAILED_ACCESS_CNT_FIELD,
    tree_obj = TREE_OBJ_FIELD,
    host_bus = HOST_BUS_FIELD,
    bus_name = BUS_NAME_FIELD,
    l_chip = L_CHIP_FIELD,
    low_cache = LOW_CACHE_FIELD,
    high_cache = HIGH_CACHE_FIELD,
    secondary_cache = SECONDARY_CACHE_FIELD,
    channel_id = CHANNEL_ID_FIELD,
    channel_chain = CHANNEL_CHAIN_FIELD,
    opened_channel_id = OPENED_CHANNEL_ID_FIELD,
    accessible_status = ACCESSIBLE_STATUS_FIELD,
    tree_objs = TREE_OBJS_FIELD,
    aggregate_sections = AGGREGATE_SECTIONS_FIELD,
    smc_dfx_infos = SMC_DFX_INFOS_FIELD,
    thread_handler = THREAD_HANDLER_FIELD,
    write_success_count = WRITE_SUCCESS_COUNT_FIELD,
    read_success_count = READ_SUCCESS_COUNT_FIELD,
    write_fail_count = WRITE_FAIL_COUNT_FIELD,
    read_fail_count = READ_FAIL_COUNT_FIELD,
    start_write_read_time = START_WRITE_READ_TIME_FIELD,
    ref_count = REF_COUNT_FIELD,
    ismonitored = ISMONITORED_FIELD,
    chip_test_fetches = CHIP_TEST_FETCHES_FIELD,
    err_table = ERR_TABLE_FIELD,
    chip_test_paras = CHIP_TEST_PARAS_FIELD,
    switch_support = SWITCH_SUPPORT_FIELD,
    stopped = STOP_FIELD,
    is_health_status_modified = IS_HEALTH_STATUS_MODIFIED_FIELD,
    delay = DELAY_FIELD,
    ComboWriteRead = COMBO_WRITE_READ_METHOD, -- ComboWriteRead需要在此表中是第一个方法,避免影响get_chip_value的判断
    write = WRITE_METHOD,
    read = READ_METHOD,
}

local function set_chip_value(self, name, val)
    local idx = FIELD_MAP[name]
    if idx then
        rawset(self, idx, val)
    end
end

local function get_chip_value(self, name)
    local idx = FIELD_MAP[name]
    if idx then
        local value = rawget(self, idx)
        -- 此处需要FIELD_MAP里的第一个方法
        if idx < COMBO_WRITE_READ_METHOD or value then
            return value
        end
    end

    local method = rawget(chip, name)
    if method then
        return method
    end
end

chip.__newindex = set_chip_value
chip.__index = get_chip_value

function chip.new(object)
    local obj = {}
    obj[NAME_FIELD] = object.name
    obj[CLASS_NAME_FIELD] = object.class_name
    obj[PROTOCOL_FIELD] = (protocol[object.class_name] or protocol.None).new()
    obj[DRIVER_FIELD] = (driver[object.class_name] or driver.None).new(obj, object)
    if not object.SwitchSupported or type(object.ComboWriteRead) == 'function' then
        obj[MUX_FIELD] = (mux[object.class_name] or mux.None).new(obj)
    end

    obj[SWITCH_SUPPORT_FIELD] = object.SwitchSupported or false
    obj[STOP_FIELD] = false
    obj[R_CHIP_FIELD] = {}
    obj[ACCESSORS_FIELD] = {}
    obj[SCANNERS_FIELD] = {}
    obj[READ_RETRY_TIMES_FIELD] = object.ReadRetryTimes or 0
    obj[WRITE_RETRY_TIMES_FIELD] = object.WriteRetryTimes or 0
    obj[RESET_ACCESSOR_FIELD] = object.ChipReset or false
    if object.Delay and object.Delay ~= 0 then
        obj[DELAY_FIELD] = object.Delay
    end

    obj[CONSEC_FAILED_ACCESS_CNT_FIELD] = 0
    -- 获取共享对象,用于直接更新资源树属性
    obj[TREE_OBJ_FIELD] = shared_object.get_shared_object(object, CHIP_INTERFACE)

    -- 创建topo时添加
    obj[HOST_BUS_FIELD] = false
    obj[BUS_NAME_FIELD] = 'Unknown'
    obj[L_CHIP_FIELD] = false

    -- 读写请求缓存
    obj[LOW_CACHE_FIELD] = cache.new(obj)
    obj[HIGH_CACHE_FIELD] = cache.new(obj)
    obj[SECONDARY_CACHE_FIELD] = cache.new(obj)

    obj[CHANNEL_ID_FIELD] = -1
    obj[CHANNEL_CHAIN_FIELD] = ''
    obj[OPENED_CHANNEL_ID_FIELD] = -1

    -- 器件可访问状态
    obj[ACCESSIBLE_STATUS_FIELD] = true

    -- 资源树对象与Chip对象为多对一关系
    obj[TREE_OBJS_FIELD] = {}

    -- Chip可能在多处声明,存在多个aggregate汇聚区域
    obj[AGGREGATE_SECTIONS_FIELD] = false
    -- SmcDfxInfo汇聚与普通汇聚进行区分
    obj[SMC_DFX_INFOS_FIELD] = false

    -- 初始化线程句柄
    obj[THREAD_HANDLER_FIELD] = false

    -- 初始化chip读写次数
    obj[WRITE_SUCCESS_COUNT_FIELD] = 0
    obj[READ_SUCCESS_COUNT_FIELD] = 0
    obj[WRITE_FAIL_COUNT_FIELD] = 0
    obj[READ_FAIL_COUNT_FIELD] = 0

    -- 初始化chip开始读写的时间
    obj[START_WRITE_READ_TIME_FIELD] = vos.vos_tick_get()

    obj[REF_COUNT_FIELD] = 1
    -- 监控标志
    obj[ISMONITORED_FIELD] = false

    obj[IS_HEALTH_STATUS_MODIFIED_FIELD] = false
    -- 注册监控回调函数
    if obj[DRIVER_FIELD].set_tracechip then
        obj[DRIVER_FIELD]:set_tracechip(send_datastream2main)
    end
    setmetatable(obj, chip)
    obj:init()
    return obj
end

function chip:init()
    if self.mux then
        return
    end

    -- IEU的MCU通道切换在工作服务进行,无法获取Chip的资源树对象,此处采用重写ComboWriteRead的方式
    self.ComboWriteRead = function(_, _, write_offset, data_in, read_offset, read_length)
        local chip_name = self.name
        log:debug(
            '%s ComboWriteRead packet req=0x%2x, data=%s, rsp=0x%2x len=%d',
            chip_name,
            write_offset,
            to_hex(data_in),
            read_offset,
            read_length
        )
        local input = object_pool_new('input_args', write_offset, BLOCK_MASK, BLOCK_ACCESS_TYPE, #data_in)
        local ok, ret = pcall(self.write, self, input, data_in)
        if not ok then
            self.handle_error(self, ret, true)
        end

        input.offset = read_offset or write_offset
        input.mask = BLOCK_MASK
        input.type = BLOCK_ACCESS_TYPE
        input.length = read_length
        ok, ret = pcall(self.read, self, input)
        if not ok then
            self.handle_error(self, ret, false)
        end

        object_pool_recycle('input_args', input)
        log:debug('%s ComboWriteRead packet rsp=%s', chip_name, to_hex(ret))
        return ret
    end

    self.mux = mux['McuSwitch'].new(self)
end

function chip:set_monitored()
    self.ismonitored = true
    log:hw_stream_info('chip: %s set ismonitored successfully ismonitored: %s', self.name, self.ismonitored)
end

function chip:unset_monitored()
    self.ismonitored = false
    log:hw_stream_info('chip: %s unset ismonitored successfully ismonitored: %s', self.name, self.ismonitored)
end

-- 业务手动更新健康状态
function chip:set_health_status(value)
    -- 将合并的器件状态统一刷新, 健康状态
    if not self.is_health_status_modified then
        self.is_health_status_modified = true
        self.tree_obj.HealthStatusValidity = true

        local tree_obj
        for _, v in ipairs(self.tree_objs) do
            v.is_health_status_modified = true
            tree_obj = v.tree_obj
            tree_obj.HealthStatus = value
            tree_obj.HealthStatusValidity = true
        end

        log:notice(
            'chip %s HealthStatus is set from %s to %s, hwproxy will not update HealthStatus.',
            self.name,
            self.tree_obj.HealthStatus,
            value
        )
    else
        for _, v in ipairs(self.tree_objs) do
            v.tree_obj.HealthStatus = value
        end
        log:notice('chip %s HealthStatus is set from %s to %s', self.name, self.tree_obj.HealthStatus, value)
    end
end

-- Chip进行合并时添加资源树对象
function chip:add_tree_obj(object)
    if object.name ~= self.name then
        local new_object = { name = object.name, class_name = object.class_name, path = object.path }
        new_object.tree_obj = shared_object.get_shared_object(object, CHIP_INTERFACE)
        if new_object.tree_obj then
            new_object.tree_obj.HealthStatus = self.tree_obj.HealthStatus
            new_object.tree_obj.HealthStatusValidity = self.tree_obj.HealthStatusValidity
        end
        self.tree_objs[#self.tree_objs + 1] = new_object
    end

    -- 如果设置汇聚Supported且长度大于0则开启汇聚任务
    if object.Supported and object.Length > 0 then
        local aggregate_obj = aggregate.new(self, object, 'Normal')
        self.aggregate_sections = self.aggregate_sections or {}
        self.aggregate_sections[object.name] = aggregate_obj
        if self.host_bus then
            aggregate_obj:start()
        end
    end
end

-- 拓扑中添加父chip
function chip:add_l_chip(object)
    self.l_chip = object
    self.low_cache:set_parent(self.l_chip.low_cache)
    self.high_cache:set_parent(self.l_chip.high_cache)
    self.secondary_cache:set_parent(self.l_chip.secondary_cache)
end

function chip:reboot_action()
    if self.switch_support then
        local ok, ret = pcall(self.mux.reboot_action, self.mux)
        if not ok or not ret then
            log:warn('chip %s, reboot action failed, err: %s', self.name, ret)
        end
    end
end

function chip:stop(reboot)
    log:hw_stream_notice('chip %s stop', self.name)
    for _, sc in pairs(self.scanners) do
        sc:stop()
    end

    for _, smc_dfx_info_obj in pairs(self.smc_dfx_infos or {}) do
        smc_dfx_info_obj:stop()
    end
    for _, aggregate_obj in pairs(self.aggregate_sections or {}) do
        aggregate_obj:stop()
    end

    for _, r_chips in pairs(self.r_chips) do
        for _, r_chip in ipairs(r_chips) do
            r_chip:stop(reboot)
        end
    end

    if reboot then
        local info = string.format('the chip %s access has been closed after reboot', self.name)
        self.low_cache:clear_queue(info)
        self.high_cache:clear_queue(info)
        self.secondary_cache:clear_queue(info)
    end

    self.low_cache:clean()
    self.high_cache:clean()
    self.secondary_cache:clean()

    if reboot then
        self:reboot_action()
        self.stopped = true
    end

    log:hw_stream_notice('chip %s stop finish', self.name)
end

-- 拓扑中添加子chip
function chip:add_r_chip(object, channel_id)
    -- 设置子chip channel属性
    object.channel_id = channel_id
    object.channel_chain = (#self.channel_chain == 0) and tostring(channel_id)
        or (self.channel_chain .. '_' .. channel_id)
    -- 将子chip添加到r_chips中,不存在则先创建表
    self.r_chips[channel_id] = self.r_chips[channel_id] or {}
    utils.add_table_node(self.r_chips[channel_id], object, #self.r_chips[channel_id] + 1)
end

-- 删除子chip
function chip:delete_r_chip(chip_name)
    for _, r_chips in pairs(self.r_chips) do
        for index = #r_chips, 1, -1 do
            if r_chips[index].name == chip_name and r_chips[index].ref_count == 0 then
                log:hw_stream_error('chip: %s was deleted in topology, pre_device is %s', chip_name, self.name)
                r_chips[index]:stop()
                table.remove(r_chips, index)
            end
        end
    end
end

-- 拓扑中添加父bus
function chip:add_l_bus(object)
    self.host_bus = object
    self.bus_name = self.host_bus and self.host_bus.name or 'Unknown'
    self.driver:add_bus(object)
    for _, sc in pairs(self.scanners) do
        sc:start()
    end
    for _, smc_dfx_info_obj in pairs(self.smc_dfx_infos or {}) do
        smc_dfx_info_obj:start()
    end
    for _, aggregate_obj in pairs(self.aggregate_sections or {}) do
        aggregate_obj:start()
    end
end

-- chip下挂Accesssor
function chip:add_accessor(object)
    local accessor_object = accessor.new(object, self)
    self.accessors[object.name] = accessor_object
end

function chip:merge_scanner(object, debounce_object)
    for _, obj in pairs(self.scanners) do
        if obj:add_resource(object, debounce_object) then
            self.scanners[object.name] = obj
            return obj
        end
    end
end

-- chip下挂Scanner
function chip:add_scanner(object, debounce_object)
    -- 尝试合并处理,普通汇聚时不合并
    local scanner_object
    if not (self.aggregate_sections or {})[object.Chip] then
        scanner_object = self:merge_scanner(object, debounce_object)
    end

    -- 新增scanner
    if not scanner_object then
        scanner_object = scanner.new(object, self, debounce_object)
        self.scanners[object.name] = scanner_object
    end

    if self.smc_dfx_infos and not scanner_object.in_aggregate then
        for _, smc_dfx_info_obj in pairs(self.smc_dfx_infos or {}) do
            if smc_dfx_info_obj.mapping[object.name] then
                smc_dfx_info_obj:add_scanner(scanner_object)
            end
        end
    elseif (self.aggregate_sections or {})[object.Chip] then
        self.aggregate_sections[object.Chip]:add_scanner(scanner_object)
    end
end

function chip:add_smc_dfx_info(object)
    local offset = object.Offset
    if not self.smc_dfx_infos then
        self.smc_dfx_infos = {}
        self.smc_dfx_infos[object.Offset] = aggregate.new(self, object, 'Smc')
    else
        local smc_dfx_info_obj = self.smc_dfx_infos[offset]
        -- 合并相同offset值的对象
        if smc_dfx_info_obj then
            log:notice('merge smcdfxinfo obj: %s -> %s, offset: %s', object.name, smc_dfx_info_obj.name, object.Offset)
            smc_dfx_info_obj:add_dfx_config(object)
        else
            self.smc_dfx_infos[offset] = aggregate.new(self, object, 'Smc')
        end
    end
end

function chip:exit_smc_dfx_info()
    self.smc_dfx_infos = false
    for _, sc in pairs(self.scanners) do
        sc:set_in_aggregate(false)
        sc:start()
    end
end

function chip:chip_init(reg_cfgs)
    if not reg_cfgs or not next(reg_cfgs) then
        return
    end
    local t_driver = self.driver
    local ok, ret = pcall(t_driver.chip_init, t_driver, reg_cfgs)
    if not ok then
        log:hw_stream_error('chip: %s, chip init failed: %s', self.name, ret)
    end
end

function chip:reset()
    -- 仅复位当前器件自身, 不复位前级链路器件

    if not self.reset_accessor or self.reset_accessor == '' then
        return
    end

    local t_driver = self.driver
    -- 各个芯片的reset方式可能不同,后续需要分离差异
    local ok, ret = pcall(t_driver.reset_chip, t_driver)
    if not ok then
        log:hw_stream_error('chip: %s, reset failed: %s', self.name, ret)
    end
end

local function chip_access_counter_update(obj, method, result)
    if telemetry.get_status(telemetry.METRICS) then
        local attribute = {
            ['hw.chip.name'] = obj.name ~= nil and obj.name or '',
            ['hw.operation.name'] = method ~= nil and method or '',
            ['hw.operation.result'] = result ~= nil and result or '',
            ['hw.bus.name'] = obj.bus_name ~= nil and obj.bus_name or '',
        }
        chip_access_counter:add(1, attribute)
    end
end

function chip:write(access, buffer)
    local span = trace.start_span('hwproxy.chip.write', trace.get_status() and { ['chip.name'] = self.name } or nil)
    local t_driver = self.driver
    local input = object_pool_new(
        'input',
        access.address or t_driver.address,
        t_driver.addr_width,
        t_driver.offset_width,
        access.offset,
        access.length,
        access.mask,
        access.type,
        buffer,
        access.protocol_flag,
        self.name,
        access.is_trace or self.ismonitored,
        access.requestor or SELFREQUESTOR
    )
    input.host_bus_called = nil
    local ok, ret
    if input.type and ACCESS_TYPE_MAP[input.type] then -- 针对flash的特殊操作
        ok, ret = pcall(t_driver[ACCESS_TYPE_MAP[input.type]], t_driver, input)
    else
        ok, ret = pcall(input.type == BIT_ACCESS_TYPE and t_driver.bit_write or t_driver.write, t_driver, input)
    end
    local host_bus_called = input.host_bus_called
    object_pool_recycle('input', input)
    local smc_completion_code
    if type(ret) == 'table' then
        smc_completion_code = ret.cc
        ret = ret.err
    end
    if not ok then
        self:update_access_status(ACCESS_FAILED, smc_completion_code)
        self.err_table = self.err_table or {}
        hw_log.store_err_log(self.err_table, ret)
        chip_access_counter_update(self, 'write', 'failed')
        self.write_fail_count = self.write_fail_count + 1
        if access.is_trace or self.ismonitored then
            input.funcname = 'write'
            input.has_error = true
            send_datastream2main(input, ret)
        end
        -- host_bus_called字段用于表示该器件读写的抛错是否来源于所属总线,true代表总线层面的抛错
        if host_bus_called then
            self:reset()
        end
        span:set_status('error', s_format('chip %s write failed, err: %s', self.name, ret))
        span:finish()
        error(ret)
    end
    self:update_access_status(ACCESS_SUCCESS)
    chip_access_counter_update(self, 'write', 'success')
    self.write_success_count = self.write_success_count + 1
    span:finish()
end

function chip:read(access)
    local span = trace.start_span('hwproxy.chip.read', trace.get_status() and { ['chip.name'] = self.name } or nil)
    local t_driver = self.driver
    local input = object_pool_new(
        'input',
        access.address or t_driver.address,
        t_driver.addr_width,
        t_driver.offset_width,
        access.offset,
        access.length,
        access.mask,
        access.type,
        access.data_in,
        access.protocol_flag,
        self.name,
        access.is_trace or self.ismonitored,
        access.requestor or SELFREQUESTOR
    )
    input.host_bus_called = nil
    local ok, ret
    if input.type and ACCESS_TYPE_MAP[input.type] then -- 针对flash的特殊操作
        ok, ret = pcall(t_driver[ACCESS_TYPE_MAP[input.type]], t_driver, input)
    else
        ok, ret = pcall(input.type == BIT_ACCESS_TYPE and t_driver.bit_read or t_driver.read, t_driver, input)
    end
    local host_bus_called = input.host_bus_called
    object_pool_recycle('input', input)
    local smc_completion_code
    if type(ret) == 'table' then
        smc_completion_code = ret.cc
        ret = ret.err
    end
    if not ok then
        self:update_access_status(ACCESS_FAILED, smc_completion_code)
        self.err_table = self.err_table or {}
        hw_log.store_err_log(self.err_table, ret)
        chip_access_counter_update(self, 'read', 'failed')
        self.read_fail_count = self.read_fail_count + 1
        if access.is_trace or self.ismonitored then
            input.funcname = 'read'
            input.has_error = true
            send_datastream2main(input, ret)
        end
        if host_bus_called then
            self:reset()
        end
        span:set_status('error', s_format('chip %s read failed, err: %s', self.name, ret))
        span:finish()
        error(ret)
    end
    self:update_access_status(ACCESS_SUCCESS)
    chip_access_counter_update(self, 'read', 'success')
    self.read_success_count = self.read_success_count + 1
    span:finish()
    return ret
end

function chip:handle_resource_failure(res, ret)
    res.total_failure = res.total_failure + 1
    res.failure_count = res.failure_count + 1
    res.success_count = 0

    if self.scanners[res.name] then
        res.tree_obj:set_error('Value', tostring(ret))
    end

    -- 设置失败状态
    if res.failure_count < res.failure_debounce_count then
        res.tree_obj.Status = SCAN_PRE_FAILURE
    else
        res.tree_obj.Status = SCAN_FAILURE
    end
end

function chip:handle_resource_success(res, ret, counter, resource_type, result_type)
    res.total_success = res.total_success + 1
    res.success_count = res.success_count + 1

    local debounced_ret = debounce_and_precision(res, ret)
    -- 当前状态为FAILURE,读取成功次数小于防抖次数时跳过更新
    if res.failure_count >= res.failure_debounce_count and res.success_count < res.success_debounce_count then
        log:hw_stream_info('chip: %s, resources: %s does not update value', self.name, res.name)
        return
    end
    -- 当前状态不为FAILURE时更新, 或当前状态为FAILURE, 成功次数超过防抖次数时更新
    res.failure_count = 0
    local tree_obj, t_scanner = res.tree_obj, self.scanners[res.name]
    if tree_obj.error_status.Value ~= nil and t_scanner then
        tree_obj:clear_error('Value')
    end
    -- 恢复时先设置Status的值,再设置属性Value,此处赋值如果值未改变不会发signal
    local old_status = tree_obj.Status
    tree_obj.Status = SCAN_OK
    local temp_value = debounced_ret or ret
    tree_obj.Value = temp_value

    -- Status状态变更为OK无条件发signal
    local ok_value = binary_to_dbus_type(SCAN_OK, tree_obj.props.Status[1])
    if old_status ~= ok_value and t_scanner then
        tree_obj:emit_property_changed_signal('Value')
    end

    if res.old_value ~= temp_value or (old_status ~= ok_value and t_scanner) then
        if counter then
            local attribute = {
                ['hw.bus.name'] = self.bus_name ~= nil and self.bus_name or '',
                ['hw.chip.name'] = self.name ~= nil and self.name or '',
                [resource_type] = res.name ~= nil and res.name or '',
                [result_type] = 'emitSignal',
            }
            if resource_type == 'hw.chip.accessor.name' then
                attribute['hw.chip.accessor.direction'] = ''
            end
            counter:add(1, attribute)
        end
        res.emit_signal_count = res.emit_signal_count + 1
        res.old_value = temp_value
    end
end

function chip:sync_resource_counter(resource_counter, resource_type, result_type, name, result, direction)
    if not resource_counter then
        return
    end

    local attribute = {
        ['hw.bus.name'] = self.bus_name ~= nil and self.bus_name or '',
        ['hw.chip.name'] = self.name ~= nil and self.name or '',
        [resource_type] = name ~= nil and name or '',
        [result_type] = result ~= nil and result or '',
    }

    if resource_type == 'hw.chip.accessor.name' then
        attribute['hw.chip.accessor.direction'] = direction ~= nil and direction or 'read'
    end
    resource_counter:add(1, attribute)
end

function chip:update_resource(resources, ok, ret, type)
    local is_scanner_type = (type == 'Scanner')
    local resource_counter = is_scanner_type and chip_scanner_counter or chip_accessor_counter
    local resource_type = is_scanner_type and 'hw.chip.scanner.name' or 'hw.chip.accessor.name'
    local result_type = is_scanner_type and 'hw.chip.scanner.result' or 'hw.chip.accessor.result'

    for _, res in pairs(resources) do
        -- scan_status为SCAN_DISABLED状态时跳过更新资源树属性和状态
        if res.tree_obj.scan_status == SCAN_DISABLED then
            local res_debounce = res.debounce
            if res_debounce and res.inited_debounce then
                res_debounce:clear_debounced_val()
                res.inited_debounce = false
            end
            log:hw_stream_info('chip: %s, resources: %s scan_status: %s', self.name, res.name, SCAN_DISABLED)
            goto continue
        end
        if not ok then
            self:handle_resource_failure(res, ret)
            self:sync_resource_counter(resource_counter, resource_type, result_type, res.name, 'failed')
        else
            self:handle_resource_success(res, ret, resource_counter, resource_type, result_type)
        end
        ::continue::
    end
end

function chip:chip_test_once(chip_test_fetches, test_paras)
    local t_driver = self.driver
    local ok, ret = pcall(t_driver.chip_test, t_driver, test_paras)
    for _, fetch in pairs(chip_test_fetches) do
        fetch.result = (ok and ret == true) and TEST_RESULT_SUCCEED or TEST_RESULT_FAILED
        fetch.unexecuted = false
        fetch.cb()
    end
end

local function scanner_loop(chip, disable_duration)
    local accessible_status = chip.accessible_status
    for _ = 1, disable_duration do
        skynet_sleep(100)
        if accessible_status then
            chip.thread_handler = false
            return
        end
    end
    chip:start_scanners()
    chip.thread_handler = false
end

function chip:stop_scanners(disable_duration)
    log:info('stop chip scanner temporarily, chip name : %s', self.name)
    for _, sc in pairs(self.scanners) do
        sc:stop()
    end

    if self.thread_handler then
        skynet.killthread(self.thread_handler)
        self.thread_handler = false
    end
    self.thread_handler = skynet.fork(scanner_loop, self, disable_duration)

    -- 递归调用该器件下的所有下级器件都暂停扫描
    for _, r_chips in pairs(self.r_chips) do
        for _, r_chip in ipairs(r_chips) do
            r_chip:stop_scanners(disable_duration)
        end
    end
end

function chip:start_scanners()
    log:hw_stream_info('chip: %s restart its scanner', self.name)
    for _, sc in pairs(self.scanners) do
        sc:start()
    end
    -- 设置可访问状态为可访问
    self.accessible_status = true
    for _, r_chips in pairs(self.r_chips) do
        for _, r_chip in ipairs(r_chips) do
            r_chip:start_scanners()
        end
    end
end

function chip:batch_write_once(obj)
    local ok, ret
    local input = object_pool_new('input_args')
    local t_write = self.write
    local write_retry_times = self.write_retry_times
    for _, v in ipairs(obj.batch_write_data) do
        input.offset = v.Offset or v[1]
        input.mask = BLOCK_MASK
        input.type = BLOCK_ACCESS_TYPE
        input.length = v.InData and #v.InData or #v[2]

        ok, ret = read_write_with_retry_times(t_write, write_retry_times, self, input, v.InData or v[2])
        if not ok then
            log:hw_stream_error('chip: %s, batch write failed: %s', self.name, ret)
            obj.fetch.result = false
            obj.fetch.unexecuted = false
            obj.fetch.cb()
            object_pool_recycle('input_args', input)
            object_pool_recycle('batch_write_args', obj)
            return
        end
    end
    obj.fetch.result = true
    obj.fetch.unexecuted = false
    obj.fetch.cb()
    object_pool_recycle('input_args', input)
    object_pool_recycle('batch_write_args', obj)
end

function chip:handle_accessor_counter(fetch, ret)
    local resource_counter = chip_accessor_counter
    local resource_type = 'hw.chip.accessor.name'
    local result_type = 'hw.chip.accessor.result'

    local accessor_name = fetch.access_obj.name
    if not ret then
        self:sync_resource_counter(resource_counter, resource_type, result_type, accessor_name, 'failed', 'write')
    end
end

function chip:handle_error(err, is_write)
    local msg = tostring(err)
    local filtered_msg = s_match(msg, '.+/(%S+%.lua:%d+:.+)') or msg
    local error_str = s_format(
        'chip: %s, bus: %s, %s failed: %s',
        self.name,
        self.bus_name,
        is_write and 'write' or 'read',
        filtered_msg
    )
    hw_log:restricted_log(log.hw_stream_error, log, error_str)
    return error_str
end

function chip:write_once(obj)
    if obj.batch_write then
        return self:batch_write_once(obj)
    end

    local ok, ret
    local input = object_pool_new(
        'input_args',
        obj.offset,
        obj.mask,
        obj.type,
        obj.length,
        obj.protocol_flag,
        nil,
        obj.is_trace or nil,
        obj.requestor,
        obj.address
    )

    if obj.is_block_io then
        ok, ret = read_write_with_retry_times(self.write, self.write_retry_times, self, input, obj.value)
    else
        ok, ret = pcall(self.write, self, input, obj.value)
    end
    if not ok then
        obj.fetch.error = self:handle_error(ret, true)
    end

    -- smbus write read处理
    if obj.need_read then
        input.offset = obj.read_offset or obj.offset
        input.mask = obj.mask
        input.type = obj.type
        input.length = obj.read_length
        ok, ret = pcall(self.read, self, input)
        obj.fetch.result = ok and ret or false
    else
        obj.fetch.result = ok
    end

    obj.fetch.unexecuted = false
    obj.fetch.cb()
    if obj.fetch.access_obj then
        self:handle_accessor_counter(obj.fetch, ok)
    end

    object_pool_recycle('write_args', obj)
    object_pool_recycle('input_args', input)
end

function chip:plugin_run_once(obj)
    local ok, ret = pcall(obj.run)
    if not ok then
        log:hw_stream_error('chip: %s, deal plugin request failed error: %s', self.name, ret)
    end

    for _, fetch in ipairs(obj.fetches) do
        if not ok then
            fetch.error = ret
            fetch.result = false
        else
            fetch.result = ret
        end
        fetch.unexecuted = false
        fetch.cb()
    end
end

local function check_fetches_is_timeout(fetches)
    for _, fetch in ipairs(fetches) do
        if not fetch.timeout then
            return false
        end
    end
    return true
end

function chip:get_value_with_mask(ok, error_msg, stream, obj_type, ret, obj_length, masks)
    if not ok then
        return false, error_msg
    end
    local value_ok, value = pcall(stream.get_value_with_mask, stream, obj_type, ret, obj_length, masks)
    if value_ok then
        return value, nil
    end
    return false, self:handle_error(value, false)
end

function chip:read_once(obj)
    local fetches = obj.fetches
    if check_fetches_is_timeout(fetches) then
        log:notice('chip:%s read request is timeout and would not process', self.name)
        object_pool_recycle(obj.protocol_flag and 'smbus_write_read_args' or 'read_args', obj)
        return
    end
    local ok, ret, error_msg
    local obj_type, obj_length = obj.type, obj.length
    local input = object_pool_new(
        'input_args',
        obj.offset,
        obj.mask,
        obj_type,
        obj_length,
        obj.protocol_flag,
        obj.data_in or obj.value or nil,
        obj.is_trace or nil,
        obj.requestor,
        obj.address
    )

    -- 记录开始读取的时间
    local start_time = time_ms()
    if obj.is_block_io then
        ok, ret = read_write_with_retry_times(self.read, self.read_retry_times, self, input)
    else
        ok, ret = pcall(self.read, self, input)
    end
    -- 记录读取结束的时间
    local end_time = time_ms()
    -- 计算一次读取耗时
    local consume_time = end_time - start_time
    if not ok then
        error_msg = self:handle_error(ret, false)
    end

    local run_again
    local stream, real_masks = self.host_bus.stream, obj.real_masks
    -- 通过fetch返回数据
    for k, fetch in ipairs(fetches) do
        if not fetch.timeout then -- 超时的fetch不需要再回填
            local res, err = self:get_value_with_mask(ok, error_msg, stream, obj_type, ret, obj_length, real_masks[k])
            fetch.result = res
            if err then
                fetch.error = err
            end
            if fetch.access_obj then
                fetch.access_obj:update_resource(fetch)
            end
            fetch.consume_time = consume_time
            fetch.unexecuted = false
            fetch.cb()

            run_again = fetch.run_again
            if run_again then
                run_again()
            end
        end
    end

    object_pool_recycle(obj.protocol_flag and 'smbus_write_read_args' or 'read_args', obj)
    object_pool_recycle('input_args', input)
end

function chip:cpld_upg_run(obj)
    local fetch = obj.fetch
    local ok, ret = pcall(fetch.run)
    fetch.run = nil
    if not ok then
        log:error('cpld chip:%s, upgrade failed: %s', self.name, ret)
        fetch.result = false
        fetch.error = ret
        fetch.unexecuted = false
        fetch.cb()
    else
        fetch.result = ret == nil and true or ret
        fetch.unexecuted = false
        fetch.cb()
    end
end

function chip:flush_chip_test(err)
    if not self.chip_test_fetches then
        return
    end

    for _, fetch in pairs(self.chip_test_fetches) do
        if fetch.unexecuted == true then
            fetch.result = TEST_RESULT_FAILED
            fetch.error = err
            fetch.unexecuted = false
            fetch.cb()
        end
    end

    self.chip_test_fetches = nil
    self.chip_test_paras = nil
end

function chip:process_chip_test(ctx)
    if not self.chip_test_fetches then
        return
    end

    local chip_test_fetches = self.chip_test_fetches
    local test_paras = self.chip_test_paras
    ctx:run_once(self.chip_test_once, self, chip_test_fetches, test_paras)

    self.chip_test_fetches = nil
    self.chip_test_paras = nil
end

local function low_cache_process(self, ctx, low_cache)
    ctx:open_channels()
    -- 处理器件自检
    self:process_chip_test(ctx)

    -- 处理写请求数据
    low_cache:process_write(function(obj)
        ctx:run_once(self.write_once, self, obj)
    end)

    -- 处理读请求数据
    local i = 0
    low_cache:process_read(function(obj)
        ctx:run_once(self.read_once, self, obj)

        i = i + 1
        if i % 2 == 0 then
            skynet_sleep(3)
        end
    end)
end

function chip:run_process(ctx)
    local low_cache = self.low_cache
    local ok, err = pcall(low_cache_process, self, ctx, low_cache)
    if not ok then
        self:flush_chip_test(err)
        low_cache:flush_queue(err)
    end

    -- 处理子 chips
    low_cache:process_child(function(r_chips)
        for _, r_chip in ipairs(r_chips) do
            r_chip:run(ctx)
        end
    end)
end

-- chip开始扫描
function chip:run(ctx)
    ctx:push(self)
    close_exec(function()
        ctx:pop()
    end, self.run_process, self, ctx)
end

local function secondary_cache_proces(self, ctx, secondary_cache)
    ctx:open_channels()
    -- 处理插件请求
    secondary_cache:process_plugin(function(obj)
        ctx:run_once(self.plugin_run_once, self, obj)
    end)
end

function chip:secondary_run_process(ctx)
    local secondary_cache = self.secondary_cache
    local ok, err = pcall(secondary_cache_proces, self, ctx, secondary_cache)
    if not ok then
        secondary_cache:flush_queue(err)
    end

    -- 处理子 chips
    secondary_cache:process_child(function(r_chips)
        for _, r_chip in ipairs(r_chips) do
            r_chip:secondary_run(ctx)
        end
    end)
end

function chip:secondary_run(ctx)
    ctx:push(self)
    close_exec(function()
        ctx:pop()
    end, self.secondary_run_process, self, ctx)
end

local function high_cache_proces(self, ctx, high_cache)
    ctx:open_channels()
    -- 处理写请求数据
    high_cache:process_write(function(obj)
        ctx:run_once(self.write_once, self, obj)
    end)

    -- 处理读请求数据
    high_cache:process_read(function(obj)
        ctx:run_once(self.read_once, self, obj)
    end)

    -- 处理插件请求
    high_cache:process_plugin(function(obj)
        ctx:run_once(self.plugin_run_once, self, obj)
    end)

    high_cache:process_cpld_upg(function(obj)
        ctx:run_once(self.cpld_upg_run, self, obj)
    end)
end

function chip:high_run_process(ctx)
    local high_cache = self.high_cache
    local ok, err = pcall(high_cache_proces, self, ctx, high_cache)
    if not ok then
        high_cache:flush_queue(err)
    end

    -- 处理子 chips
    high_cache:process_child(function(r_chips)
        for _, r_chip in ipairs(r_chips) do
            r_chip:high_run(ctx)
        end
    end)
end

-- 扫描高优先级任务
function chip:high_run(ctx)
    ctx:push(self)
    close_exec(function()
        ctx:pop()
    end, self.high_run_process, self, ctx)
end

function chip:open_channel(channel_id)
    if self.opened_channel_id == channel_id then
        return
    end

    self:close_channel()

    local ok, err = pcall(self.mux.open_channel, self.mux, channel_id)
    if not ok then
        error(s_format('chip: %s open channel(%d) failed, error: %s', self.name, channel_id, err), 0)
    end

    local delay = self.delay
    if delay and delay > 0 then
        log:info('chip: %s open channel(%d) delay: %d ms', self.name, channel_id, delay)
        utils.msleep(delay)
    end

    self.opened_channel_id = channel_id
end

function chip:close_channel()
    if self.opened_channel_id == -1 then
        return
    end

    local t_mux = self.mux
    local ok, err = pcall(t_mux.close_channel, t_mux, self.opened_channel_id)
    if not ok then
        log:hw_stream_error('chip: %s close channel failed, error: %s', self.name, err)
    end
    self.opened_channel_id = -1
end

function chip:wrap(input)
    local tmp_chip = self.l_chip
    local r_chip = self
    while tmp_chip do
        tmp_chip.protocol:wrap(input, tmp_chip, r_chip)
        r_chip = tmp_chip
        tmp_chip = tmp_chip.l_chip
    end
end

function chip:unwrap(data, input)
    local tmp_chip = self.l_chip
    local pre_chip_cnt = 0
    local pre_chip_list = {}
    while tmp_chip do
        pre_chip_cnt = pre_chip_cnt + 1
        pre_chip_list[pre_chip_cnt] = tmp_chip
        tmp_chip = tmp_chip.l_chip
    end

    for i = pre_chip_cnt, 1, -1 do
        local pre_chip = pre_chip_list[i]
        data = pre_chip.protocol:unwrap(data, input, pre_chip)
    end
    return data
end

-- chip读写方法,将读写请求保存到缓存
function chip:realtime_read(accessor_name, fetch, offset)
    local host_bus, high_cache, chip_name = self.host_bus, self.high_cache, self.name
    check_queue_is_over_limit(self, high_cache, 'read', chip_name, host_bus.name, self.accessible_status)
    local span = trace.start_span(
        'hwproxy.chip.realtime_read',
        trace.get_status() and { ['chip.name'] = chip_name, ['accessor.name'] = accessor_name } or nil
    )
    local accessor_obj = self.accessors[accessor_name]
    if not accessor_obj then
        log:error('chip: %s, accessor not exist, realtime read failed, accessor name: %s', chip_name, accessor_name)
        span:set_status('error', s_format('accessor %s not exist', accessor_name))
        span:finish()
        return
    end
    if offset then
        accessor_obj.offset = offset
    end
    fetch.access_obj = accessor_obj

    local read_args = object_pool_new(
        'read_args',
        accessor_obj.offset,
        accessor_obj.size,
        DEFAULT_MASK,
        accessor_obj.mask,
        accessor_obj.type,
        fetch,
        nil,
        nil,
        nil,
        accessor_name
    )

    high_cache:read(read_args)
    host_bus:notify_high_task(self)
    span:finish()
end

function chip:realtime_write(accessor_name, value, fetch)
    local host_bus, high_cache, chip_name = self.host_bus, self.high_cache, self.name
    check_queue_is_over_limit(self, high_cache, 'write', chip_name, host_bus.name, self.accessible_status)
    local span = trace.start_span(
        'hwproxy.chip.realtime_write',
        trace.get_status() and { ['chip.name'] = chip_name, ['accessor.name'] = accessor_name } or nil
    )
    local accessor_obj = self.accessors[accessor_name]
    if not accessor_obj then
        log:error('chip: %s accessor not exist, realtime write failed, accessor name: %s', chip_name, accessor_name)
        span:set_status('error', s_format('accessor %s not exist', accessor_name))
        span:finish()
        return
    end

    fetch.access_obj = accessor_obj
    local size = accessor_obj.size
    local write_args = object_pool_new(
        'write_args',
        accessor_obj.write_offset,
        size,
        accessor_obj.mask,
        accessor_obj.type,
        value:sub(1, size),
        fetch,
        nil,
        nil,
        nil,
        accessor_name
    )

    high_cache:write(write_args)
    host_bus:notify_high_task(self)
    span:finish()
end

function chip:bus_block_read(fetch, ctx, address, read_length)
    self:block_read(fetch, ctx, 0, read_length, address)
end

function chip:bus_block_write(fetch, ctx, address, data_in)
    self:block_write(fetch, ctx, 0, data_in, address)
end

function chip:bus_block_write_read(fetch, ctx, address, data_in, read_length)
    self:block_write_read(fetch, ctx, data_in, read_length, address)
end

function chip:block_read(fetch, ctx, offset, length, address)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'read', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local read_args = object_pool_new(
        'read_args',
        offset,
        length,
        DEFAULT_MASK,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        fetch,
        true,
        nil,
        self.ismonitored or nil,
        requestor,
        address
    )
    high_cache:read(read_args, requestor == DISCOVERY_REQUESTOR)
    host_bus:notify_high_task(self)
end

function chip:block_read_with_low_priority(fetch, ctx, offset, length)
    local host_bus, low_cache = self.host_bus, self.low_cache
    check_queue_is_over_limit(self, low_cache, 'read', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local read_args = object_pool_new(
        'read_args',
        offset,
        length,
        DEFAULT_MASK,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        fetch,
        true,
        nil,
        self.ismonitored or nil,
        requestor
    )

    low_cache:read(read_args)
    host_bus:notify_high_task(self)
end

function chip:block_write(fetch, ctx, offset, data_in, address)
    local host_bus, high_cache, chip_name = self.host_bus, self.high_cache, self.name
    check_queue_is_over_limit(self, high_cache, 'write', chip_name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local write_args = object_pool_new(
        'write_args',
        offset,
        #data_in,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        data_in,
        fetch,
        true,
        nil,
        nil,
        nil,
        self.ismonitored or nil,
        requestor,
        address
    )

    high_cache:write(write_args)
    host_bus:notify_high_task(self)
end

function chip:block_batch_write(fetch, ctx, write_data)
    local host_bus, high_cache, chip_name = self.host_bus, self.high_cache, self.name
    check_queue_is_over_limit(self, high_cache, 'write', chip_name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local batch_write_args = object_pool_new('batch_write_args', write_data, fetch, self.ismonitored or nil, requestor)

    high_cache:write(batch_write_args)
    host_bus:notify_high_task(self)
    local info = {}
    for i, v in ipairs(write_data) do
        info[i] = {}
        info[i].offset = v.Offset or v[1]
        info[i].length = v.InData and #v.InData or #v[2]
    end

    log:notice('Chip %s block_batch_write finish, %s, requestor: %s', chip_name, cjson_encode(info), requestor)
end

function chip:block_write_read(fetch, ctx, data_in, read_length, address)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'read', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'

    local read_args = object_pool_new(
        'read_args',
        EXTEND_READ_OFFSET,
        read_length,
        DEFAULT_MASK,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        fetch,
        true,
        data_in,
        self.ismonitored or nil,
        requestor,
        address
    )

    high_cache:read(read_args)
    host_bus:notify_high_task(self)
end

function chip:block_write_read_by_protocol(fetch, ctx, data_in, read_length, protocol)
    local host_bus, high_cache, chip_name = self.host_bus, self.high_cache, self.name
    local bus_name = host_bus.name
    check_queue_is_over_limit(self, high_cache, 'read', chip_name, bus_name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'

    -- 没有传入protocol参数
    if not protocol then
        fetch.result = false
        fetch.error = 'the protocol flag parameter is not transferred'
        return
    end

    -- 如果传入Protocol参数,但是值不对
    if protocol ~= PROTOCOL_SMBUS and protocol ~= PROTOCOL_MCTP_OVER_SMC then
        fetch.result = false
        fetch.error = 'the protocol parameter value(' .. protocol .. ') is incorrect.'
        return
    end

    -- 如果是非i2c设备,直接报错
    if not s_match(bus_name, '^I2c') then
        fetch.result = false
        fetch.error = 'this parameter smbus only supports devices that mounted to the I2c bus'
        return
    end
    local smbus_write_read_args = object_pool_new(
        'smbus_write_read_args',
        read_length,
        DEFAULT_MASK,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        fetch,
        true,
        data_in,
        chip_name,
        protocol,
        ctx.is_trace or nil,
        requestor
    )
    log:debug(
        'chip %s start smbus write_read. protocol: %s host_bus.name: %s',
        chip_name,
        smbus_write_read_args.protocol_flag,
        bus_name
    )
    high_cache:read(smbus_write_read_args)
    host_bus:notify_high_task(self)
end

function chip:block_combo_write_read(fetch, ctx, write_offset, data_in, read_offset, read_length)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'write', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local write_args = object_pool_new(
        'write_args',
        write_offset,
        #data_in,
        BLOCK_MASK,
        BLOCK_ACCESS_TYPE,
        data_in,
        fetch,
        nil,
        true,
        read_offset,
        read_length,
        self.ismonitored or nil,
        requestor
    )

    high_cache:write(write_args)
    host_bus:notify_high_task(self)
end

function chip:bit_read(fetch, ctx, offset, length, mask)
    local low_cache = self.low_cache
    check_queue_is_over_limit(self, low_cache, 'read', self.name, self.host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local read_args = object_pool_new(
        'read_args',
        offset,
        length,
        DEFAULT_MASK,
        mask,
        BIT_ACCESS_TYPE,
        fetch,
        nil,
        nil,
        self.ismonitored or nil,
        requestor
    )

    low_cache:read(read_args)
end

function chip:bit_write(fetch, ctx, offset, length, mask, data_in)
    local low_cache = self.low_cache
    check_queue_is_over_limit(self, low_cache, 'write', self.name, self.host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local write_args = object_pool_new(
        'write_args',
        offset,
        length,
        mask,
        BIT_ACCESS_TYPE,
        data_in,
        fetch,
        nil,
        nil,
        nil,
        nil,
        self.ismonitored or nil,
        requestor
    )

    low_cache:write(write_args)
end

function chip:chip_test(fetch, test_para)
    check_accessible_status(self.accessible_status, self.name, self)
    self.chip_test_paras = test_para
    local chip_test_fetches = self.chip_test_fetches
    if not chip_test_fetches then
        chip_test_fetches = {}
        self.chip_test_fetches = chip_test_fetches
    end
    fetch.unexecuted = true
    chip_test_fetches[#chip_test_fetches + 1] = fetch
    self.low_cache:notify_parent()
end

function chip:plugin_request(fetch, plugin_func, control_params, ctx)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local host_bus = self.host_bus
    if control_params and control_params.Priority and control_params.Priority == PRIORITY_SECONDARY then
        local secondary_cache = self.secondary_cache
        check_queue_is_over_limit(self, secondary_cache, 'plugin', self.name, host_bus.name, self.accessible_status)
        secondary_cache:plugin_request({ fetches = { fetch }, run = plugin_func }, requestor == DISCOVERY_REQUESTOR)
        host_bus:notify_secondary_task(self)
    else
        local high_cache = self.high_cache
        check_queue_is_over_limit(self, high_cache, 'plugin', self.name, host_bus.name, self.accessible_status)
        high_cache:plugin_request({ fetches = { fetch }, run = plugin_func }, requestor == DISCOVERY_REQUESTOR)
        host_bus:notify_high_task(self)
    end
end

function chip:cpld_upg_request(fetch)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'cpld_upg', self.name, host_bus.name, self.accessible_status)
    high_cache:cpld_upg_request({ fetch = fetch })
    host_bus:notify_high_task(self)
end

function chip:inner_block_combo_write_read(_, write_offset, data_in, read_offset, read_length)
    local fetch = object_pool_new('fetch', empty_cb, nil, false, nil, {})
    self:block_combo_write_read(fetch, {}, write_offset, data_in, read_offset, read_length)
    return wait_hw_access(fetch)
end

function chip:flash_raw_write(fetch, ctx, data_in)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'write', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local write_args = object_pool_new(
        'write_args',
        nil,
        #data_in,
        BLOCK_MASK,
        FLASH_WRITE_ACCESS_TYPE,
        data_in,
        fetch,
        true,
        nil,
        nil,
        nil,
        self.ismonitored or nil,
        requestor,
        nil
    )

    high_cache:write(write_args)
    host_bus:notify_high_task(self)
end

function chip:flash_raw_write_read(fetch, ctx, length, data_in)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'read', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local read_args = object_pool_new(
        'read_args',
        EXTEND_READ_OFFSET,
        length,
        DEFAULT_MASK,
        BLOCK_MASK,
        FLASH_WRITEREAD_ACCESS_TYPE,
        fetch,
        true,
        data_in,
        self.ismonitored or nil,
        requestor,
        nil
    )
    high_cache:read(read_args, false)
    host_bus:notify_high_task(self)
end

function chip:flash_erase(fetch, ctx, offset, erase_type)
    local host_bus, high_cache = self.host_bus, self.high_cache
    check_queue_is_over_limit(self, high_cache, 'write', self.name, host_bus.name, self.accessible_status)
    local requestor = ctx and ctx.Requestor or 'Unknown'
    local write_args = object_pool_new(
        'write_args',
        offset,
        nil,
        BLOCK_MASK,
        FLASH_ERASE_ACCESS_TYPE,
        erase_type,
        fetch,
        true,
        nil,
        nil,
        nil,
        self.ismonitored or nil,
        requestor,
        nil
    )

    high_cache:write(write_args)
    host_bus:notify_high_task(self)
end

local MID_BRANCH = '├─'
local LAST_BRANCH = '└─'
local MID_INDENT = '│ '
local LAST_INDENT = '  '
function chip:dump_topology(prefix, last_chip, buffer)
    local root_call = not buffer
    buffer = buffer or {}

    local branch = last_chip and LAST_BRANCH or MID_BRANCH
    buffer[#buffer + 1] = prefix .. branch .. self.name

    local log_channels = {}

    for channel_id, r_chips in pairs(self.r_chips) do
        log_channels[#log_channels + 1] = {
            chips = r_chips,
            channel = channel_id,
        }
    end

    table.sort(log_channels, function(a, b)
        return a.channel < b.channel
    end)

    local channel_count = #log_channels
    local indent = last_chip and LAST_INDENT or MID_INDENT
    local next_prefix = prefix .. indent

    for k = 1, channel_count do
        local v = log_channels[k]
        local last_channel = (k == channel_count)

        buffer[#buffer + 1] = next_prefix .. (last_channel and LAST_BRANCH or MID_BRANCH) .. 'Channel_' .. v.channel

        local chips = v.chips
        local chip_count = #chips

        local sub_prefix = next_prefix .. (last_channel and LAST_INDENT or MID_INDENT)

        for i = 1, chip_count do
            chips[i]:dump_topology(sub_prefix, i == chip_count, buffer)
        end
    end

    if root_call then
        return table.concat(buffer, '\n')
    end
end

function chip:dump_aggregate_info()
    local dump_str = {}
    for _, smc_dfx_info_obj in pairs(self.smc_dfx_infos or {}) do
        dump_str[#dump_str + 1] = smc_dfx_info_obj:dump()
    end
    for _, aggregate_obj in pairs(self.aggregate_sections or {}) do
        dump_str[#dump_str + 1] = aggregate_obj:dump()
    end
    return #dump_str ~= 0 and t_concat(dump_str) or nil
end

function chip:dump_scanners_info()
    local dump_scanners = {}
    for _, scanner_obj in pairs(self.scanners or {}) do
        local temp = scanner_obj:dump()
        for key, _ in pairs(temp) do
            temp[key].chip_name = self.name
        end
        dump_scanners[#dump_scanners + 1] = temp
    end
    return #dump_scanners ~= 0 and dump_scanners or nil
end

function chip:dump_chip_access_info()
    local dump_chip = {}
    local consumed_time = vos.vos_tick_get() - self.start_write_read_time
    dump_chip[#dump_chip + 1] = {
        chip_name = self.name,
        write_success_count = self.write_success_count,
        write_failed_count = self.write_fail_count,
        read_success_count = self.read_success_count,
        read_failed_count = self.read_fail_count,
        chip_write_read_time = consumed_time,
        err_table = self.err_table or {},
    }
    return dump_chip
end

function chip:update_access_status(status, smc_completion_code)
    -- 当业务设置过健康状态后,就不再更新健康状态
    if self.is_health_status_modified then
        return
    end

    local tree_obj = self.tree_obj
    -- smc器件cc不为0都是抛错到上层, 但是只有cc等于4是硬件问题, cc为其他值应忽略
    if not tree_obj or status == tree_obj.HealthStatus or (smc_completion_code and smc_completion_code ~= 4) then
        return
    end

    -- 器件访问连续失败3次才去更新状态为失败
    if status == ACCESS_FAILED and self.consec_failed_access_cnt < 2 then
        self.consec_failed_access_cnt = self.consec_failed_access_cnt + 1
        return
    end

    self.consec_failed_access_cnt = 0
    tree_obj.HealthStatus = status
    tree_obj.HealthStatusValidity = true
    -- 将合并的器件状态统一刷新
    for _, v in ipairs(self.tree_objs) do
        tree_obj = v.tree_obj
        tree_obj.HealthStatus = status
        tree_obj.HealthStatusValidity = true
    end
end

return chip