/* 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.
 */

#include <bcal/uart.h>

#include <algorithm>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <climits>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <map>
#include <memory>
#include <mutex>
#include <poll.h>
#include <stdexcept>
#include <string>
#include <sys/eventfd.h>
#include <system_error>
#include <termios.h>
#include <unistd.h>

namespace BCAL_UART_ASPEED {
using namespace bcal;
using namespace BCAL_DRIVER_UART;

namespace {

constexpr const char* DRIVER_VERSION = "bcal_uart_aspeed v1.0.0 (ttyS termios)";

/* strerror 返回共享静态缓冲区,多线程不安全;message() 每次返回独立 string。 */
string_t error_text(int error)
{
    return std::generic_category().message(error);
}

/* index 即 /dev/ttyS<n>;物理 UART 为 serial0~12,serial13~16 是 VUART,不归本驱动管理。 */
constexpr int32_t MAX_UART_INDEX = 12;
constexpr uint32_t MAX_IO_LEN_EXCLUSIVE = 1024 * 1024; /* 长度必须小于该值(1 MiB) */

/* 8250 分频关系:baud = uartclk / (16 * divisor);与标准速率偏差在此范围内归一到标准值 */
constexpr uint64_t UART_CLK_DIVISOR  = 16;
constexpr uint64_t BAUD_SNAP_PERCENT = 2;

constexpr size_t SYSFS_VALUE_MAX = 64; /* sysfs 单值属性都很短,64 字节足够 */

/* 敏感词规则 openubmc-pv10 会把“字母+5位数字”误判,用 token 拼接生成别名以免保留扫描豁免。 */
#define UART_BAUD_CONST(rate) B##rate
constexpr speed_t UART_BAUD_19200 = UART_BAUD_CONST(19200);
constexpr speed_t UART_BAUD_38400 = UART_BAUD_CONST(38400);
constexpr speed_t UART_BAUD_57600 = UART_BAUD_CONST(57600);
#undef UART_BAUD_CONST

const std::map<uint32_t, speed_t> g_baud_to_speed = {
    {1200, B1200},     {1800, B1800},            {2400, B2400},            {4800, B4800},
    {9600, B9600},     {19200, UART_BAUD_19200}, {38400, UART_BAUD_38400}, {57600, UART_BAUD_57600},
    {115200, B115200}, {230400, B230400},        {460800, B460800},        {921600, B921600},
};

const std::map<uint8_t, tcflag_t> g_data_bits = {{5, CS5}, {6, CS6}, {7, CS7}, {8, CS8}};

const std::map<char, tcflag_t> g_parity_flags = {
    {'N', 0}, {'E', PARENB}, {'O', PARENB | PARODD}, {'M', PARENB | PARODD | CMSPAR}, {'S', PARENB | CMSPAR},
};

speed_t baud_to_speed(uint32_t baud)
{
    auto it = g_baud_to_speed.find(baud);
    return it == g_baud_to_speed.end() ? 0 : it->second;
}

/* 读取 sysfs 中的单个数值(十进制或 0x 十六进制),失败抛异常。 */
uint32_t read_uint_file(const string_t& path)
{
    const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
    if (fd < 0) {
        const int error = errno;
        throw std::runtime_error("open " + path + " failed: " + error_text(error));
    }
    char buffer[SYSFS_VALUE_MAX];
    ssize_t n;
    do {
        errno = 0; /* n == 0(空文件)时 errno 不会被赋值,必须每轮清零 */
        n     = ::read(fd, buffer, sizeof(buffer) - 1);
    } while (n < 0 && errno == EINTR);
    const int error = n < 0 ? errno : 0;
    ::close(fd);
    if (n <= 0) {
        if (error != 0) {
            throw std::runtime_error("read " + path + " failed: " + error_text(error));
        }
        throw std::runtime_error("read " + path + " failed: empty");
    }
    buffer[n] = '\0';
    char*               end   = nullptr;
    errno                     = 0;
    const unsigned long value = std::strtoul(buffer, &end, 0);
    if (errno != 0 || end == buffer) {
        throw std::runtime_error("invalid numeric value in " + path);
    }
    return static_cast<uint32_t>(value);
}

/* termios 里的速率可能不在表内,此时不能返回 0 冒充有效波特率。 */
uint32_t baud_from_termios(const termios& term)
{
    const speed_t speed = ::cfgetispeed(&term);
    for (const auto& item : g_baud_to_speed) {
        if (item.second == speed) {
            return item.first;
        }
    }
    throw std::runtime_error("termios reports an unsupported UART baud rate");
}

uint8_t data_bits_from_termios(const termios& term)
{
    for (const auto& item : g_data_bits) {
        if ((term.c_cflag & CSIZE) == item.second) {
            return item.first;
        }
    }
    throw std::runtime_error("invalid UART data bits in termios");
}

char parity_from_termios(const termios& term)
{
    if ((term.c_cflag & PARENB) == 0) {
        return 'N';
    }
    if ((term.c_cflag & CMSPAR) != 0) {
        return (term.c_cflag & PARODD) != 0 ? 'M' : 'S';
    }
    return (term.c_cflag & PARODD) != 0 ? 'O' : 'E';
}

} // namespace

class UartImpl : public Uart {
public:
    explicit UartImpl(int32_t index);
    ~UartImpl() override;

