You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux驱动DS1343 SPI片选逻辑疑问:^=还是|= SPI_CS_HIGH?

RTC DS1343驱动SPI模式配置的合理性分析

问题背景

在Linux内核v5.6至v6.10-rc4版本中,drivers/rtc/rtc-ds1343.c的ds1343_probe函数里有一段SPI模式配置代码:

/* RTC DS1347 works in spi mode 3 and
 * its chip select is active high. Active high should be defined as
 * "inverse polarity" as GPIO-based chip selects can be logically
 * active high but inverted by the GPIO library.
 */
spi->mode |= SPI_MODE_3;
spi->mode ^= SPI_CS_HIGH;
spi->bits_per_word = 8;
res = spi_setup(spi);
if (res)
    return res;

存在的核心疑惑:若设备节点已通过spi-cs-high属性正确配置了片选极性(GPIO片选搭配ACTIVE_HIGH配置),spi->mode ^= SPI_CS_HIGH会翻转SPI_CS_HIGH位,破坏原有正确配置。

历史代码问题

在提交3b52093dc917之前,代码采用直接赋值的方式配置SPI模式:

/* RTC DS1347 works in spi mode 3 and
 * its chip select is active high
 */
spi->mode = SPI_MODE_3 | SPI_CS_HIGH;
spi->bits_per_word = 8;
res = spi_setup(spi);
if (res)
    return res;

这段代码的问题是完全覆盖了SPI核心已分配的所有mode标志,会丢失其他必要的配置项(如SPI核心默认设置的其他模式位)。

提交修改说明

该提交的官方修改理由为:

The current use of mode flags to us SPI_MODE_3 and
SPI_CS_HIGH is fragile: it overwrites anything already
assigned by the SPI core. Change it thusly:

  • Just |= the SPI_MODE_3 so we keep other flags
  • Assign ^= SPI_CS_HIGH since we might be active high
    already, and that is usually the case with GPIOs used
    for chip select, even if they are in practice active low.

Add a comment clarifying why ^= SPI_CS_HIGH is the right
choice here.

核心对比:^= SPI_CS_HIGH vs |= SPI_CS_HIGH

硬件特性前提

DS1347硬件本身的片选要求是高电平有效,这是固定硬件特性——无论采用GPIO片选还是硬件SPI片选,最终硬件层面的片选信号必须满足高电平有效才能正常通信。

两种操作的实际影响

  1. spi->mode |= SPI_CS_HIGH:
    强制设置SPI_CS_HIGH位,确保片选高有效,同时保留SPI核心已配置的其他mode标志(如时钟极性、相位之外的其他选项),完全贴合DS1347的硬件需求,不会破坏原有正确配置。

  2. spi->mode ^= SPI_CS_HIGH:
    翻转当前的SPI_CS_HIGH位,如果SPI核心已经根据设备树的spi-cs-high属性设置了正确的高有效位,翻转后会直接变成低有效,违反硬件要求,导致设备无法正常工作。

对提交理由的澄清

提交中提到的“GPIO-based chip selects can be logically active high but inverted by the GPIO library”存在误解:当用户在设备树中配置spi-cs-high属性时,已经明确告知SPI核心片选的硬件极性,GPIO驱动会自动处理电平逻辑,驱动不需要额外翻转SPI_CS_HIGH位。额外的翻转操作反而会抵消正确的配置。

结论

使用spi->mode |= SPI_CS_HIGH才是符合DS1347硬件特性的正确选择,^= SPI_CS_HIGH会在设备节点正确配置的情况下导致错误的片选极性,直接破坏设备功能。

内容的提问来源于stack exchange,提问作者Ian Abbott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:36:05