    void     init(void* args, uint32_t size) override;
    void     lock(void) override;
    void     unlock(void) override;
    string_t get_version(void) override;
    string_t get_driver_name(void) const override;
    int32_t  control(uint32_t cmd, void* args_in, void* args_out) override;

    void     open(void) override;
    void     close(void) override;
    string_t read(uint32_t len) override;
    string_t select_read(uint32_t len, uint32_t timeout) override;
    int32_t  write(const string_view_t& val) override;
    void     send_break(int32_t duration) override;
    void     set_baud_rate(uint32_t baud) override;
    void     set_parity(char parity) override;
    void     set_data_bits(uint8_t bits) override;
    void     set_stop_bits(uint8_t bits) override;
    uint32_t get_host_baud_rate(void) override;

private:
    class InFlightGuard; /* 在途调用守卫:析构需等已登记的调用全部退出后才能释放对象 */

    /* 一次 open 对应一个会话:fd 与 wake eventfd 在最后一个引用释放时关闭,fd 编号不会被复用。 */
    struct Session {
        Session(int data_fd, int wake) : fd(data_fd), wake_fd(wake) {}
        Session(const Session&)            = delete;
        Session& operator=(const Session&) = delete;
        ~Session();

        int fd;
        int wake_fd;
    };

    std::shared_ptr<Session>     require_session() const;
    std::shared_ptr<Session>     take_session();
    std::shared_ptr<Session>     create_session() const;
    std::shared_ptr<Session>     open_once(bool* created);
    std::unique_lock<std::mutex> lock_if_current(const std::shared_ptr<Session>& session) const;
    std::unique_lock<std::mutex> lock_or_throw(const std::shared_ptr<Session>& session, const char* what) const;
    void                         wake_session(const std::shared_ptr<Session>& session) const;
    void                         close_if_current(const std::shared_ptr<Session>& session);
    void                         check_chan(uint8_t chan, const char* cmd_name) const;
    bool                         apply_format(const std::shared_ptr<Session>& session, speed_t speed);
    void                         apply_baud_rate(uint32_t baud);
    bool                         set_raw_mode(int fd) const;
    termios                      get_termios(int fd) const;
    void                         apply_termios(int fd, const termios& term) const;
    void                         verify_baud_applied(int fd, speed_t speed) const;
    uint32_t                     get_baud_from_reg(int fd) const;
    string_t                     read_from(int fd, uint32_t len) const;

    int32_t         m_index;
    std::string     m_path;
    std::mutex      m_hardware_mutex; /* 只供 lock()/unlock() 使用;跨进程需调用方协调 */
    /* 换会话与按次操作都在 m_session_mutex 下;锁内确认 m_session == session 后操作不会落到新会话。 */
    mutable std::mutex       m_session_mutex;
    std::shared_ptr<Session> m_session;
    std::mutex              m_life_mutex; /* m_inflight 为在途调用数,m_closing 置位后不再登记/发布会话 */
    std::condition_variable m_drained;
    uint32_t                m_inflight{0};
    std::atomic<bool>       m_closing{false};
};

class UartImpl::InFlightGuard {
public:
    explicit InFlightGuard(UartImpl& self) : m_self(self)
    {
        std::lock_guard<std::mutex> guard(m_self.m_life_mutex);
        if (!m_self.m_closing.load()) {
            ++m_self.m_inflight;
            m_registered = true;
        }
    }

    ~InFlightGuard()
    {
        if (!m_registered) {
            return;
        }
        std::lock_guard<std::mutex> guard(m_self.m_life_mutex);
        if (--m_self.m_inflight == 0) {
            m_self.m_drained.notify_all();
        }
    }

    bool registered() const
    {
        return m_registered;
    }

    InFlightGuard(const InFlightGuard&) = delete; /* 禁止拷贝:否则 m_inflight 会被重复递减 */
    InFlightGuard& operator=(const InFlightGuard&) = delete;

private:
    UartImpl& m_self;
    bool      m_registered{false};
};

UartImpl::Session::~Session()
{
    if (fd >= 0) {
        ::close(fd);
    }
    if (wake_fd >= 0) {
        ::close(wake_fd);
    }
}

UartImpl::UartImpl(int32_t index) : m_index(index)
{
    if (index < 0 || index > MAX_UART_INDEX) {
        throw std::runtime_error("UART index " + std::to_string(index) + " is out of range(0-" +
                                 std::to_string(MAX_UART_INDEX) + ")");
    }
    m_path = "/dev/ttyS" + std::to_string(index);
}

UartImpl::~UartImpl()
{
    /* 顺序不能反:先置 m_closing 再摘会话并唤醒;open() 看到置位后不再发布新会话,
     * 否则已登记的 open 可能在摘链后装入新会话,它的 select_read 无人唤醒,drain 会挂住。 */
    {
        std::lock_guard<std::mutex> guard(m_life_mutex);
        m_closing.store(true);
    }
    auto session = take_session();
    wake_session(session);
    /* 在途 write/send_break 可能长期阻塞;必须无超时等待,超时后继续析构会访问已释放对象(UAF)。 */
    {
        std::unique_lock<std::mutex> guard(m_life_mutex);
        m_drained.wait(guard, [this] { return m_inflight == 0; });
    }
}

void UartImpl::init(void* args, uint32_t size)
{
    (void)args;
    (void)size;
}

void UartImpl::lock(void)
{
    m_hardware_mutex.lock();
}

void UartImpl::unlock(void)
{
    m_hardware_mutex.unlock();
}

string_t UartImpl::get_version(void)
{
    return DRIVER_VERSION;
}

string_t UartImpl::get_driver_name(void) const
{
    return "uart";
}

void UartImpl::check_chan(uint8_t chan, const char* cmd_name) const
{
    if (chan != static_cast<uint8_t>(m_index)) {
        throw std::runtime_error(std::string("UART ") + cmd_name + " chan " + std::to_string(chan) +
                                 " does not match driver index " + std::to_string(m_index));
    }
}

bool UartImpl::set_raw_mode(int fd) const
{
    termios term{};
    if (::tcgetattr(fd, &term) != 0) {
        return false;
    }
    ::cfmakeraw(&term);
    term.c_cflag |= CLOCAL | CREAD;
    term.c_cc[VMIN]  = 0;
    term.c_cc[VTIME] = 0;
    return ::tcsetattr(fd, TCSANOW, &term) == 0;
}

std::shared_ptr<UartImpl::Session> UartImpl::require_session() const
{
    std::lock_guard<std::mutex> guard(m_session_mutex);
    if (m_closing.load() || !m_session) {
        throw std::runtime_error("UART " + std::to_string(m_index) + " is not open");
    }
    return m_session;
}

/* close()/析构只在锁内摘链;Session 析构(::close 可能等待发送完成)放到锁外执行。 */
std::shared_ptr<UartImpl::Session> UartImpl::take_session()
{
    std::lock_guard<std::mutex> guard(m_session_mutex);
    return std::move(m_session);
}

/* 校验 session 仍是当前会话并移交会话锁;未持锁返回表示会话已切换。 */
std::unique_lock<std::mutex> UartImpl::lock_if_current(const std::shared_ptr<Session>& session) const
{
    std::unique_lock<std::mutex> lock(m_session_mutex);
    if (m_session != session) {
        lock.unlock();
    }
    return lock;
}

/* setter 是 void 接口:会话在调用期间被切走时必须抛异常,不能静默假成功。 */
std::unique_lock<std::mutex> UartImpl::lock_or_throw(const std::shared_ptr<Session>& session, const char* what) const
{
    auto lock = lock_if_current(session);
    if (!lock) {
        throw std::runtime_error("UART " + std::to_string(m_index) + " session was closed during " + what);
    }
    return lock;
}

/* 写会话专属 eventfd 唤醒阻塞在该会话 poll() 上的线程;EINTR 重试,其余失败记录告警。 */
void UartImpl::wake_session(const std::shared_ptr<Session>& session) const
{
    if (!session || session->wake_fd < 0) {
        return;
    }
    const uint64_t value = 1;
    while (::write(session->wake_fd, &value, sizeof(value)) < 0) {
        if (errno == EINTR) {
            continue;
        }
        const int error = errno;
        std::fprintf(stderr, "[WARN] uart: write session wake eventfd failed: %s\n", error_text(error).c_str());
        return;
    }
}

/* 打开设备并创建会话;调用方不能持 m_session_mutex,失败由 Session 析构回收 fd/eventfd。 */
std::shared_ptr<UartImpl::Session> UartImpl::create_session() const
{
    auto session = std::make_shared<Session>(-1, -1);

    /* O_NDELAY 避免 open 阻塞在载波检测上;随后必须切回阻塞模式,否则 read 始终立即返回空。 */
    const int fd = ::open(m_path.c_str(), O_RDWR | O_NOCTTY | O_NDELAY | O_CLOEXEC);
    if (fd < 0) {
        const int error = errno;
        throw std::runtime_error("open " + m_path + " failed: " + error_text(error));
    }
    session->fd = fd; /* 交给 session 管理:后续任何异常都会关掉它 */
    if (::fcntl(fd, F_SETFL, 0) != 0) {
        const int error = errno;
        throw std::runtime_error("set blocking mode on " + m_path + " failed: " + error_text(error));
    }
    if (!set_raw_mode(fd)) {
        const int error = errno;
        throw std::runtime_error("configure raw mode on " + m_path + " failed: " + error_text(error));
    }
    const int wake_fd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
    if (wake_fd < 0) {
        const int error = errno;
        throw std::runtime_error("eventfd for UART session wakeup failed: " + error_text(error));
    }
    session->wake_fd = wake_fd;
    return session;
}

void UartImpl::open(void)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    (void)open_once(nullptr);
}

/* 返回当前或新建的会话;created 表示本次新建;对象正在析构时返回空。 */
std::shared_ptr<UartImpl::Session> UartImpl::open_once(bool* created)
{
    if (created != nullptr) {
        *created = false;
    }

    {
        std::lock_guard<std::mutex> guard(m_session_mutex);
        if (m_closing.load()) {
            return nullptr;
        }
        if (m_session) {
            return m_session;
        }
    }

    auto session = create_session(); /* 不持锁:并发 open 多创建的会话会在二次检查中丢弃并在锁外关闭 */

    {
        std::lock_guard<std::mutex> guard(m_session_mutex);
        /* 先检查 m_closing 再发布:置位后不再发布新会话,析构摘链后不会再有新会话漏网。 */
        if (m_closing.load()) {
            return nullptr;
        }
        if (m_session) {
            return m_session;
        }
        m_session = session;
        if (created != nullptr) {
            *created = true;
        }
        return session;
    }
}

void UartImpl::close_if_current(const std::shared_ptr<Session>& session)
{
    std::shared_ptr<Session> detached;
    {
        std::lock_guard<std::mutex> guard(m_session_mutex);
        if (m_session != session) {
            return;
        }
        detached = std::move(m_session);
    }
    wake_session(detached); /* 唤醒可能已拿到这个会话的 select_read */
}

void UartImpl::close(void)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    auto session = take_session();
    wake_session(session); /* 锁外写 eventfd,避免唤醒操作落在会话锁内 */
    /* session 在此释放:无在途引用则立即关 fd;阻塞中的 write 会延长关闭时间,close 非同步释放。 */
}

termios UartImpl::get_termios(int fd) const
{
    termios term{};
    if (::tcgetattr(fd, &term) != 0) {
        const int error = errno;
        throw std::runtime_error("tcgetattr " + m_path + " failed: " + error_text(error));
    }
    return term;
}

void UartImpl::apply_termios(int fd, const termios& term) const
{
    if (::tcsetattr(fd, TCSANOW, &term) != 0) {
        const int error = errno;
        throw std::runtime_error("tcsetattr " + m_path + " failed: " + error_text(error));
    }
}

/* 内核在速率超出 UART 时钟能力时不报错而保留旧 termios,这里回读确认,避免把“没生效”当成功。 */
void UartImpl::verify_baud_applied(int fd, speed_t speed) const
{
    termios applied{};
    if (::tcgetattr(fd, &applied) != 0) {
        const int error = errno;
        throw std::runtime_error("tcgetattr " + m_path + " failed: " + error_text(error));
    }
    if (::cfgetispeed(&applied) == speed && ::cfgetospeed(&applied) == speed) {
        return;
    }
    throw std::runtime_error("UART " + m_path +
                             " baud rate was not applied: kernel kept the previous rate, the UART clock may be "
                             "too low for this rate (e.g. 24MHz/13 => max 115200)");
}

/* 8N1 + 指定速率整份下发,不继承系统配置;speed 已校验。返回 false 表示会话已切换。 */
bool UartImpl::apply_format(const std::shared_ptr<Session>& session, speed_t speed)
{
    auto lock = lock_if_current(session);
    if (!lock) {
        return false;
    }
    const int fd = session->fd;

    termios term{};
    term.c_cflag |= CLOCAL | CREAD | CS8;
    term.c_cc[VMIN]  = 0;
    term.c_cc[VTIME] = 0;
    (void)::cfsetispeed(&term, speed);
    (void)::cfsetospeed(&term, speed);

    (void)::tcflush(fd, TCIFLUSH);
    apply_termios(fd, term);
    verify_baud_applied(fd, speed);
    return true;
}

/* 单次最多读 4 KiB;len 更大时返回短读,调用方按字节流继续读。 */
string_t UartImpl::read_from(int fd, uint32_t len) const
{
    char         chunk[4096];
    const size_t want = std::min(sizeof(chunk), static_cast<size_t>(len));
    ssize_t      count;
    do {
        count = ::read(fd, chunk, want);
    } while (count < 0 && errno == EINTR);
    if (count < 0) {
        const int error = errno;
        throw std::runtime_error("read " + m_path + " failed: " + error_text(error));
    }
    return string_t(chunk, static_cast<size_t>(count));
}

string_t UartImpl::read(uint32_t len)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return {};
    }
    if (len == 0) {
        return {};
    }
    if (len >= MAX_IO_LEN_EXCLUSIVE) {
        throw std::runtime_error("UART read length is too large: " + std::to_string(len));
    }

    auto session = require_session();
    /* 校验与 read 在同一把会话锁内:close→open 无法插入;VMIN=0 保证分块读不会阻塞。 */
    auto lock = lock_if_current(session);
    if (!lock) {
        return {};
    }
    return read_from(session->fd, len);
}

string_t UartImpl::select_read(uint32_t len, uint32_t timeout)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return {};
    }
    if (len == 0) {
        return {};
    }
    if (len >= MAX_IO_LEN_EXCLUSIVE) {
        throw std::runtime_error("UART select_read length is too large: " + std::to_string(len));
    }

    /* 会话引用保证等待期间 fd 不会被关闭/复用;close()/析构写本会话 wake_fd 打断 poll。 */
    auto       session  = require_session();
    const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
    for (;;) {
        int wait_ms = 0;
        if (timeout != 0) {
            const auto now = std::chrono::steady_clock::now();
            if (now >= deadline) {
                return {};
            }
            const auto left_us = std::chrono::duration_cast<std::chrono::microseconds>(deadline - now).count();
            /* 向上取整防提前返回;poll 的 int 毫秒参数按 INT_MAX 截断 */
            wait_ms = static_cast<int>(std::min<int64_t>((left_us + 999) / 1000, INT_MAX));
        }

        pollfd fds[2] = {{session->fd, POLLIN, 0}, {session->wake_fd, POLLIN, 0}};

        const int ret = ::poll(fds, 2, wait_ms);
        if (ret < 0) {
            if (errno == EINTR) {
                continue; /* 信号打断不算超时,按剩余时间重试 */
            }
            const int error = errno;
            throw std::runtime_error("poll " + m_path + " failed: " + error_text(error));
        }
        /* 唤醒 fd 任何事件都表示会话关停;新会话有自己的 eventfd,不存在陈旧唤醒 */
        if (fds[1].revents != 0) {
            return {};
        }
        if (ret == 0) { /* poll 的毫秒参数被 INT_MAX 截断时会先到期;未到 deadline 继续等 */
            if (timeout == 0 || std::chrono::steady_clock::now() >= deadline) {
                return {};
            }
            continue;
        }
        if (fds[0].revents == 0 || (fds[0].revents & POLLNVAL) != 0) {
            return {};
        }
        /* 校验与 read 在会话锁内;0 字节且未到 deadline 时继续等(数据可能被并发读者抢走)。 */
        auto lock = lock_if_current(session);
        if (!lock) {
            return {};
        }
        string_t data = read_from(session->fd, len);
        if (!data.empty() || (fds[0].revents & (POLLHUP | POLLERR)) != 0 ||
            timeout == 0 || std::chrono::steady_clock::now() >= deadline) {
            return data;
        }
    }
}

int32_t UartImpl::write(const string_view_t& val)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return -1;
    }
    auto      session = require_session();
    const int fd      = session->fd;
    /* read(0) 是“不读”的 no-op;write("") 是无效入参,按设计文档 F04 在入口拒绝。 */
    if (val.empty()) {
        throw std::runtime_error("UART write data is empty");
    }
    if (val.size() >= MAX_IO_LEN_EXCLUSIVE) {
        throw std::runtime_error("UART write length is too large: " + std::to_string(val.size()));
    }
    /* 只持会话引用不持会话锁:写可能被流控阻塞,持锁会拖住 close()/open();TX 无法按会话严格隔离。 */
    /* 阻塞 tty 在内核缓冲区满或信号打断时也会短写,必须循环写满,否则数据被静默丢弃 */
    size_t written = 0;
    while (written < val.size()) {
        const ssize_t count = ::write(fd, val.data() + written, val.size() - written);
        if (count < 0) {
            if (errno == EINTR) {
                continue;
            }
            const int error = errno;
            throw std::runtime_error("write " + m_path + " failed: " + error_text(error));
        }
        if (count == 0) {
            throw std::runtime_error("write " + m_path + " returned 0");
        }
        written += static_cast<size_t>(count);
    }
    return 0;
}

void UartImpl::send_break(int32_t duration)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    /* duration <= 0 是“不发 break”,不需要已 open;0 会退化成内核固定 250ms,无法表达 */
    if (duration <= 0) {
        return;
    }

    /* 只持有会话引用:tcsendbreak() 可能阻塞,持会话锁会拖住 close()/open()。 */
    auto session = require_session();
    /* duration 单位 ms;glibc 按 (duration+99)/100 转成 TCSBRKP 的 100ms 单位,
     * 内核再按该值 × 100ms 发送,因此最小 100ms,必须传毫秒原值。 */
    if (::tcsendbreak(session->fd, duration) != 0) {
        const int error = errno;
        throw std::runtime_error("send break on " + m_path + " failed: " + error_text(error));
    }
}

void UartImpl::set_baud_rate(uint32_t baud)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    apply_baud_rate(baud);
}

/* 供 control(CMD_UPDATE_BAUD_V2) 复用:外层 control 已登记,不能再套一层 InFlightGuard。 */
void UartImpl::apply_baud_rate(uint32_t baud)
{
    const speed_t speed = baud_to_speed(baud);
    if (speed == 0) {
        throw std::runtime_error("unsupported UART baud rate: " + std::to_string(baud));
    }
    auto session = require_session();
    auto lock = lock_or_throw(session, "set_baud_rate");
    const int fd   = session->fd;
    termios   term = get_termios(fd);
    if (::cfgetispeed(&term) == speed && ::cfgetospeed(&term) == speed) {
        return;
    }
    (void)::cfsetispeed(&term, speed);
    (void)::cfsetospeed(&term, speed);
    apply_termios(fd, term);
    verify_baud_applied(fd, speed);
}

void UartImpl::set_parity(char parity)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    const auto flags = g_parity_flags.find(parity);
    if (flags == g_parity_flags.end()) {
        throw std::runtime_error("invalid UART parity: " + std::string(1, parity));
    }
    auto session = require_session();
    auto lock = lock_or_throw(session, "set_parity");
    const int fd   = session->fd;
    termios   term = get_termios(fd);
    /* ISTRIP 会截掉第 8 位,必须清零;校验检查由 INPCK 负责,先清相关位避免 CMSPAR 残留。 */
    term.c_cflag &= ~(PARENB | PARODD | CMSPAR);
    term.c_cflag |= flags->second;
    term.c_iflag &= ~ISTRIP;
    if (parity == 'N') {
        term.c_iflag &= ~INPCK;
    } else {
        term.c_iflag |= INPCK;
    }
    apply_termios(fd, term);
}

void UartImpl::set_data_bits(uint8_t bits)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    const auto size = g_data_bits.find(bits);
    if (size == g_data_bits.end()) {
        throw std::runtime_error("invalid UART data bits: " + std::to_string(bits));
    }
    auto session = require_session();
    auto lock = lock_or_throw(session, "set_data_bits");
    const int fd   = session->fd;
    termios   term = get_termios(fd);
    term.c_cflag &= ~CSIZE;
    term.c_cflag |= size->second;
    apply_termios(fd, term);
}

void UartImpl::set_stop_bits(uint8_t bits)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return;
    }
    if (bits != 1 && bits != 2) {
        throw std::runtime_error("invalid UART stop bits: " + std::to_string(bits));
    }
    auto session = require_session();
    auto lock = lock_or_throw(session, "set_stop_bits");
    const int fd   = session->fd;
    termios   term = get_termios(fd);
    if (bits == 1) {
        term.c_cflag &= ~CSTOPB;
    } else {
        term.c_cflag |= CSTOPB;
    }
    apply_termios(fd, term);
}

uint32_t UartImpl::get_host_baud_rate(void)
{
    InFlightGuard life{*this};
    (void)life; /* 只依赖 RAII:析构会等本调用退出,closing 时同样返回 0 */
    /* HOST 侧速率对 BMC 不可见;按 bcal 文档“失败返回 0”表示不可用,本端速率走 CMD_GET_BAUD_FROM_TCGETATTR。 */
    return 0;
}

/* “寄存器口径”波特率:用 sysfs uartclk + 8250 分频公式还原;偏差超过 ±2% 时返回实测值。 */
uint32_t UartImpl::get_baud_from_reg(int fd) const
{
    const uint32_t uartclk = read_uint_file("/sys/class/tty/ttyS" + std::to_string(m_index) + "/uartclk");
    if (uartclk == 0) {
        throw std::runtime_error("UART /dev/ttyS" + std::to_string(m_index) + " reports uartclk=0");
    }
    const uint32_t baud = baud_from_termios(get_termios(fd)); /* 内核当前记录的速率 */
    /* divisor 与 8250 的 DIV_ROUND_CLOSEST 同算法,取整误差交给上面的 ±2% 归一吸收。 */
    const uint64_t divisor = std::max<uint64_t>(
        1, (static_cast<uint64_t>(uartclk) + (UART_CLK_DIVISOR / 2) * baud) / (UART_CLK_DIVISOR * baud));
    const uint32_t actual = static_cast<uint32_t>(uartclk / (UART_CLK_DIVISOR * divisor));

    for (const auto& item : g_baud_to_speed) {
        const uint32_t standard = item.first;
        const uint64_t diff     = actual > standard ? actual - standard : standard - actual;
        if (diff * 100 <= static_cast<uint64_t>(standard) * BAUD_SNAP_PERCENT) {
            return standard;
        }
    }
    return actual;
}

int32_t UartImpl::control(uint32_t cmd, void* args_in, void* args_out)
{
    InFlightGuard life{*this};
    if (!life.registered()) {
        return -1;
    }
    switch (cmd) {
        case CMD_OPEN_PORT: {
            if (args_in == nullptr) {
                throw std::runtime_error("UART CMD_OPEN_PORT args_in is null");
            }
            auto*      info       = static_cast<UART_OPEN_PORT_INFO_S*>(args_in);
            check_chan(info->chan, "CMD_OPEN_PORT");

            /* 参数校验必须早于设备操作:非法波特率先 open 再回滚 close 会拉低 DTR,对端误判掉线。 */
            const speed_t speed = baud_to_speed(info->baud);
            if (speed == 0) {
                throw std::runtime_error("unsupported UART baud rate: " + std::to_string(info->baud));
            }

            bool created = false;
            auto session = open_once(&created);
            if (!session) {
                return -1; /* 对象正在析构:不再发布新会话 */
            }
            try {
                if (!apply_format(session, speed)) {
                    throw std::runtime_error("UART CMD_OPEN_PORT session was closed during format");
                }
            } catch (...) {
                if (created) {
                    close_if_current(session);
                }
                throw;
            }
            return 0;
        }
        case CMD_UPDATE_BAUD:
            /* 按互联对象取对端速率依赖 HOST 侧速率与板级编号,本平台无对应;请显式下发速率。 */
            throw std::runtime_error("UART CMD_UPDATE_BAUD is not supported on current platform: "
                                     "use CMD_OPEN_PORT or CMD_UPDATE_BAUD_V2 with an explicit baud rate");
        case CMD_UPDATE_BAUD_V2: {
            if (args_in == nullptr) {
                throw std::runtime_error("UART CMD_UPDATE_BAUD_V2 args_in is null");
            }
            const auto* info = static_cast<UART_UPDATE_BAUD_V2_INFO_S*>(args_in);
            check_chan(info->chan, "CMD_UPDATE_BAUD_V2");
            apply_baud_rate(info->val);
            return 0;
        }
        case CMD_GET_BAUD_FROM_TCGETATTR: {
            if (args_in == nullptr || args_out == nullptr) {
                throw std::runtime_error("UART get baud args is null");
            }
            check_chan(static_cast<CMD_GET_CHAN_IN_S*>(args_in)->chan, "get baud");
            auto session = require_session();
            auto lock    = lock_if_current(session);
            if (!lock) {
                return -1; /* 会话已切换:本次查询无效 */
            }
            /* 内核 termios 记录的速率(“以为”的配置值),不是 HOST 侧速率 */
            static_cast<CMD_GET_BAUD_OUT_S*>(args_out)->baud = baud_from_termios(get_termios(session->fd));
            return 0;
        }
        case CMD_GET_BAUD_FROM_REG: {
            if (args_in == nullptr || args_out == nullptr) {
                throw std::runtime_error("UART get baud args is null");
            }
            check_chan(static_cast<CMD_GET_CHAN_IN_S*>(args_in)->chan, "get baud");
            auto session = require_session();
            auto lock    = lock_if_current(session);
            if (!lock) {
                return -1; /* 会话已切换:本次查询无效 */
            }
            static_cast<CMD_GET_BAUD_OUT_S*>(args_out)->baud = get_baud_from_reg(session->fd);
            return 0;
        }
        case CMD_GET_DATA_BITS_FROM_TCGETATTR:
        case CMD_GET_DATA_BITS_FROM_REG: { /* Aspeed 无用户态寄存器视图,FROM_REG 与 TCGETATTR 等价 */
            if (args_in == nullptr || args_out == nullptr) {
                throw std::runtime_error("UART get data bits args is null");
            }
            check_chan(static_cast<CMD_GET_CHAN_IN_S*>(args_in)->chan, "get data bits");
            auto session = require_session();
            auto lock    = lock_if_current(session);
            if (!lock) {
                return -1; /* 会话已切换:本次查询无效 */
            }
            const termios term = get_termios(session->fd);
            static_cast<CMD_GET_DATA_BITS_OUT_S*>(args_out)->data_bits = data_bits_from_termios(term);
            return 0;
        }
        case CMD_GET_PARITY_FROM_TCGETATTR:
        case CMD_GET_PARITY_FROM_REG: { /* Aspeed 无用户态寄存器视图,FROM_REG 与 TCGETATTR 等价 */
            if (args_in == nullptr || args_out == nullptr) {
                throw std::runtime_error("UART get parity args is null");
            }
            check_chan(static_cast<CMD_GET_CHAN_IN_S*>(args_in)->chan, "get parity");
            auto session = require_session();
            auto lock    = lock_if_current(session);
            if (!lock) {
                return -1; /* 会话已切换:本次查询无效 */
            }
            const termios term = get_termios(session->fd);
            static_cast<CMD_GET_PARITY_OUT_S*>(args_out)->parity = parity_from_termios(term);
            return 0;
        }
        case CMD_GET_STOP_BITS_FROM_TCGETATTR:
        case CMD_GET_STOP_BITS_FROM_REG: { /* Aspeed 无用户态寄存器视图,FROM_REG 与 TCGETATTR 等价 */
            if (args_in == nullptr || args_out == nullptr) {
                throw std::runtime_error("UART get stop bits args is null");
            }
            check_chan(static_cast<CMD_GET_CHAN_IN_S*>(args_in)->chan, "get stop bits");
            auto session = require_session();
            auto lock    = lock_if_current(session);
            if (!lock) {
                return -1; /* 会话已切换:本次查询无效 */
            }
            const termios term = get_termios(session->fd);
            static_cast<CMD_GET_STOP_BITS_OUT_S*>(args_out)->stop_bits = (term.c_cflag & CSTOPB) != 0 ? 2 : 1;
            return 0;
        }
        default:
            throw std::runtime_error("unsupported UART control command: " + std::to_string(cmd));
    }
}

} // namespace BCAL_UART_ASPEED

extern "C" {

__attribute__((visibility("default"))) bcal::IDriver* create_driver(int32_t index)
{
    /* 异常不能穿越 extern "C" 边界,捕获后返回 nullptr,由 bcal 按创建失败处理 */
    try {
        return new BCAL_UART_ASPEED::UartImpl(index);
    } catch (const std::exception& e) {
        std::fprintf(stderr, "[ERROR] uart: create driver(index=%d) failed: %s\n", static_cast<int>(index), e.what());
        return nullptr;
    } catch (...) {
        std::fprintf(stderr, "[ERROR] uart: create driver(index=%d) failed: unknown exception\n",
                     static_cast<int>(index));
        return nullptr;
    }
}

__attribute__((visibility("default"))) void destroy_driver(bcal::IDriver* driver)
{
    delete driver;
}

} // extern "C"